“”“Python函数
“””
1,创建函数
#在 Python 中,使用 def 关键字定义函数:
def test_func():
print(‘我的第一个函数’)
2,调用函数
#如果需要调用函数,可以直接使用函数名加括号
def soybean():
print(‘eating,sleeping,beat soybean’)
soybean()
#eating,sleeping,beat soybean
3,参数
#信息可以作为参数传递给函数。
#参数在函数名后的括号内指定。您可以根据需要添加任意数量的参数,只需用逗号分隔即可。
def foreign_name(Hitman):
print(Hitman + ’ baby’)
foreign_name(‘Smoking’)
foreign_name(‘Laughing’)
foreign_name(‘Crying’)
#Smoking baby
#Laughing baby
#Crying baby
4,默认值参数
def defaut_func(living = ‘big house’):
print(“I living in the”, living)
defaut_func(‘little bin’)
defaut_func(‘country house’)
defaut_func()
defaut_func(‘villa dom’)
‘’‘I living in the little bin
I living in the country house
I living in the big house
I living in the villa dom’’’
5,list传参
def kinds_of_fish(fish):
for p in fish:
print(p, ‘swimming in the sea’)
fish = [‘clownfish’, ’ octopus’, ‘shark’]
kinds_of_fish(fish)
‘’‘clownfish swimming in the sea
octopus swimming in the sea
shark swimming in the sea’’’
6,返回值
#如需使函数返回值,请使用 return 语句
def multiplication(number):
return 10 * number
print(multiplication(8))
print(multiplication(10))
print(multiplication(99))
#80 100 990
7,关键字参数
#参数的顺序无关紧要。
def key_word(fruit1, fruit2, fruit3):
print('The sweetest fruit is ', fruit1)
key_word(fruit1=‘strawberry’,fruit2=‘watermelon’,fruit3=‘lemon’)
#The sweetest fruit is strawberry
8,任意参数
#如果参数数目未知,请在参数名称前添加 *
def random(*games):
print('The World Championship of ', games[2])
random(‘Dota2’,‘WOW’,‘LOL’,‘CS’)
#The World Championship of LOL
9,pass语句
#函数定义不能为空,出于某种原因写了无内容的函数定义,使用 pass 语句来避免错误。
def nothing():
pass
10,递归
#递归是一种常见的数学和编程概念。它意味着函数调用自身。特别要注意的是递归的终止条件。
def recursion(k):
if(k>0):
result = k+recursion(k-1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
recursion(3)
‘’‘Recursion Example Results
1
3
6’’’