简体   繁体   English

如何在函数内比较字符串

[英]How to compare strings within a function

I am trying to learn Python for fun.我想学习 Python 是为了好玩。 I'm doing an online lesson at codecademy.com, but I have no idea what I have to do.我正在 codecademy.com 上在线课程,但我不知道我必须做什么。

I'm trying to compare 's' parameter with other parameter (string parameter), and the returned value should be "Sorry".我正在尝试将 's' 参数与其他参数(字符串参数)进行比较,返回值应为“Sorry”。

def shut_down(s):
    return s
    if s == 'yes':
        return "Shutting down"
    elif s == 'no':
        return "Shutdown aborted"
    else:
        return "Sorry"

so I call the function:所以我调用函数:

shut_down('lhagvbs')

It always returns, "Your function failed on the message yes. It returned 'yes' when it should have returned 'Shutting down'"它总是返回,“您的函数在消息 yes 上失败。它在应该返回‘关闭’时返回‘是’”

And i think my code does not work.而且我认为我的代码不起作用。 Not even the def function is correct.甚至 def 函数也不正确。

Please explain why, what, where, etc.请解释原因、内容、地点等。

Sorry, I do not speak/write English well, but I hope it's understandable.对不起,我不会说/写英语,但我希望这是可以理解的。

(This is not homework). (这不是家庭作业)。

You need to remove the return s as you are returning s regardless, all the code after return s is unreachable so you never evaluate your if/elif or else:您需要删除return s ,你正在返回s不管,毕竟代码return s不可达,所以你永远不会计算你的if / elif的,否则:

def shut_down(s):
    if s == 'yes':
        return "Shutting down"
    elif s == 'no':
        return "Shutdown aborted"
    else:
        return "Sorry"

In keeping with the fact you can only return once from any function, you can also forget the elif and else:根据您只能从任何函数返回一次的事实,您也可以忘记 elif 和 else:

def shut_down(s):
    if s == 'yes':
        return "Shutting down"
    if s == 'no':
        return "Shutdown aborted"
    return "Sorry"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM