创建函数
用 def关键字定义函数
def my_function():
print("Hello from a function")
my_function()
运行结果
Hello from a function
参数
可以在函数中设定参数
def my_function(fname):
print(fname + "Gates")
my_function("Rory John")
my_function("Jennifer Katharine")
my_function("Phoebe Adele")
运行结果
Rory JohnGates
Jennifer KatharineGates
Phoebe AdeleGates
默认参数值
可以在函数中直接为变量设置参数
def my_function(country = "china"):
print("I am from" + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
运行结果
I am fromSweden
I am fromIndia
I am fromchina
I am fromBrazil
以列表传参
def my_function(food):
for x in food:
print(x)
fruits = ["apple","banana","cherry"]
my_function(fiuits)
运行代码为
apple
banana
cherry
返回值
函数的返回值可以返回到函数的调用处
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
运行结果
15
25
45
关键字参数
def my_function(child1,child2,child3):
print("The youngest child is " + child3)
my_function(child1 = "Phoebe",child2 = "Jennifer" ,child3 = "Rory")
得到结果
The youngest child is Rory
任意参数
可以通过列表的索引值来输出想要的输出的结果
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Phoebe","Jennifer","Rory")
输出结果
The youngest child is Rory
pass语句
def my_function:
pass
输出结果为空
递归
def tri_recursion(k):
if(k>0):
result = k+tri_recursion(k-1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
tri_recursion(6)
运行结果
1
3
6
10
15
21