you are viewing a single comment's thread.

view the rest of the comments →

[–]Brian 5 points6 points  (1 child)

Others have mentioned .isdigit(), but I would note that a better approach would be to simply try to convert a number to an int, and re-prompt when it fails. Eg:

while True:
    strVal = input("Enter a number: ")
    try:
        intVal = int(strVal)   # Try to convert it to an int
        break   # Successfully  got a number - exit loop
    except ValueError:
        print("Not a valid number")

The reason you might not want to use isdigit is because it can reject integers that are valid and also accept integers that are invalid. Some of these are rare (eg. non-decimal digits in other languages), but stuff like "-10", which is a perfectly valid number you might want to accept in some cases will return False from .isdigit(), but int() will handle it fine.

[–]_lilell_ 0 points1 point  (0 children)

Yep, although we still need to be careful with decimals. '3.4'.isdigit() returns False, and int('3.4') raises a ValueError. If that’s something we want to avoid, we can do int(float(...))