【问题标题】:Simple Beginner Loop Wont Close简单的初学者循环不会关闭
【发布时间】:2022-01-25 23:20:15
【问题描述】:

练习了一些东西,我已经超越了这个简单的概念,但是这个循环不会关闭,我不明白为什么。

ans = "Y"

while ans == "Y" or "y": 
    num = int(input("What's your number? "))
    if num % 2 == 0:
        print("That number is even!\n")
    else:
        print("That number is odd!\n")
    ans = str(input("Do you have another number, Y/y or N/n? "))

所以我先声明变量,这样我就可以进入循环,然后在尾部再次请求它以将其关闭......但无论我输入什么,它都会继续。

我确定这很简单,就像我说我已经通过这种事情但它不会关闭并且我不确定问题是什么?

【问题讨论】:

  • 不应该是ans == “Y”还是ans == “y”?我猜简单的“y”总是会评估为真。这就是循环永远不会退出的原因。
  • 这就是为什么(甚至还没有改变它)...知道我的大脑冻结了一些东西。谢谢!

标签: while-loop


【解决方案1】:

问题在于'或“y”':

您应该检查 ans 是 Y 还是正确表示为 'ans == "Y" 或 ans == "y"' 的 y

您还需要指定 ans 的起始条件。

ans = "y"
while ans == "Y" or ans == "y":
    num = int(input("What's your number? "))
    if num % 2 == 0:
        print("That number is even!\n")
    else:
        print("That number is odd!\n")
ans = str(input("Do you have another number, Y/y or N/n? "))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-14
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    相关资源
    最近更新 更多