Python学习第6天
1、函数
函数是一种仅在调用时运行的代码块。可以将数据(称为参数)传递到函数中。函数可以把数据作为结果返回。
在 Python 中,使用 def 关键字定义函数:
def my_function(): #def定义函数
print("Hello from a function") #函数中的执行语句
如需调用函数,请使用函数名称后跟括号:
def my_function():#def定义函数
print("Hello from a function") #函数中的执行语句
my_function()#调用函数
信息可以作为参数传递给函数。参数在函数名后的括号内指定。您可以根据需要添加任意数量的参数,只需用逗号分隔即可。
def my_function(fname):
print(fname + " Gates")
my_function("Rory John")
my_function("Jennifer Katharine")
my_function("Phoebe Adele")
#########结果########
Rory John Gates
Jennifer Katharine Gates
Phoebe Adele Gates
pass 语句
def myfunction:
pass#跳过了不执行该代码段
2、Lambda
lambda 函数是一种小的匿名函数。
lambda 函数可接受任意数量的参数,但只能有一个表达式。
x = lambda a : a + 10
print(x(5))
#15
x = lambda a, b : a * b
print(x(5, 6))
#30
如果在短时间内需要匿名函数,需要使用 lambda 函数。
3、一行输入多个数字
思路:将字符串转化为数字
l=input()#输入l,l为字符串
shuzu=[]#存放数字
for x in l:
if x!=' ':
shuzu.append(int(x))#将x转化为整型并添加进入数组中
shuzu.sort()#排序
print(shuzu)
#样例输入:5 1 4 3
#输出[1, 3, 4, 5]