Play4Fun
Play4Fun

Reputation: 3

Checking if input value is integer, command, or just bad data (Python)

I'm trying to do something (admittedly) simple. I want my function to take an input, run a few lines if it's an integer or print an error message if it's a string or exit the loop if it's a specific command (done). My problem is that it never detects an integer, instead always displaying the error message unless I'm exiting the loop.

#The starting values of count (total number of numbers) 
#and total (total value of all the numbers)
count = 0
total = 0

while True:
    number = input("Please give me a number: ")
    #the first check, to see if the loop should be exited
    if number == ("done"):
        print("We are now exiting the loop")
        break
    #the idea is that if the value is an integer, they are to be counted, whereas
    #anything else would display in the error message
    try:
        int(number)
        count = count + 1
        total = total + number
        continue
    except:
        print("That is not a number!")
        continue
#when exiting the code the program prints all the values it has accumulated thus far
avarage = total / count
print("Count: ", count)
print("Total: ", total)
print("Avarage: ", avarage)

From poking around a bit with the code, it seems like the problem lies with the (count = count + 1) and (total = total + 1), but I'm unable to see why. Any help greatly appreciated.

Upvotes: 0

Views: 184

Answers (1)

Chris
Chris

Reputation: 16172

You aren't assigning your int(number) to anything, so it remains a string.

Two things you need to do. Change your exception handling to print the actual error, so that you have some clue as to what's going on. This code does the following.

except Exception as e:
    print("That is not a number!", e)
    continue

Output:

That is not a number! unsupported operand type(s) for +: 'int' and 'str'

Which means you are adding a string and an integer together, which you can't do. Looking at your code, you do that at:

try:
    int(number) <------- This is not doing anything for your program
    count = count + 1
    total = total + number

You think it's permanently changing number to an int, so you can use it later, but it's not. It's just for that one line, so you'll need to move it two lines down like this:

try:
    count = count + 1
    total = total + int(number)

Upvotes: 1

Related Questions