函数是pyhton中的一个强大而简介的工具,它可以轻松解决在程序中需要重复使用一段代码的问题。
创建和调用函数
定义函数需要用到def语句。def语句以‘():’作为结尾。下面是创建并使用一个函数的示例:
def count1to10(): #创建函数
for i in range(10):
return i+1
print(count1to10()) #调用函数
return是一个函数的结尾,它规定了函数的返回值,在return后没有字符时,默认返回值为None。
参数
在小括号内可以输入函数会用到的参数,
def write(占位符):
print(占位符)
return
write('Python3')
def multi(a,b,c):
return a*b-c
x=12
y=44
z=48
print(multi(x,y,z))
关键字参数
关键字参数是指在调用函数时,通过指定参数名来传递参数值的一种方式
关键字参数没有顺序要求
示例:
def multi(a,b,c):
return a*b-c
print(multi(b=44,a=12,c=48))
默认参数
如果在创建函数时加入默认参数,后续可以在不输入参数时,使用默认值。
示例:
def multi(a=12,b=44,c=48):
return a*b-c
print(multi())
print(multi(3,5,2))
全局变量和局部变量
定义在函数内部的变量拥有一个局部作用域,定义在函数外的则拥有全局作用域。全局变量可以在整段程序中使用,而举报变量只能在函数内使用。
示例:
res=444#这是一个全局变量
def sub(num1,num2):
#返回相减后的结果
res=num1-num2 #这是一个局部变量
print('局部变量为',res)
return res
sub(40,10)
print('全局变量为',res)
iiCkq3s9WCh
I admire your ability to distill complex concepts into easily understandable pieces. Bravo!
This article has given me fresh perspective on the issue, thanks.
You always tackle current topics that intrigue my interest. I appreciate that!
You have provided a fresh take on a typically discussed topic; I appreciate the unique perspective.
I am really impressed along with your writing skills as well as with the layout for your blog. Is this a paid theme or did you modify it yourself? Anyway keep up the excellent high quality writing, it’s uncommon to see a nice blog like this one today. !