简体   繁体   中英

python, how to quit while loop when answer is wrong

i just started with python. in my code i asked for the user age. if he is younger than 18 i want to quit the program and not just ask the question again. how do i do this?

i tried break, breakpoint, quit, systemexit, system error..

a = 3
while a < 4:
    print ("age: ")
    age = input()

    age = int(age)



    if (age >= 18):
        print("welcome")
        a = a + 3
    else:
        print("too young")
        SystemExit
        exit
        break
        quit

print("oi")

the program asks the question again and again.

You need to control while with a boolean and make it false if the value is less and break :

check = True
while check:
    age = int(input("age: "))

    if (age < 18):
        print('too young')
        check = False
        break
    else:
        print("welcome")

Your if statement isn't indented properly. It needs to be under the while loop. If you want another way to continuously ask the user for their age and if they're too young then exit the program:

   import sys

   while True:    
       age = int(input('Enter your age'))

       if age < 18:
           sys.exit('You are too young')

I think you may want to either use sys.exit() as other have suggested above, or you could try using a boolean value to be the condition for the 'while' loop.

oldEnough = True
while oldEnough == True:
    age = int(input("Age: "))
    if age > 17:
        print ("Welcome")
        oldEnough = True;
        a += 3

    elif age < 18:
        print ("Too young")
        oldEnough = False
        break; # just for good measure.

I hope this works for you. Good luck!

You may want to try something like this

while True:
    age = input("Input your age: ")
    age = int(age)
    if age >= 18:
        print("welcome")
        break
    else:
        print("too young")
        exit(0)  # exit code 0 means everything is ok, exit with a diff code to indicate an issue

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM