简体   繁体   中英

Break Program whilst in a while true - try and except

I need my program to break if the user inputs 'no'. At the moment, the program will not break, and when 'no' is inputed, the try and except restarts

while final_answer_check == True:

try:
    final_answer = str(input("Do you want a copy of the answers?"))
    if final_answer.lower() == "no":
        final_answer_check = False

I'd expect the program to break, but it just asks "Do you want a copy of the answers?" again

Continuing from the comments, this should do:

final_answer_check = True   # a boolean flag 

while final_answer_check:    # while the flag is set to true
    try:
        final_answer = str(input("Do you want a copy of the answers?"))
        if final_answer.lower() == "no":
            final_answer_check = False
    except:
        pass

EDIT :

A better approach however could be to use a infinite loop with a break :

while True:
    try:
        final_answer = input("Do you want a copy of the answers?")
        if final_answer.lower() == "no":
            break
    except:
        pass

OUTPUT :

Do you want a copy of the answers?no

Process finished with exit code 0

First, you need to define the variable final_answer_check and set the value into True . If you build your code in a block of try...except , you need to make it complete, not only try .

final_answer_check = True
while final_answer_check == True:
    try:
        final_answer = str(input("Do you want a copy of the answers?"))
        if final_answer.lower() == "no":
            final_answer_check = False
        else:
            final_answer_check = True
    except:
        print ("your another code should be here")

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