掷骰子程序的无限while循环问题

2024-05-29 03:49:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我为一个项目做了这段代码,我遇到了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')

Tags: or项目代码inputifrandomdiceyes
3条回答

您的else语句是未缩进的(在循环之外),因此永远不会重置其中的变量,因此while循环需要的条件始终是True,因此是一个无限循环。你只需要缩进这个:

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

只有当roll_agn在循环内变成非“yes”时,才会执行while的else块。你永远不会在while循环中改变它,所以它永远循环。在

正如其他人所指出的那样,你的压痕消失了。下面是一些关于如何进一步改进代码的建议

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')

无论玩家进入什么地方,这都是有效的。在

相关问题 更多 >

    热门问题