+ 1

Please Help: Check if input is a whole number (in Python)

Please help... I found a code from 101computing.net that checks if the input is a number but I would like to ensure that the user's input is a whole number, >= 0 only (no negative numbers) What do I need to include in my code to check if the number is >= 0? Here is the code: #How to make sure the user enters a number (integer) - www.101computing.net def inputNumber(num): while True: try: userInput = int(input(num)) except ValueError: print("Not a valid input! Try again, enter a number.") continue else: return userInput break #MAIN PROGRAM STARTS HERE: age = inputNumber("Enter your age: ") if (age >= 18): print("You are old enough to vote.") else: print("You will be able to vote in " + str(18-age) + " year(s).")

4th Feb 2019, 4:30 PM
Anna
4 odpowiedzi
+ 6
You can use assert to make sure that the input is a whole number >= 0: try: age = int(input('Enter your age: ')) assert isinstance(age, int) and age >= 0 except (ValueError, AssertionError): print('Please enter a valid age.')
4th Feb 2019, 5:10 PM
Anna
Anna - avatar
+ 3
You're welcome 👌😀
4th Feb 2019, 9:02 PM
Anna
Anna - avatar
+ 1
Thank you very much, Anna. We have the same name. :) It worked. I appreciate your help very much. :)
4th Feb 2019, 8:45 PM
Anna
- 1
jkd hashauihhasiuhddd
5th Feb 2019, 6:33 PM
Logan Cummins
Logan Cummins - avatar