Use the built-in input()
function to read input from the user. (If you
are using Python 2, use raw_input()
instead.) These functions return a
string, so you will have to cast the returned value to an integer with the
built-in int()
function. If the user entered an invalid number, this will
raise a ValueError
that you can catch. Here is an example:
string_input = input("Enter a number: ")
try:
number = int(string_input)
print(number)
except ValueError:
print("That was no number!")
And here's the result of running it:
$ python3 int.py
Enter a number: 88
88
$ python3 int.py
Enter a number: asdf
That was no number!
You can embed the whole thing in a while
loop and break out only once a
valid number was entered.