首页 文章

Python 3中While循环的问题 - 当它应重复[重复]时循环中断

提问于
浏览
0

这个问题在这里已有答案:

我目前正在研究用Python 3.5编写的Yahtzee游戏 . 我已经定义了一个函数,要求用户输入将要播放的人的姓名,然后再检查这是否正确 .

def get_player_names():

   while True:
      print("Who are playing today? ")

      players = [str(x) for x in input().split()]

      n = len(players)

      if n == 1:
          for p in players:
              print("So", p, "is playing alone today.")

          choice = input("Is this correct?(y/n)\n")

          if choice == "y" or "Y":
              break
          elif choice == "n" or "N":
              continue
          else:
              print("You should enter either y/Y or n/N")
              continue

      elif n > 1:
          print("So today, ", n, " people are playing, and their names are: ")

          for p in players:
              print(p)

          choice = input("Is this correct?(y/n)\n")

          if choice == "y" or "Y":
              break
          elif choice == "n" or "N":
              continue
          else:
              print("You should enter either y/Y or n/N")
              continue

      else:
          print("Sorry, but at least one person has to participate")
          continue

  placeholder()


def placeholder():
  print("KTITENS")

get_player_names()

该程序创建没有问题的玩家列表,以及当用户确认玩家的名字是正确的时,此时循环中断并且调用下一个函数 . (目前这只是打印KITTENS的功能 . 问题是如果用户输入“n”/“N”或其他东西,我希望循环重复,但它会中断 .

希望有人可以帮助我!抱歉,如果这个问题是重复的,但我找不到有关Python 3的类似问题 .

2 回答

  • 2

    问题是那些线:

    if choice == "y" or "Y":
        break
    elif choice == "n" or "N":
        # Some stuff
    

    应该是:

    if choice == "y" or choice == "Y":
        break
    elif choice == "n" or choice == "N":
        # Some stuff
    

    实际上, or "Y" 始终为真,因此始终会调用 break .

    您可以在python控制台中输入以下内容来检查:

    >>> if 'randomstring': print('Yup, this is True')
    Yup, this is True
    
  • 4

    更改

    if choice == "y" or "Y":
              break
          elif choice == "n" or "N":
              continue
    

    if choice == "y" or choice =="Y":
              break
          elif choice == "n" or choice =="N":
              continue
    

    'Y' 是非空字符串,因此 bool('Y') 始终为 True

    你可以在这里阅读Truth Value Testing

相关问题