ValueError: invalid literal for int () with base 10

I created a program in which the user enters a number, and the program will count up to that number and display how much time it took. However, when I enter letters or decimals (i.e. 0.5), I get an error. Here is the complete error message:

Traceback (most recent call last):
  File "C:\Documents and Settings\Username\Desktop\test6.py", line 5, in <module>
    z = int(z)
ValueError: invalid literal for int() with base 10: 'df'

What can I do to fix this?

Here is the complete code:

import time
x = 0
print("This program will count up to a number you choose.")
z = input("Enter a number.\n")
z = int(z)
start_time = time.time()
while x < z:
    x = x + 1
    print(x)
end_time = time.time()
diff = end_time - start_time
print("That took",(diff),"seconds.")

Please, help!

+3
source share
2 answers

Well, there really is a way to β€œfix” this, it behaves as expected - you cannot write a letter in int, which really does not make sense. Best of all (and this is a pythonic way of doing things), just write a function using try ... except block:

def get_user_number():
    i = input("Enter a number.\n")
    try:
        # This will return the equivalent of calling 'int' directly, but it
        # will also allow for floats.
        return int(float(i)) 
    except:
        #Tell the user that something went wrong
        print("I didn't recognize {0} as a number".format(i))
        #recursion until you get a real number
        return get_user_number()

Then you replace the following lines:

z = input("Enter a number.\n")
z = int(z)

with

z = get_user_number()
+8

if string.isdigit(z):

, .

, int() , .

EDIT: , wooble , :

try: 
    int(z)
    do something
except ValueError:
    do something else
+1

All Articles