根据列表检查输入,为什么一种方式有效而另一种方式无效?



几天前开始学习python,用简单的是/否输入完成一项任务,并用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

前者运行良好,而后者将打印";当然"而不管用户输入什么。为什么会这样?

在这方面,我很高兴听到你们在让代码的其余部分变得更好方面的任何其他提示。渴望听到并参与这个社区!

您必须显示所有字符串与的比较

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〃;新线路。不会显示

旧:

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")

最后一个是,如果你得到你的输入,你可以在同一行中使用下条和条形函数

旧:

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操作数,这就是为什么它总是打印Sure thing。在这里你可以看一看并更好地理解它。

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

这就是or的工作方式
操作:x or y
结果:如果x为false,则y,否则x

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

您使用的是:

if valid == "yes" or "y":
print("Sure thing")
elif valid == "no" or "n":
print("Okay bye")
break

因此,在第一个条件中,您检查if (valid == "yes") or ("y"),但不检查if valid == ("yes" or "y")。当您将非空字符串用作bool时,它始终为True,因此第一个条件始终为True。如果你想这样做,你可以使用元组(它就像列表,但你不能编辑它(:if valid in ("yes", "y")

valid是一个列表,所以valid永远不会等于"是";,所以它只是转到";y";,这将永远是正确的。您需要检查";是";或";y";有效:

if "yes" in valid or "y" in valid:
print("Sure thing")
elif "no" in valid or "n" in valid:
print("Okay bye")
break

当然,使用此代码,它将始终打印";当然"因为CCD_ 17包括所有选项。

相关内容

最新更新