写一个函数,shut_down
,它接受一个参数(您可以使用任何您喜欢的参数;在这种情况下,我们将使用 s
作为字符串)。
shut_down 函数应该返回 "Shutting down..."
当它得到 "Yes"
, "yes"
, 或 "YES"
作为参数,和 "Shutdown aborted!"
当它得到 "No"
, "no"
, 或 "NO"
.
如果它得到的不是这些输入,函数应该返回 "Sorry, I didn't understand you."
。
到目前为止我写的代码如下。它会出错,例如给出"No"
作为参数,它不返回 "Shutdown aborted!"
正如预期的那样。
def shut_down(s):
if s == "Yes" or "yes" or "YES":
return "Shutting down..."
elif s == "No" or "no" or "NO":
return "Shutdown aborted!"
else:
return "Sorry, I didn't understand you."
最佳答案
这个:
s == "Yes" or "yes" or "YES"
等同于:
(s == "Yes") or ("yes") or ("YES")
它将始终返回 True
,因为非空字符串为 True
。
相反,您希望将 s
与每个字符串单独进行比较,如下所示:
(s == "Yes") or (s == "yes") or (s == "YES") # brackets just for clarification
它应该是这样结束的:
def shut_down(s):
if s == "Yes" or s == "yes" or s == "YES":
return "Shutting down..."
elif s == "No" or s == "no" or s == "NO":
return "Shutdown aborted!"
else:
return "Sorry, I didn't understand you."
关于python - 函数和 if - else 在 python 中。多个条件。代码学院,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15149667/