Ruby Ruby - 3 years ago 132
Python Question

Python 2.7.10 Checking if an input is an integer using int()

i am new to python and am currently trying to write a piece of code for a maths quiz to ensure the user inputs an integer for the answer without the program crashing . i have tried to do this

user_answer=raw_input("enter your answer:")
while user_answer!=int(user_answer):
user_answer=raw_input("please enter an integer")

but it always crashes when I run it and says

ValueError: invalid literal for int() with base 10:

Is there a way to use
to check if my string is an integer?Thanks

Answer Source

Your raw input is a str. str will never equal an int. Do your validation in a try...except

    user_answer = int(user_answer)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download