程序停留在while循环但不运行程序?

时间:2014-03-03 14:27:24

标签: python while-loop

这是螃蟹模拟器。我的while循环遇到了麻烦。在哪里说

while val == True:

问题出在哪里。它保持在while循环中但没有任何反应。如果您发现任何事情,我将非常感激。 这是完整的代码。 (我试图验证一切)

import time
import random
control1 = False
control2 = True
x = True
val = True
z = True
def throw(n):
    for i in range(1,n+1):
        dice_1 = random.randint(1,6);dice_2 = random.randint(1,6)
        print "roll",i,", die 1 rolled",dice_1,"and die 2 rolled",dice_2,",total",dice_1+dice_2
        time.sleep(2)
    return n

while z == True:
    if x == True:
        while control1 == False:
            try:
                amount_1 = int(raw_input("Welcome to crabs.\nHow many times would you like to roll:"))
                control1 = True
            except ValueError:
                print ("Enter a valid number.")
            throw(amount_1)
            x = False
    else:
        while val == True:
            roll_again = raw_input("Would you like to roll again: ")
            if roll_again == "1":
                val = False
                while control2 == True:
                    try:
                        amount_2 = int(raw_input("How many times would you like to roll:"))
                        control2 = False
                    except ValueError:
                        print ("Enter a valid number.")
                    throw(amount_2)
                    z = True
            elif roll_again == "2":
                val = False
                exit()
            else:
                val = True

3 个答案:

答案 0 :(得分:2)

首次浏览该计划后xval都是False,但z仍为True。结果,外环继续滚动。

答案 1 :(得分:0)

把这一行:

print z, x, val

在声明之下。

在您回复“你想再次滚动:”问题“2”后,您会看到xval都是错误的。这意味着它将遍历if..else语句的每个部分,并且无限循环。

答案 2 :(得分:0)

执行else分支(if x)之后,它停留在无限循环中,因为您将值设置为False。然后在下一次迭代中说while val == True,因为这个语句不是False,并且有 no 其他语句需要考虑,所以你在无限循环中运行。

要了解我的意思,只需在此处添加打印声明:

else:
    print val
    while val == True:
        roll_again = raw_input("Would you like to roll again: ")
        if roll_again == "1":

现在,我不知道你的实际节目是否需要所有布尔值,但是如果我要使它工作,我就会开始消除我不需要的布尔值。我认为你的结构过于复杂。

修改: 这是一个使程序更简单的建议。

import time
import random
x = True
z = True
def throw(n):
    for i in range(1,n+1):
        dice_1 = random.randint(1,6);dice_2 = random.randint(1,6)
        print "roll",i,", die 1 rolled",dice_1,"and die 2     rolled",dice_2,",total",dice_1+dice_2
        time.sleep(2)
    return n


def ask(x):
    if x: 
        print "Welcome to crabs."
    try:
        amount = int(raw_input("How many times would you like to roll:"))
    except ValueError:
        print ("Enter a valid number.")
    throw(amount)

while z:
    ask(x)
    x = False
    roll_again = raw_input("Would you like to roll again: ")
    if roll_again == "1":
        continue
    else:
        break