如何在Python中突破while循环?

如何在Python中突破while循环?,python,while-loop,break,Python,While Loop,Break,我必须为我的comp班制作这个游戏,我不知道如何打破这个循环。看,我必须和“计算机”对抗,通过滚动更大的数字,看看谁得分更高。但我不知道如何“打破”我的轮换,并过渡到电脑轮换。我需要“Q”(退出)来表示计算机开始转向,但我不知道怎么做 ans=(R) while True: print('Your score is so far '+str(myScore)+'.') print("Would you like to roll or quit?") ans=input("

我必须为我的comp班制作这个游戏,我不知道如何打破这个循环。看,我必须和“计算机”对抗,通过滚动更大的数字,看看谁得分更高。但我不知道如何“打破”我的轮换,并过渡到电脑轮换。我需要“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

我要做的是运行循环,直到ans为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

几个更改意味着只有
R
R
将滚动。任何其他角色都将退出

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

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

想象一下,你来调试其他人的代码,在第1行看到一段时间是真的,然后不得不拖拽另外200行代码,其中包含15个break语句,每行都必须阅读无数行代码,以找出导致代码出现中断的真正原因。你会想杀了他们…很多

导致while循环停止迭代的条件应该始终从代码本身的while循环行中清除,而不必查看其他地方

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

(python 3.8中添加了赋值表达式),并且可以做得更像python:

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

使用
break
的方式很好,但必须准确地键入
Q
<例如,code>q不起作用。第一行应该是
ans=('R')
?你根本不需要它,如果需要请纠正我-break发送了一个错误信号来停止while循环?@SIslam
break
停止
while
循环,但没有“假信号”:
while
表示“while语句后面的表达式计算为True时循环”,因此如果
while
之后的内容是
True
本身,
while
将永远循环
break
表示“立即停止循环”,可用于任何循环,包括
while
for
循环。
myScore = 0
while ans := input("Roll...").lower() == "r":
    # ... do something
else:
    print("Now I'll see if I can break your score...")