《Python编程从入门到实践》_第八章_函数
一个简单的函数
先看一个简单的函数
- def say_hello():
- '''打印hello'''
- print("Hello!")
- say_hello()
- #运行结果
- Hello!
def为函数的关键字,say_hello为你定义的函数的名称,还可能在括号内指出函数为完成其任务需要什么样的信息,即便括号是空的,也是必不可少的,最后以冒号结尾。
向函数传递信息
- def say_hello(name):
- '''打印hello'''
- print("Hello! " + name)
- say_hello('Frank')
- #运行结果
- Hello! Frank
这里在括号里面加了一个变量name,然后将'Frank'传递给了name,输出。
实参和形参
在函数say_hello的定义中,变量name是一个形参——函数完成其工作所需的一项信息。在代码say_hello('Frank')中,其'Frank'就是一个实参,实参是调用函数时传递给函数的信息。
传递实参
位置实参
你调用函数时,Python必须将函数调用中的每个实参都关联到函数定义的一个形参。为此,最简单的关联方式是基于实参的顺序,这种关联方式被称为位置实参,可以多次调用。
- def introduce(name,age):
- '''自我介绍'''
- print("Hello! my name is " + name +" !" + "I'am " + age + " years old !")
- introduce('Frank','')
- #运行结果
- Hello! my name is Frank !I'am 18 years old !
关键字实参
可以直接将形参和实参关联起来,这样就不必要在意顺序了。
- def introduce(name,age):
- '''自我介绍'''
- print("Hello! my name is " + name +" !" + "I'am " + age + " years old !")
- introduce(age='',name='Candy')
- #运行结果
- Hello! my name is Candy !I'am 18 years old !
默认值
可以给函数的形参指定一个默认值,当你给形参重新指定值的时候,会覆盖默认值。
- def introduce(name,age=''):
- '''自我介绍'''
- print("Hello! my name is " + name +" !" + "I'am " + age + " years old !")
- introduce(name='Candy')
- introduce(age='',name='Frank')
- #运行结果
- Hello! my name is Candy !I'am 20 years old !
- Hello! my name is Frank !I'am 23 years old !
返回简单值
函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个或一组值。函数返回的值被称为返回值。
- def get_formatted_name(first_name,last_name):
- '''返回整洁的姓名'''
- full_name = first_name + ' ' + last_name
- return full_name.title()
- musician = get_formatted_name('jimi','hendrix')
- print(musician)
- #运行结果
- Jimi Hendrix
让实参变为可选的
有的时候,我们不需要每个形参都有实参,但是没有实参会导致输出出错,可以看一下下面的例子:
- 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.title()
- musician = get_formatted_name('jimi','hendrix')
- print(musician)
- musician = get_formatted_name('jimi','hendrix','dork')
- print(musician)
- #运行结果
- Jimi Hendrix
- Jimi Dork Hendrix
看上面的例子,并非所有的人都中间名,所有我们在指定实参的时候,middle_name不一定要有,这里我们用''空字符串来指定middle_name的默认值(空字符串为False),再用if判断用那种full_name的格式输出。
返回字典
- def build_person(first_name,last_name,age=''):
- '''返回一个值,其中包含一个人的信息'''
- person = {"first":first_name,"last":last_name}
- if age:
- person['age'] = age
- return(person)
- musician = build_person('jimi','hendrix','')
- print(musician)
- #运行结果
- {'first': 'jimi', 'last': 'hendrix', 'age': ''}
函数可返回任何类型的值,包括列表和字典等较复杂的数据结构。
结合使用while循环和函数
- def get_formatted_name(first_name,last_name):
- '''返回整洁的姓名'''
- full_name = first_name + " " + last_name
- return full_name.title()
- while True:
- f_name = input("Please input your first name:")
- l_name = input("Please input your last name:")
- name = get_formatted_name(f_name,l_name)
- print("hello! " + name)
- #运行结果
- Please input your first name:bin
- Please input your last name:liu
- hello! Bin Liu
- Please input your first name:
函数括号里面也可以是被赋值的变量名。
传递列表
可以将一个列表传递给形参
- def greet_users(names):
- '''遍历列表,打招呼'''
- for name in names:
- print("Hello, " + name + '!')
- usernames = ["Frank","May","Caroline"]
- greet_users(usernames)
- #运行结果
- Hello, Frank!
- Hello, May!
- Hello, Caroline!
在函数中修改列表
- def print_models(upprint,completed):
- '''弹出已打印的给完成的列表,并打印'''
- while upprint:
- current = upprint.pop()
- print("print:",current)
- completed.append(current)
- def show_models(completed):
- '''显示已打印的'''
- print("The following models have been print:")
- for c in completed:
- print(c)
- upprint = ["apple","book","shirt"]
- completed = []
- print_models(upprint,completed)
- show_models(completed)
- #运行结果
- print: shirt
- print: book
- print: apple
- The following models have been print:
- shirt
- book
- apple
在这个例子中,函数执行结束后,upprint列表就空了,为了解决这个问题,可向函数传递列表的副本而不是原件,这样函数所做的任何修改都只影响副本,而不会影响原件。
- def print_models(upprint[:],completed):
传递任意数量的实参
- def make_pizza(*toppings):
- '''概述要制作的pizza'''
- print("\nMaking a pizza with the following toppings:")
- for topping in toppings:
- print("--",topping)
- make_pizza('pepperoni')
- make_pizza('mushrooms','grenn peppers','extra cheese')
- #运行结果
- Making a pizza with the following toppings:
- -- pepperoni
- Making a pizza with the following toppings:
- -- mushrooms
- -- grenn peppers
- -- extra cheese
形参名*toppings的星号让Python创建一个名为toppings的空元祖,并将收到的所有值都封装想到这个元祖中。
结合使用位置实参和任意数量实参
如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。Python会先匹配实参和关键字实参,再将余下的实参都收集到最后一个形参中。
- def make_pizza(size,*toppings):
- '''概述要制作的pizza'''
- print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")
- for topping in toppings:
- print("--",topping)
- make_pizza(16,'pepperoni')
- make_pizza(12,'mushrooms','grenn peppers','extra cheese')
- #运行结果
- Making a 16-inch pizza with the following toppings:
- -- pepperoni
- Making a 12-inch pizza with the following toppings:
- -- mushrooms
- -- grenn peppers
- -- extra cheese
使用任意数量的关键字实参
- def build_profile(first_name,last_name,**info):
- '''创建一个字典,其中包含我们知道的有关用户的一切'''
- profile={}
- profile["first_name"]=first_name
- profile["last_name"]=last_name
- for k,v in info.items():
- profile[k]=v
- return profile
- user_profile = build_profile("bin","liu",location="princeton",field="physics")
- print(user_profile)
- #运行结果
- {'first_name': 'bin', 'last_name': 'liu', 'location': 'princeton', 'field': 'physics'}
将函数存储在模块中
- #pizza打印方式模块
- def make_pizza1(size,*toppings):
- '''概述要制作的pizza'''
- print("\n Making a " + str(size) +
- "-inch pizza with the following toppings:")
- for topping in toppings:
- print("----" + topping)
- def make_pizza2(size,*toppings):
- '''概述要制作的pizza'''
- print("\nsize:",size)
- print("toppings:")
- for topping in toppings:
- print("====",topping)
在同一目录下创建:pizza.py
- #pizza
- import make_pizza
- make_pizza.make_pizza1(16,'pepperoni','mushrooms')
- make_pizza.make_pizza2(16,'pepperoni','mushrooms')
运行结果:
- Making a 16-inch pizza with the following toppings:
- ----pepperoni
- ----mushrooms
- size: 16
- toppings:
- ==== pepperoni
- ==== mushrooms
导入特定的函数
- #pizza打印方式模块 文件make_pizza.py
- def make_pizza1(size,*toppings):
- '''概述要制作的pizza'''
- print("\n Making a " + str(size) +
- "-inch pizza with the following toppings:")
- for topping in toppings:
- print("----" + topping)
- def make_pizza2(size,*toppings):
- '''概述要制作的pizza'''
- print("\nsize:",size)
- print("toppings:")
- for topping in toppings:
- print("====",topping)
- #pizza 文件pizza.py
- from make_pizza import make_pizza1,make_pizza2
- make_pizza1(16,'pepperoni','mushrooms')
- make_pizza2(16,'pepperoni','mushrooms')
- #运行结果
- Making a 16-inch pizza with the following toppings:
- ----pepperoni
- ----mushrooms
- size: 16
- toppings:
- ==== pepperoni
- ==== mushrooms
使用as给函数定义别名
- #pizza
- from make_pizza import make_pizza1 as pz1,make_pizza2 as pz2
- pz1(16,'pepperoni','mushrooms')
- pz2(16,'pepperoni','mushrooms')
- #运行结果
- Making a 16-inch pizza with the following toppings:
- ----pepperoni
- ----mushrooms
- size: 16
- toppings:
- ==== pepperoni
- ==== mushrooms
语法:from module_name import function_name as fn
使用as给模块定义别名
- #pizza
- import make_pizza as pz
- pz.make_pizza1(16,'pepperoni','mushrooms')
- pz.make_pizza2(16,'pepperoni','mushrooms')
- #运行结果
- Making a 16-inch pizza with the following toppings:
- ----pepperoni
- ----mushrooms
- size: 16
- toppings:
- ==== pepperoni
- ==== mushrooms
语法:import module_name as mn
导入模块中所有的函数
- #pizza
- from make_pizza import *
- make_pizza1(16,'pepperoni','mushrooms')
- make_pizza2(16,'pepperoni','mushrooms')
- #运行结果
- Making a 16-inch pizza with the following toppings:
- ----pepperoni
- ----mushrooms
- size: 16
- toppings:
- ==== pepperoni
- ==== mushrooms
*可以代表前面指定模块里的所有函数。
《Python编程从入门到实践》_第八章_函数的更多相关文章
- 《Python编程从入门到实践》第二章_变量和简单数据类型
什么是变量呢? 举例: >>> message = "Hello,Python!" >>> print (message) Hello,Pyth ...
- 《Python编程从入门到实践》_第十章_文件和异常
读取整个文件 文件pi_digits.txt #文件pi_digits.txt 3.1415926535 8979323846 2643383279 下面的程序打开并读取整个文件,再将其内容显示到屏幕 ...
- 《python编程从入门到实践》读书实践笔记(一)
本文是<python编程从入门到实践>读书实践笔记1~10章的内容,主要包含安装.基础类型.函数.类.文件读写及异常的内容. 1 起步 1.1 搭建环境 1.1.1 Python 版本选择 ...
- Python编程从入门到实践笔记——异常和存储数据
Python编程从入门到实践笔记——异常和存储数据 #coding=gbk #Python编程从入门到实践笔记——异常和存储数据 #10.3异常 #Python使用被称为异常的特殊对象来管理程序执行期 ...
- Python编程从入门到实践笔记——文件
Python编程从入门到实践笔记——文件 #coding=gbk #Python编程从入门到实践笔记——文件 #10.1从文件中读取数据 #1.读取整个文件 file_name = 'pi_digit ...
- Python编程从入门到实践笔记——类
Python编程从入门到实践笔记——类 #coding=gbk #Python编程从入门到实践笔记——类 #9.1创建和使用类 #1.创建Dog类 class Dog():#类名首字母大写 " ...
- Python编程从入门到实践笔记——函数
Python编程从入门到实践笔记——函数 #coding=gbk #Python编程从入门到实践笔记——函数 #8.1定义函数 def 函数名(形参): # [缩进]注释+函数体 #1.向函数传递信息 ...
- Python编程从入门到实践笔记——用户输入和while循环
Python编程从入门到实践笔记——用户输入和while循环 #coding=utf-8 #函数input()让程序暂停运行,等待用户输入一些文本.得到用户的输入以后将其存储在一个变量中,方便后续使用 ...
- Python编程从入门到实践笔记——字典
Python编程从入门到实践笔记——字典 #coding=utf-8 #字典--放在{}中的键值对:跟json很像 #键和值之间用:分隔:键值对之间用,分隔 alien_0 = {'color':'g ...
- Python编程从入门到实践笔记——if语句
Python编程从入门到实践笔记——if语句 #coding=utf-8 cars=['bwm','audi','toyota','subaru','maserati'] bicycles = [&q ...
随机推荐
- Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'blog.t_blog.addTime' which is not functi
sql报错: Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Expression #1 of SELECT ...
- 移动端适配video适配
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 文件上传下载(C#,web,asp.net)
目的:在浏览器页面启动上传下载CS软件,实现文件的批量下载与上传. 技术路线: 开发上传下载客户端CS程序与注册程序,压缩放到服务器端指定位置: 开发服务器端程序用以接收上传请求,压缩放到服务器端: ...
- Nginx 进行性能配置
总所周知,网络上我们购买的服务器的性能各不相同,如果采用 Nginx 的默认配置的话,无法将服务器的全部性能优势发挥出来,我们应该选择适合自己需求的配置. 当我们默认安装后 Nginx 后,我们便得到 ...
- Win7下C/C++跨平台开发工具IDE的安装之Eclipse-CDT
2. win7下安装Eclipse-CDT运行C/C++程序: 下载Eclipse-CDT 64位:http://www.eclipse.org/downloads/packages/release/ ...
- 三种timer控件的简单实例
.system.windows.forms .system.threading.timer .system.timers.timer using System; using System.Collec ...
- flex弹性布局,好用
一直不太喜欢自己布局前端页面,都是扒别人的页面 ,最近在练习小程序,页面无处可扒,只有自己布局 发现flex弹性布局真好用,布局起来很简单,实现的效果也很好,赞 以后可以自己写一点前端了,哈哈
- sqlalchemy orm数据类型验证方法比较
1.在定义ORM模型时校验 sqlalchemy提供validates函数支持对字段的校验 from sqlalchemy.orm import validates class EmailAddres ...
- adminlte+layui框架搭建3 - layui弹出层
在amdinlte首页引入layui.js 和layui.css后添加代码 <script> layui.use(['layer'], function () { var layer = ...
- CMM模型,结构化开发方法和面向对象开发方法的比较,UML(统一建模语言),jackson开发方法
CMM模型 一.CMM简介 CMM,英文全称为Capability Maturity Model for Software,即:软件成熟度模型. CMM的核心是把软件开发视为一个过程.它是对于软件在定 ...