Skip to main content
 首页 » 编程设计

python之在不使用 break 的情况下跳出 python 循环

2025年05月04日1798°冷暖

while answer  == 'Y': 
    roll = get_a_roll() 
    display_die(roll) 
    if roll == first_roll: 
        print("You lost!") 
    amount_won = roll 
    current_amount = amount_earned_this_roll + amount_won 
    amount_earned_this_rol = current_amoun 
    print("You won $",amount_won) 
    print(  "You have $",current_amount) 
    print("") 
    answer = input("Do you want to go again? (y/n) ").upper() 
 
 
if answer == 'N': 
    print("You left with $",current_amount) 
else: 
    print("You left with $",current_amount) 

这里使用此循环的目的是在游戏中掷骰子,并且根据掷骰的次数获得奖励,除非您掷的骰子与第一次掷骰相匹配。现在,如果发生这种情况,我需要循环停止,而且我知道这很容易使用 break 语句实现,但是,我被告知不允许使用 break 语句。如果 roll == first_roll,我还能如何让循环终止?

请您参考如下方法:

您可以:

  • 使用标志变量;您已经在使用一个,只需在此处重复使用即可:

    running = True 
    while running: 
        # ... 
        if roll == first_roll: 
            running = False 
        else: 
            # ... 
            if answer.lower() in ('n', 'no'): 
                running = False 
            # ... 
    
  • 从函数返回:

    def game(): 
        while True: 
            # ... 
            if roll == first_roll: 
                return 
            # ... 
            if answer.lower() in ('n', 'no'): 
                return 
            # ... 
    
  • 引发异常:

    class GameExit(Exception): 
        pass 
     
    try: 
        while True: 
            # ... 
            if roll == first_roll: 
                raise GameExit() 
            # ... 
            if answer.lower() in ('n', 'no'): 
                raise GameExit() 
            # ... 
    except GameExit: 
        # exited the loop 
        pass