codecademy.com关于python的两道小程序

来源:互联网 发布:linux kasan 编辑:程序博客网 时间:2024/05/28 05:18

题目一:

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

代码如下:

def shut_down(s):    if s.lower()=="yes":        return "Shutting down..."    elif s.lower()=="no":        return "Shutdown aborted!"    else:        return "Sorry, I didn't understand you."

或者

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

def shut_down(s):    if s in ["YES","Yes","yes"]:        return "Shutting down..."    elif s in ["NO","no","No"]:        return "Shutdown aborted!"    else:        return "Sorry, I didn't understand you."


============================

题目二:

This is a two-parter: first, define a function, distance_from_zero, with one parameter (choose any parameter name you like).

Second, have that function do the following:

Check the type of the input it receives.
If the type is int or float, the function should return the absolute value of the function input.
If the type is any other type, the function should return "Not an integer or float!"


代码如下:

def distance_from_zero(s):    if type(s)==int or type(s)==float:        return abs(s)    else:        return "Not an integer or float!"



原创粉丝点击