I have written a script in Python and I want to make it so if you don't input a number when it asks "What's your age?" It will say "Please input a number" and then repeat the original question. I have tried many different suggestions I have seen on other posts but none of them are working.
Here is the script:
yesorno = "yes"
while yesorno == "yes" :
import time
Age = 0
Age = int(input("What is your age?"))
Age = Age*365*24
print(Age)
yesorno = input("Would you like to run again?(yes/no)")
while yesorno != "no" :
print("Please input yes or no")
yesorno = input("Would you like to run again?(yes/no)")
while yesorno == "no" :
print("Program stopping...")
import sys
sys.exit("Program stopping...")
There are many ways to do this, but allow me to recommend one that adds to your existing code, focusting on this line:
Age = int(input("What is your age?"))
As you probably already know, if the person inputs something that isn't an integer, this line throws an error.
You can catch these errors in a try...except... block, excepting the error that's thrown when any non-int is inputted in that line.
try:
Age = int(input("What is your age?"))
except ValueError:
print("Please input a number")
To make this continue the loop, I'd put the yesorno
in the try statement so it only executes if the Age input was successful, otherwise, react as if the user inputted yes, as so:
try:
Age = int(input("What is your age?"))
Age = Age*365*24
print(Age)
yesorno = input("Would you like to run again?(yes/no)")
except ValueError:
print("Please input a number")
yesorno = "yes"
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments