python - 函数和 if - else 在 python 中。多个条件。代码学院

标签 python function

写一个函数,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/

相关文章:

python - 在列表中查找项目索引

python - Azure函数读取和写入Blob存储抛出内部500错误

c - 在函数 c 中使用枚举定义全局变量

java - 如何在java中实现杰卡德系数?

python - 为什么我的函数在调用时不会激活?

python - 在PythonQT上进行实时输出并将按键输入发送到命令

python - 如何聚合 Pandas 中的多列?

python - 在 matplotlib 中设置可变点大小

R 获取函数参数的名称

C++: "error: expected ' ,' or ' .. .' before ' (' token"