在python中对照列表检查输入为什么一种方法有效而另一种方法无效?

2024-09-28 21:01:40 发布

您现在位置:Python中文网/ 问答频道 /正文

几天前开始学习python,正在使用简单的yes/no输入执行任务,并使用while循环执行不同的操作,具体取决于用户是否希望继续使用该程序

整个程序相当小,所以希望可以在这里发布其全部代码。这就是我的工作原理:

import random

print("=====================================")
print("I Add Numbers and Tell You the Sum v2")
print("=====================================")

while True:
    rand1 = random.randint(1, 100)
    rand2 = random.randint(1, 100)
    result = rand1 + rand2

    print(f"I'm adding {rand1} and {rand2}. If you add them together,the result would be {result}")
    print()

    again_input = input("Would you like to try again? (Y/N) ")
    again = again_input.lower().strip()

    validyes = ["yes", "y"]
    validno = ["no", "n"]

    if again in validyes:
        print("Sure thing!")
        print()
    elif again in validno:
        print("Okay. See you!")
        break
    else:
        print("That's not a valid response. The program will now exit.")
        break

虽然相关代码没有按预期工作,但要根据有效列表检查用户输入,请执行以下操作:

valid = ["yes", "y", "no", "n"]

if valid == "yes" or "y":
    print("Sure thing")
elif valid == "no" or "n":
    print("Okay bye")
    break
else:
    print("That's not a valid response. The program will now exit")
    break

前者可以正常运行,而后者将打印“肯定的事情”,而不管用户输入什么。为什么会这样

在这方面,我很高兴听到你们可能会有关于改进其余代码的任何其他提示。渴望听到并参与这个社区


Tags: no代码用户youinputrandomresultyes
3条回答

您必须显示所有字符串的内容以及它们所比较的内容

if again == "yes" or again == "y":
    print("Sure thing")
elif again == "no" or again == "n":
    print("Okay bye")
    break
else:
    print("That's not a valid response. The program will now exit")
    break

还有一个技巧是在新行中使用“\n”。将不显示\n

旧的:

print(f"I'm adding {rand1} and {rand2}. If you add them together,the result would be {result}")
print()

新的:

print(f"I'm adding {rand1} and {rand2}. If you add them together,the result would be {result}\n")

最后,对于lower和strip函数,如果您得到输入,您可以在同一行中使用它

旧的:

again_input = input("Would you like to try again? (Y/N) ")
again = again_input.lower().strip()

新的:

again = input("Would you like to try again? (Y/N) ").lower().strip()

这就是or的工作原理
操作:x or y
结果:如果x为假,则y,否则x

说明:valid == "yes"将为false,原因很明显,因为您正在将列表与字符串进行比较。当第一个条件为false时,运算符or将计算下一个条件,该条件为"y",并且将始终为true(您可以使用bool("y")确认它),因此它总是打印"Sure thing"

在第二种情况下,使用OR操作数是错误的,这就是为什么它总是打印肯定的东西Here你可以看一看,更好地理解它

为了使代码更好,我建议保留包含所有有效输入的有效列表,并使用if again in valid方法检查是或否,但要处理哪些是有效输入,哪些不是有效输入

相关问题 更多 >