if 语句是否应该在断言值的函数中以 else 结尾
Should an if-statement end with else in a function that asserts the values
假设我有一个带有变量 drinks
的函数,其值可能会在以后扩展:
def what_to_drink(drinks):
assert drinks in ['coffee','tea'], "Invalid 'drink' value. Please choose between 'coffee' or 'tea'."
if drinks == 'coffee':
print("I don't drink coffee, I drink tea my dear")
elif: drinks == 'tea':
print("I am an English man in New York")
由于饮料的价值可能会扩大,因此使用 elif
而不是 else
似乎更有意义。但是,if 语句是否应该以 else 语句结尾?这似乎是多余的,因为 assert 运算符已经充当了不需要的值的看门人。但是,如果没有 else 语句,逻辑似乎不完整。
Edit: As pointed out, by @user2390182 and @TedKleinBergman, the usage of assert
in the first place is arguably a bigger thing to consider than whether
an else is useful when the logic doesn't allow it to get there.
However, I assume here that you have decided to use assert
yourself,
and will be using it in a way that respects the assert
consistently.
事实:
由于 drinks
始终必须是您列表的一个元素,只要您始终为列表中的每个项目分配一个 elif
,您将永远不会达到 else
,因此它是没必要。
意见:
在这种情况下该怎么做才是正确的做法,这完全取决于个人选择。在线共识通常是“代码越少越好”,但如果它使您的代码更清晰,或者如果您可能经常更改饮料清单,那么将它添加为一个包罗万象的东西可能更有意义,以阻止任何事情在你的发展过程中打破。与许多类似的决定一样,您必须根据具体情况做出决定,并决定您认为在这种情况下哪个更好。
假设我有一个带有变量 drinks
的函数,其值可能会在以后扩展:
def what_to_drink(drinks):
assert drinks in ['coffee','tea'], "Invalid 'drink' value. Please choose between 'coffee' or 'tea'."
if drinks == 'coffee':
print("I don't drink coffee, I drink tea my dear")
elif: drinks == 'tea':
print("I am an English man in New York")
由于饮料的价值可能会扩大,因此使用 elif
而不是 else
似乎更有意义。但是,if 语句是否应该以 else 语句结尾?这似乎是多余的,因为 assert 运算符已经充当了不需要的值的看门人。但是,如果没有 else 语句,逻辑似乎不完整。
Edit: As pointed out, by @user2390182 and @TedKleinBergman, the usage of
assert
in the first place is arguably a bigger thing to consider than whether an else is useful when the logic doesn't allow it to get there. However, I assume here that you have decided to useassert
yourself, and will be using it in a way that respects theassert
consistently.
事实:
由于 drinks
始终必须是您列表的一个元素,只要您始终为列表中的每个项目分配一个 elif
,您将永远不会达到 else
,因此它是没必要。
意见:
在这种情况下该怎么做才是正确的做法,这完全取决于个人选择。在线共识通常是“代码越少越好”,但如果它使您的代码更清晰,或者如果您可能经常更改饮料清单,那么将它添加为一个包罗万象的东西可能更有意义,以阻止任何事情在你的发展过程中打破。与许多类似的决定一样,您必须根据具体情况做出决定,并决定您认为在这种情况下哪个更好。