如何在Python中打破while循环?

Nin*_*nja 23 python break while-loop

我必须为我的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
Run Code Online (Sandbox Code Playgroud)

Joh*_*ooy 13

一些变化意味着只有一个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
Run Code Online (Sandbox Code Playgroud)

  • @SIslam 那种。`break` 停止了 `while` 循环,但没有“假信号”:`while` 表示“循环,而 `while` 语句之后的表达式计算结果为 True”,所以如果 `while` 之后的内容是`True` 本身,`while` 将永远循环;`break` 的意思是“立即停止循环”并且可以工作任何循环,包括 `while` 和 `for` 循环。 (5认同)
  • 如果需要,请纠正我——break 发送一个 False 信号来停止 while 循环? (2认同)

小智 10

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

想象一下,你来调试别人的代码,在第 1 行看到 while True,然后必须仔细浏览另外 200 行代码,其中有 15 个 Break 语句,必须阅读无数行代码才能解决每一行问题到底是什么导致了它的崩溃。你很想杀掉他们……很多。

导致 while 循环停止迭代的条件应始终从 while 循环代码行本身中清除,而无需在其他地方查找。

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


Phi*_*hil 7

我要做的是运行循环,直到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
Run Code Online (Sandbox Code Playgroud)


aug*_*uag 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
Run Code Online (Sandbox Code Playgroud)