简体   繁体   中英

Nesting if/else statement in while loop

This is a text adventure game. The user is faced with the first scenario a() . If they choose 2, the game continues. If they choose 1, they die and are presented with the option to play again. Not sure what I'm doing wrong here.

"""
MAIN LOOP
"""
play_again = "yes"
while play_again == "yes" or play_again == "y":
    a()  # user makes a choice
    choice = choose_ans()
    check_ans_a(choice)  # intention: if user chooses "1", they die and are asked to play again
        if choice == "1":  # problem: Unexpected indent. If indent is deleted, b() becomes unreachable
            play_again = input('Play again?\n'
                               '(y)es ')
            break
        else:
            continue
    b()
    choice = choose_ans()
    check_ans_b(choice)

EDIT: The solution, derived from comments below, was simple:

"""
MAIN LOOP
"""
play_again = "yes"
while play_again == "yes" or play_again == "y":
    a()  # user makes a choice
    choice = choose_ans()
    check_ans_a(choice)
        if choice == "1"  # player dies
            play_again = input('Play again?\n'
                               '(y)es ')
            continue  # restarts loop
    b()
    choice = choose_ans()
    check_ans_b(choice)

The problem is your else: continue . If the code enters the if block, it will break out of the while loop. But if the condition isn't met, the else block will be entered. Inside a while loop, continue will automatically go to the top of the loop and start again, which is why b() is never reached.

The problem is the continue. Continues makes the code "jump" to the start of the while loop again. Suggestion: delete the else/continue part. If there are only these two options it's not needed. If a==1 the break will leave the while loop. if its 2 a==2 is not True therefore the part after it (b) will be tested.

https://www.tutorialspoint.com/python3/python_continue_statement.htm

Try run this version of your code for debug purpose, comment/uncomment to see how the result changes. I used random to simulate the user input getting rid of the method calls.

import random

play_again = "yes"
while play_again == "yes" or play_again == "y":
    choice = random.choice(["1","2"])
    print('choice = choose_ans()', choice)
    if choice == "1":
        play_again = random.choice(["yes","no"])
        print('play_again?', play_again)
        # break # <-- the break control is already made by while condition
    # else:
    #     continue
    # b()
    choice = random.choice(["1","2"])
    print('check_ans_b(choice)', choice)

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