Python Forum
[split] Very basic coding issue - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: [split] Very basic coding issue (/thread-27329.html)



[split] Very basic coding issue - aary - Jun-03-2020

age = int(input('please enter your age: '))
try:
    if age > 0:
        print("You are", age, "years old!")
    elif age > 90:
        print('you are too old!')
except:
    print('that can\'t be your age')



RE: [split] Very basic coding issue - Yoriz - Jun-03-2020

Did you have a question?


RE: [split] Very basic coding issue - buran - Jun-03-2020

Maybe you want to swap the if and elif - first check if age > 90 and then elif age > 0


RE: [split] Very basic coding issue - pyzyx3qwerty - Jun-03-2020

age = input('please enter your age: ')
while True : 
    try:
        age = int(age)
        if age > 0 and age < 90:
            print("You are", age, "years old!")
            break
        elif age > 90:
            print('you are too old!')
            break
    except ValueError:
        print('that can\'t be your age')
        break
3 different outputs :
Output:
please enter your age: g that can't be your age
Output:
please enter your age: 99 you are too old!
Output:
please enter your age: 10 You are 10 years old!



RE: [split] Very basic coding issue - buran - Jun-03-2020

actually it's better to have minimal number of lines in the try block, i.e. where you expect the error. Also, the input must be inside the loop (otherwise, why would you have a loop at all, if you break out in any case):
while True :
    age = input('please enter your age: ')
    try:
        age = int(age)
    except ValueError:
        print('that can\'t be your age')
        continue
    if age > 0 and age < 90:
            print("You are", age, "years old!")
    elif age > 90:
        print('you are too old!')
    break
or using else

while True :
    age = input('please enter your age: ')
    try:
        age = int(age)
    except ValueError:
        print('that can\'t be your age')
    else:
        if age > 0 and age < 90:
                print("You are", age, "years old!")
        elif age > 90:
            print('you are too old!')
        break