栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python编程:从入门到实践(第二版)第 8 章 函数 学习笔记

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python编程:从入门到实践(第二版)第 8 章 函数 学习笔记

1.1 一个简单的实例

输入:

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

输出:

greet_user()
1.2 默认值

使用默认值可以在传参的时候,选择对这个部分不传递参数,如

输入:

def describe_pet(pet_name, animal_type='dog'):
	print(f"nI have a {animal_type}.")
	print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet(pet_name='willie')

输出:

I have a dog.
My dog's name is Willie.

若选择对这一部分进行传参,则会忽略这个形参的默认值

可以使用下面这样进行调用函数

describe_pet('willie')
describe_pet(pet_name='willie')
describe_pet('harry', 'hamster')
describe_pet(pet_name='harry', animal_type='hamster')
describe_pet(animal_type='hamster', pet_name='harry')

除了列表传递的实参,在函数调用后,在主函数内不会发生改变。

将直接将列表表传递给函数后(列表传递的参数相当于一个地址),函数就可对其进行修改,也可以选择不修改。如
输入:

def gaibian(list):
list[0]='new'

def bugaibian(list):
	list[0]='newnew'

list=['old']
gaibian(list)
print(list)
bugaibian(list[:]) #list[:]相当于list的一个副本
print(list)

输出:

['new']
['new']

1.3 返回值

一个普通的实例,
输入:

def build_person(first_name, last_name, age=None):
	person = {'first': first_name, 'last': last_name}
	if age:
		person['age'] = age
	return person


musician = build_person('jimi', 'hendrix', age=27)
print(musician)

输出:

{'first': 'jimi', 'last': 'hendrix', 'age': 27}

1.4 传递任意数量的实参

如,
输入:

def make_pizza(*toppings):
 """打印顾客点的所有配料。"""
 print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

输出:

('pepperoni',)
('mushrooms', 'green peppers', 'extra cheese')

形参名*toppings 中的星号让Python创建一个名为toppings 的空元组,并将收到的所有值都封装到这个元组中。

如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。Python先匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参中。如
输入:

def make_pizza(size, *toppings):
 print(f"nMaking a {size}-inch pizza with the following toppings:")
 for topping in toppings:
 print(f"- {topping}")
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

输出:

Making a 16-inch pizza with the following toppings:
- pepperoni

Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/987577.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号