python基础之函数

定义函数

def greet_user():
	print("Hello")
greet_user()

函数传参

def greet_user(username):
	print("Hello " + username.title() + '!')
greet_user('huny')

关键字参数

def describe_pet(pet_name, animal_type):
    print("
I have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")
    
describe_pet('harry', 'hamster')
describe_pet(pet_name='harry', animal_type='hamster')
describe_pet(animal_type='hamster', pet_name='harry')

默认参数

def describe_pet(pet_name, animal_type='dog'):
    print("
I have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")
    
describe_pet('willie')
describe_pet(pet_name='willie')

函数返回值

def get_formatted_name(first_name,last_name,middle_name=''):
	if middle_name:
		full_name = first_name + " " + middle_name + ' ' + last_name
	else:
		full_name = first_name + ' ' + last_name

	return full_name

musician = get_formatted_name('jimi','hendrix')
print(musician)

musician = get_formatted_name('john','hooker','lee')
print(musician)

函数结合循环

def get_formatted_name(first_name,last_name):
	full_name = first_name + " " + last_name
	return full_name

while True:
	f_name = input("First name: ")
	if f_name == "q":
		break
	l_name = input("Last name: ")
	if l_name == "q":
		break

	formatted_name = get_formatted_name(f_name,l_name)
	print('Hello, ' + formatted_name + '!')

函数结合列表

def greet_users(names):
	for name in names:
		msg = "Hello, " + name.title() + "!"
		print(msg)

username= ['hannah','ty','margot']
greet_users(username)

任意数量的参数

def make_pizza(size,*toppings):
	print(size)

	for topping in toppings:
		print("-: " + topping)

make_pizza(16,'pepperoni')
make_pizza(12,'green peppers','extra cheese')

不定长参数

#*代表元组参数
#**代表字典参数
def play(*hero,**thing):
	print(hero,thing)
play('关羽','赵云',name='无尽之刃',color='yellow')

匿名函数

变量名= lambda参数:表达式
◆参数:可选,通常以逗号分隔的变量表达式形式,也就是位置参数
◆表达式:不能包含循环、return,可以包含if...else...
相比函数,lamba表达式具有以下2 个优势:
◆对于单行函数,使用lambda 表达式可以省去定义函数的过程,让代码更加简洁;
◆对于不需要多次复用的函数,使用lambda 表达式可以在用完之后立即释放,提高程序执行的性能。

func = lambda x, y, z: x + y + z
ret = func(1, 2, 3)
print(ret)

递归函数

一个函数调用其本身,则称它为递归函数。递归函数必须是不断的递归调用函数本身直到达到某一个条件然后返回一个结果。

#创建一个函数power为任意数字做幂运算 n ** i
def power(n,i):
    if i == 1:
        return n
    return n * power(n,i-1)
print(power(10,2))

{{uploading-image-290106.png(uploading...)}}

高阶函数

函数对象也可以作为参数传递给函数,还可以作为函数的返回值。参数为函数对象的函数或返回函数对象的函数称为高阶函数,即函数的函数

map函数

map() 函数的基本语法格式:map(function, iterable)其中,function参数表示要传入一个函数,可以是内置函数、自定义函数或者lambda 匿名函数;iterable表示一个或多个可迭代对象,可以是列表、字符串等。
map() 函数的功能是对可迭代对象中的每个元素,都调用指定的函数,并返回一个map 对象,不是list。

#map()函数
lie = [1,2,3,4,5]
new_list = map(lambda x: x*x,lie)
print(new_list)
print(list(new_list))

filter()函数

filter()函数的基本语法格式:filter(function, iterable)funcition参数表示要传入一个函数,iterable表示一个可迭代对象。
filter() 函数的功能是对iterable中的每个元素,都使用function 函数判断,并返回True 或者False,最后将返回True 的元素组成一个新的可遍历的集合。

#filter函数
lie = [1,2,3,4,5]
def test(n):
    return n % 2 == 0
new_list = filter(test,lie)
print(new_list)
print(list(new_list))

reduce() 函数

通常用来对一个集合做一些累积操作,基本语法格式为:reduce(function, iterable)其中,function规定必须是一个包含2 个参数的函数;iterable表示可迭代对象。注意:由于reduce() 函数在Python 3.x 中已经被移除,放入了functools模块,因此在使用该函数之前,需先导入functools模块,需要引用:from functools import reduce

from functools import reduce
listDemo = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, listDemo)
print(product)

原文地址:https://www.cnblogs.com/huny/p/13765926.html