【发布时间】:2014-11-19 01:04:54
【问题描述】:
我一直在解决一个问题,但我不确定风格/功能是否明智,这通常被认为是最佳实践。
我有一个函数可以对同一个字符串进行多次检查,并根据该字符串返回一个值。使用堆叠的 if 语句或 if-elif-else 语句是更好的样式或功能吗?
例子:
def f(s):
if s == 'Hey':
return 'Sup.'
if s == "How's it going?"
return 'Not bad.'
return 'I have no idea what you said.'
或
def f(s):
if s == 'Hey':
return 'Sup.'
elif s == "How's it going?"
return 'Not bad.'
else
return 'I have no idea what you said.'
【问题讨论】:
-
if/elif/else暗示XOR行为,换句话说,恰好一种情况应该是True。堆叠if语句表明可以执行多个案例(即使在您的示例中它们不会)。
标签: python coding-style pep8