【发布时间】:2019-02-10 22:23:03
【问题描述】:
所以我想在 Python (3.7) 中演示一个简单的 if 语句。 我最终编写了一个简单的代码(v1_alt.1)。
v1_alt.1 按预期工作,我觉得它很容易演示 if 语句是如何工作的。我也想评估前任。 '深绿色' 为 True。
但我觉得它应该写得有点不同。所以我最终测试了不同的代码。我最终用不同的方法来证明什么是有效的,什么是无效的。但我有问题理解它以及为什么。
### v1
color = input("v1 - What is my favourite color? ") # ex. dark green
# alt.1 - Working code. Accept ex. 'dark green'.
if "red" in color or "green" in color:
print(f"You entered {color}. That is is one of my favourite colors! "
"(v1_alt.1)")
# alt.2 - Not working code. Will always evaluate True (Why?)
if "red" or "green" in color:
print(f"You entered {color}. That is is one of my favourite colors! "
"(v1_alt.2)")
# alt.3 - Not working code. Will always evaluate Red True, but not Green (Why?)
if ("red" or "green") in color:
print(f"You entered {color}. That is is one of my favourite colors! "
"(v1_alt.3)")
# alt.4 - Not working code. Will always evaluate True (Why)
if ("red" or "green" in color):
print(f"You entered {color}. That is is one of my favourite colors! "
"(v1_alt.4)")
# alt. 5 - Working code, but I want to accept ex. 'dark green'
if color in {"red", "green"}:
print(f"You entered {color}. That is is one of my favourite colors! "
"(v1_alt.5)")
### v2
fav_colors = ("red", "green")
color = input("v2 - What is my favourite color? ") # ex: dark green
for c in fav_colors:
if c in color:
print(f"You entered {color}. That is correct! "
f"{c} is one of my favourite colors "
"(v2_alt.1)")
if [c for c in fav_colors if c in color]:
print(f"You entered {color}. That is correct! "
f"{c} is one of my favourite colors "
"(v2_alt.2)")
为什么 v1_alt.2 和 v1_alt.4 总是评估为 True?
为什么在 v1_alt.3 中,“红色”答案而不是“绿色”答案评估为 True?
编写 v1_alt.1 的最佳方式是什么?我可以编写一个 v2 代码,但我想保持简单以用于教程目的。
【问题讨论】:
-
我愿意
any(option in colour for option in ("red", "green")
标签: python python-3.x