如何在Python中跳出while循环?

40

我必须为我的电脑课程制作这个游戏,但是我无法弄清如何打破这个循环。你看,我必须和“电脑”对战,通过掷出更大的数字并查看谁得分更高来进行比赛。但是我不知道如何从自己的回合中“退出”,并转入电脑的回合。我需要在“Q”(退出)信号的指示下开始电脑的回合,但我不知道如何做到。

ans=(R)
while True:
    print('Your score is so far '+str(myScore)+'.')
    print("Would you like to roll or quit?")
    ans=input("Roll...")
    if ans=='R':
        R=random.randint(1, 8)
        print("You rolled a "+str(R)+".")
        myScore=R+myScore
    if ans=='Q':
        print("Now I'll see if I can break your score...")
        break

使用break的方式是可以的,但你必须准确地输入Q。例如,小写字母q是不行的。第一行代码应该是ans=('R')吗?但无论如何你都不需要它。 - John La Rooy
5个回答

26

有几个变化意味着只有一个 Rr 会滚动,任何其他字符都会退出。

import random

while True:
    print('Your score so far is {}.'.format(myScore))
    print("Would you like to roll or quit?")
    ans = input("Roll...")
    if ans.lower() == 'r':
        R = np.random.randint(1, 8)
        print("You rolled a {}.".format(R))
        myScore = R + myScore
    else:
        print("Now I'll see if I can break your score...")
        break

2
请纠正我- break 会发送一个False信号来停止 while 循环? - SIslam
6
有点儿类似。break 命令可以停止 while 循环,但它没有“假信号”,while 循环的意思是“当跟随 while 语句后面的表达式求值为 True 时循环”,因此如果 while 后面的内容本身就是 True,那么 while 将无限循环;break 命令的意思是“立刻停止循环”,可以用于任何类型的循环,包括 while 循环和 for 循环。 - Westcroft_to_Apse

13

我的做法是运行循环直到答案是Q

ans=(R)
while not ans=='Q':
    print('Your score is so far '+str(myScore)+'.')
    print("Would you like to roll or quit?")
    ans=input("Roll...")
    if ans=='R':
        R=random.randint(1, 8)
        print("You rolled a "+str(R)+".")
        myScore=R+myScore

10

不要使用while True和break语句,这是糟糕的编程风格。

想象一下,当你来调试别人的代码时,在第一行看到while True,然后不得不沿着其他200行代码翻找15个break语句,为了每一个都必须阅读数行代码才能弄清楚它是如何到达break语句的。你会非常气愤。

导致while循环停止迭代的条件应该始终在while循环代码本身的行中清晰明了,无需查看其他位置的代码。

Phil提供的“正确”解决方案,在while循环语句本身中有一个明确的结束条件。


4
ans=(R)
while True:
    print('Your score is so far '+str(myScore)+'.')
    print("Would you like to roll or quit?")
    ans=input("Roll...")
    if ans=='R':
        R=random.randint(1, 8)
        print("You rolled a "+str(R)+".")
        myScore=R+myScore
    else:
        print("Now I'll see if I can break your score...")
        ans = False
        break

1

海象运算符(添加到Python 3.8的赋值表达式)和while循环else子句可以更加Pythonic:

myScore = 0
while ans := input("Roll...").lower() == "r":
    # ... do something
else:
    print("Now I'll see if I can break your score...")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接