如何在Python中打破while循环?

时间:2013-01-30 00:13:08

标签: 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("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

5 个答案:

答案 0 :(得分:10)

一些更改意味着只会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

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分:0)

在True和break语句中不使用。这是不好的编程。

想象一下,您来调试其他人的代码,并且在第1行上看到一会儿True,然后不得不通过其中包含15条break语句的另外200行代码进行拖网操作,而每条代码必须读取不计其数的代码行找出实际上导致它崩溃的原因。您想杀死他们……很多。

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

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

答案 4 :(得分:0)

Walrus operator(添加到 python 3.8 的赋值表达式)和 while-loop-else-clause 可以做得更像 Python:

$ echo $LS_COLORS | tr : \\012 | egrep '^(or|mi)'
or=01
mi=01