函数和if-else in python.多重条件.密码学
编写一个带有一个参数的函数shut_down
(您可以使用任何您喜欢的东西;在这种情况下,我们将s
用作字符串).
Write a function, shut_down
, that takes one parameter (you can use anything you like; in this case, we'd use s
for string).
shut_down函数在获取"Yes"
,"yes"
或"YES"
作为参数时应返回"Shutting down..."
,并在获取"No"
,"no"
或"NO"
时返回"Shutdown aborted!"
.
如果得到的不是这些输入,函数应返回"Sorry, I didn't understand you."
The shut_down function should return "Shutting down..."
when it gets "Yes"
, "yes"
, or "YES"
as an argument, and "Shutdown aborted!"
when it gets "No"
, "no"
, or "NO"
.
If it gets anything other than those inputs, the function should return "Sorry, I didn't understand you."
我到目前为止编写的代码如下.它会出错,例如以"No"
作为参数,它不会按预期方式返回"Shutdown aborted!"
.
The code I wrote so far is below. It makes errors, e.g. given "No"
as the argument, it does not return "Shutdown aborted!"
as expected.
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
.
Which will always return True
, since a non-empty string is True
.
相反,您希望分别将s
与每个字符串进行比较,如下所示:
Instead, you want to compare s
with each string individually, like so:
(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."