【问题标题】:infinite while loop issue on dice roll program掷骰子程序的无限while循环问题
【发布时间】:2014-05-12 17:48:08
【问题描述】:

我已经为一个项目编写了这段代码,我在 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')

【问题讨论】:

  • 将你的else:缩进到while循环中,它会解决问题。

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


【解决方案1】:

只有当 roll_agn 在循环内变为非“是”时才会执行 while 的 else 块。您永远不会在 while 循环中更改它,因此它会永远循环。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      正如其他人指出的那样,您的缩进已关闭。以下是一些关于如何进一步改进代码的建议

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

      无论玩家输入什么,这都会起作用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-16
        • 2014-05-12
        • 2013-12-15
        • 2014-02-28
        相关资源
        最近更新 更多