骰子滚动程序上的无限循环问题

时间:2014-04-01 19:00:23

标签: python python-3.x random while-loop dice

我为一个项目制作了这个代码,我遇到了while循环的问题,因为它只是重复第一个输入函数,这里是代码,如果有人可以指出我的问题并帮助我,我会预测它修复我的代码,thnx

import random
roll_agn='yes'
while roll_agn=='yes':
    dice=input ('Please choose a 4, 6 or 12 sided dice: ')
    if dice ==4:
        print(random.randint(1,4))
    elif dice ==6:
        print(random.randint(1,6))
    elif dice ==12:
        print(random.randint(1,12))
    else:
        roll_agn=input('that is not 4, 6 or 12, would you like to choose again, please answer yes or no') 
    if roll_agn !='yes':
        print ('ok thanks for playing')

3 个答案:

答案 0 :(得分:1)

只有当roll_agn变为非 - '是'时,才会执行while块的else块。在循环内。你永远不会在while循环中改变它,所以它永远循环。

答案 1 :(得分:0)

你的else语句没有缩进(在循环之外),所以内部的变量永远不会重置,因此while循环所需的条件总是True,因此无限环。你只需要缩进这个:

elif dice ==12:
     ...
else:
^    roll_agn = input()

答案 2 :(得分:0)

其他人指出,你的缩进已经消失了。以下是有关如何进一步改进代码的一些建议

import random


while True:
    try:
        dice = int(input ('Please choose a 4, 6 or 12 sided dice: '))  # this input should be an int 
        if dice in (4, 6, 12):  # checks to see if the value of dice is in the supplied tuple
            print(random.randint(1,dice))
            choice = input('Roll again? Enter yes or no: ')
            if choice.lower() == 'no':  # use .lower() here so a match is found if the player enters No or NO
                print('Thanks for playing!')
                break  # exits the loop
        else:
            print('that is not 4, 6 or 12')
    except ValueError:  # catches an exception if the player enters a letter instead of a number or enters nothing
        print('Please enter a number')

无论玩家进入什么状态,这都会有效。