gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:12:35 25 4
gpt4 key购买 nike

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

关于python - 在不使用 break 的情况下跳出 python 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19773965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com