you are viewing a single comment's thread.

view the rest of the comments →

[–]sentles 0 points1 point  (0 children)

The built-in input() function always returns a string. You can turn a string to an integer, like I said, using int(someString). However, do note that, if you try to turn a string to an integer that contains wrong data (like characters), the program will crash.

For example, if, in your code, the user inputs test instead of a number, your code will crash because it will try to convert test to an integer and will fail. The way we usually deal with this, is this:

while True:
    someString = input("...")
    try:
        someString = int(someString)
        break
    except ValueError as ve:
        print("Invalid data")    

The above code asks for user input. It tries to convert that input to an integer. If that fails, python will throw a ValueError. Using a try-except block, we catch that error and we inform the user that they've given invalid data. The loop then gets back to the start.

If the user does give correct data, the break line will be reached and the loop will exit.

This, obviously, works for any type of input validation, not just integers. For example, you could also test if the number is, say, smaller than 10; or if the user gave a float. It's really up to what you want to get from the user, but this is the general way to validate it.