Reputation: 13
age = int(input)
while age > 130 or age < 0:
print('Please print a valid age')
age = int(input())
I am trying to make sure that the user doesn't type a letter and make my program crash. Also, I am trying to ask for a valid age between 0 and 130. If values are outside, a message should come up saying, not a valid age and should proceed to rewind the while statement by asking the user to prompt in different values for age
Upvotes: 0
Views: 596
Reputation: 1434
input()
always considered as string if user inputs non integer it will throw ValueError
which can be handled with try and except block as below:
try:
age = int(input())
while age > 130 or age < 0:
print('Please print a valid age')
age = int(input())
except ValueError:
print('Please print a valid age')
Upvotes: 0
Reputation: 13498
Use a try except to handle non-digit inputs. To keep prompting the user for a valid age until they have inputted one just keep your loop on true and only break it when you get a valid age:
print("Please input a valid age")
while True:
try:
age = int(input())
assert 0 < age < 130
break
except (AssertionError, ValueError):
print("Please input a valid age")
print(age)
If you don't want to use try/excepts you can use .isdigit()
:
print("Please input a valid age")
while True:
age = input()
if age.isdigit() and (0 <int(age)< 130): break
else: print("Please input a valid age")
print(int(age)) #age is valid and you can safely convert to int
Upvotes: 2
Reputation: 354
You can do the following. Can I help you?
def CheckAge(value):
"""Check the user input number"""
return value.isdigit()
def CheckRange(value):
"""Check the number range"""
if int(value) > 0 and int(value) < 130:
return True
while True:
age = input('Please enter your age:')
if CheckAge(age) and CheckRange(ageq):
break
else:
print('Please input a valid age')
Upvotes: 0