【问题标题】:Python stuck in while loop while trying to reach a list via inputPython在尝试通过输入到达列表时陷入while循环
【发布时间】:2018-07-31 18:01:34
【问题描述】:

我是 Python 新手,需要您帮助解决以下问题。

  • 假设用户猜测列表中的数字

  • 问题:我不明白如何创建一个循环提示用户输入一个数字,直到输入的数字是列表的一部分。然后循环应该结束。

我已经设法做到了循环永不停止的地步:/

如果你们不仅能告诉我正确的方法,而且能简短地解释我应该如何为列表做循环(而不是用循环创建它们),我将非常感激

  • 代码:

    #Checks if the customer's input is part of the list
    
    lst=[3,6,8,9]
    guess=int(input("Type a number and check if it's part of the list:"))
    
    while guess != lst:
       print("try again")
       guess=int(input("Type a number and check if it's part of the list:"))
    else:
    
       print("Congrats!")
    

    提前致谢!干杯!

【问题讨论】:

  • 整数永远不会等于列表。
  • 改用while guess not in lst:
  • 可能想用guess in lst
  • 感谢大家的快速解答!问题解决了!干杯!

标签: python-3.x list input while-loop


【解决方案1】:

您可以使用 bool True 进行无限循环,并在条件为真时中断循环。

lst=[3,6,8,9]
while True:
  guess=int(input("Type a number and check if it's part of the list:"))
  if guess in lst:
      print("Congrats")
      break
  else:
      print("Try Again")
      continue

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多