【问题标题】:Issues with While Loop in Python 3 - loop breaks when it should repeat [duplicate]Python 3 中的 While 循环问题 - 当它应该重复时循环中断 [重复]
【发布时间】:2016-10-02 10:09:53
【问题描述】:

我目前正在开发一个用 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 的类似问题。

【问题讨论】:

    标签: python python-3.x if-statement input while-loop


    【解决方案1】:

    问题是那些行:

    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
    

    【讨论】:

    • 效果很好,非常感谢!
    【解决方案2】:

    改变

    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

    【讨论】:

    • 效果很好,非常感谢。发布的两个答案相差一分钟并且具有相同的解决方案,因此我将另一个答案作为解决方案进行了检查,但仍然感谢!
    猜你喜欢
    • 1970-01-01
    • 2021-01-03
    • 2019-02-01
    • 2011-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    相关资源
    最近更新 更多