函数和if - else在Python中。 Codeacademy [英] Functions and if - else in python. Codeacademy

查看:105
本文介绍了函数和if - else在Python中。 Codeacademy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

写一个函数shut_down,它接受一个参数(你可以使用任何你喜欢的东西;在这种情况下,我们会使用s作为字符串)。当Shut_down函数获得Yes,yes或YES作为参数时,应该返回Shutting down ...,并且Shutdown aborted!当它得到否,不或否。

如果它获得了除这些输入之外的任何东西,函数应该返回Sorry,I didn'



这是我的代码到目前为止...它的错误,并说不不会返回关机中止!

  def shut_down(s):
if s ==YesoryesorYES:
return关闭...
elif s ==否或no或NO:
返回关机中止!
其他:
返回对不起,我不了解你。


解决方案

b $ b

  s ==是或是或是

等价于:

 (s ==Yes)or(yes )或(是)

哪个总是会返回 True ,因为非空字符串是 True



相反,您想比较<$

 (s ==是的,是的,c $ c> s  )或(s ==是)或(s ==YES)#括号仅用于说明



$ p
$ b

  def shut_down(s):
if s ==是或s ==是或s ==YES:
返回关闭...
elif s ==否或s ==否或s = =NO:
returnShutdown aborted!
其他:
返回对不起,我不了解你。


Write a function, shut_down, that takes one parameter (you can use anything you like; in this case, we'd use s for string). 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."

This is my code so far...it errors and says "No" does not return "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."

解决方案

This:

s == "Yes" or "yes" or "YES"

is equivalent to this:

(s == "Yes") or ("yes") or ("YES")

Which will always return True, since a non-empty string is True.

Instead, you want to compare s with each string individually, like so:

(s == "Yes") or (s == "yes") or (s == "YES")  # brackets just for clarification

It should end up like this:

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."

这篇关于函数和if - else在Python中。 Codeacademy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆