因此,我想在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中,为什么“红色”答案而不是“绿色”答案?
编写v1_alt.1的最佳方法是什么?我可以编写v2代码,但出于教程目的,我想使其简单。
答案 0 :(得分:6)
在Python中,如果x
被称为bool(x) is True
,则该对象在布尔上下文中等效于True
。
# alt.2 - Not working code. Will always evaluate True (Why?)
if "red" or "green" in color:
该表达式的值为"red" or ("green" in color)
。由于"red"
是真实的,因此表达式也是如此(第二部分甚至没有求值)。
# alt.3 - Not working code. Will always evaluate Red True, but not Green (Why?)
if ("red" or "green") in color:
括号中的表达式的值为"red"
,因为在Python中,or
和and
返回其参数。 or
返回第一个参数(如果为真),否则返回第二个参数。因此,整个语句可以简化为if 'red' in color: ...
您的第四个示例与第二个示例等效:这些括号没有任何变化。
# alt. 5 - Working code, but I want to accept ex. 'dark green'
if color in {"red", "green"}
然后,一切都不会阻止您将颜色添加到该集合中:{"red", "green", "dark green"}
。
编写v1_alt.1的最佳方法是什么
几乎没有任何“最佳方法”,因为这些东西往往只是口味问题。话虽这么说,如果您有一套固定的颜色,我将使用元组或一组类似您的“ alt 5”示例中的颜色。如果您有一组固定的基色,并且始终希望修饰符位于开头(如“深绿色”)并且以空格分隔,则可以拆分传入的字符串:if color.split()[-1] in base_colors
,其中{{1} }是基色的集合/元组/列表/(任何可搜索的数据结构)。如果您的任务需要复杂的逻辑,那么使用专用功能会更好:
base_colors
一个函数封装了实现细节,否则将“污染”您的主要执行图。而且,可以安全地修改它,而无需接触其他部分(只要保持其纯净)。