0

I'm trying to figure out how to handle the problem with wrong values in Python.

There is such a case - somebody need to give Name, surname and age and for example in the case of age he is giving strings. I want to print that he is not giving a number and push him to give another one and check if it is int() so I can put it to the final print() at the bottom of the code. I guess I need to give the same exceptions to name and surname but in other direction. Please help me go through this I spend entire day to find out how to solve it and couldn't find the answer..

name=input('give name: ')
surname=input('give surname: ')
full_name= name + " " + surname
wiek=input('age: ')

try:
    age = int(age)
except ValueError as e:
    print("It is not a number! Try again..";age)



print("Hi "+ full_name + "!\nAfter 50 years you will have " + str(age+50) + " years")

Regards, zupa

1 Answers1

1

You were close. You have to wrap the try block inside while loop to try until you succeed:

age = None
while age is None:
    try:
        age = int(input("age:"))
    except ValueError as e:
        print("It is not a number! Try again..", age)

RafalS
  • 5,834
  • 1
  • 20
  • 25