while True:
try:
name=str(input("Enter your name="))
age=int(input("Enter your age="))
except ValueError:
print("error!! please enter the values again")
continue
else:
break
current_year=int(input("What is the current year you are living in="))
n=100-age
x=n+current_year
print(name,"",x,"is the year you will turn 100")
So how do I create an error msg for my use if he/she enter a negative number for the age, such that it allows the user to re-input the age.
Add a while
loop which asks if the age is smaller than zero. If this condition is satisfied (the user entered a negative digit), the loop will go on (it will ask for a new input):
while True:
try:
name=input("Enter your name=")
age=int(input("Enter your age="))
while age < 0:
age=int(input("Enter your age="))
current_year=int(input("What is the current year you are living in="))
except ValueError:
print("error!! please enter the values again")
continue
else:
break
n=100-age
x=n+current_year
print(name,"",x,"is the year you will turn 100")
I would try something using a while loop.
while age < 0:
age=int(input("Enter your age="))
if age < 0:
print('try again')
We keep on taking user's age until they enter something above 0.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.