Home > Mobile >  I am running into a Name error when I convert a string input to an int
I am running into a Name error when I convert a string input to an int

Time:07-30

I am very new to python and programming as a whole. I recently took up a python beginners course and got an assignment that I am having difficulties with, the assignment will be posted below.

"Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below."

I am currently trying to convert a string input to an int so I can compare it with a none type, when I do this I get a name error. Both the code and the error will be posted below

I am aware that there is a multitude of issues in this code and if you spot something feel free to let me know. Here is my code, please go easy on me.

Code:

Largest = None
smallest = None
while True:
    try:
        Numbers = int(input("Enter A number: "))
        if Numbers == ('done'):
            break
    except:
        print ('invalid number')
    for Numbers in [Numbers]:
        if Largest is None:
            Largest = Numbers
        elif Numbers > Largest:
            Largest = Numbers
        if smallest is None:
            smallest = Numbers
        elif Numbers < smallest:
            smallest = Numbers
print (Largest)
print (smallest)

Error:

C:\Users\Noah\Desktop\py4e>throw_away.py
Enter A number: f
invalid number
Traceback (most recent call last):
  File "C:\Users\Noah\Desktop\py4e\throw_away.py", line 10, in <module>
    for Numbers in [Numbers]:
NameError: name 'Numbers' is not defined

CodePudding user response:

This happens because, when you have an error, you go into your except clause, but you then move right on into processing your numbers. Because there was an error, the Numbers variable was not created.

You need a continue in your except clause.

By the way, for Numbers in [Numbers]: is wrong in several ways. First, you should not have the loop variable be the same as the thing you are iterating. Next, Numbers is not a list -- it's a single number. So, you don't need a for loop at all. Just delete that line.

CodePudding user response:

You need to rewrite your script to make it work:

# In order to keep track of all numbers typed by the user,
# we will use this list. It needs to be allocated just once
# before the main loop begins.
Numbers = []

# Start the main loop
while True:
    try:
        # Ask for the user input
        num = input("Enter A number: ")

        # Before converting it to an integer, check if the input
        # is the string 'done'
        if num == ('done'):
            # If it is, break the loop.
            break

        # Otherwise, try to convert it to a number
        else:
            num = int(num)

    # In any case, if int(num) fails, this exception will be
    # catched and this block will execute instead
    except:
        print ('invalid number')

    # If no exceptions were raised, then it means everything is
    # normal.
    #
    # Append the user input converted to a number to the list.
    else:
        Numbers.append(num)

# When outside of the loop, check if the list is empty.
if (len(Numbers) == 0):
    print('No numbers were recorded. List is empty.')

# If its not empty, find the minimum and maximum number, and
# print them on the screen.
else:
    print ('MAX: ', max(Numbers))
    print ('MIN: ', min(Numbers))

NOTE: There are other ways to write this script and get the same output. This is one of many ways to solve your problem. There are ways to make this script even faster by taking out the min and max functions and using the smallest and Largest variables from your script. That's an exercise for you if you're curious about it.

  • Related