一、定义函数

形参:函数完成一项工作所需要的信息,在函数定义时完成

实参:调用函数时传递给函数的信息

二、传递实参

1.位置实参:每个实参都关联到函数定义中的一个形参

示例: def describe_pet(animal_type,pet_name):
print("My "+ animal_type+"'s is "+pet_name.title()+".") describe_pet('hamster','harry')

2.关键字实参是传递给函数的名称-值对 (直接在实参中将名称和值关联起来,这样无需考虑函数调用中的实参顺序)

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

3.默认值:编写函数时,可给每个形参指定默认值。在调用函数时给形参指定了实参值时,python将使用指定实参值;否则,将使用形参的默认值。

def describe_pet(pet_name,animal_type='dog'):
print("My "+ animal_type+"'s is "+pet_name.title()+".") 调用式1: describe_pet('hamster') 使用形参默认值 调用式2: describe_pet(pet_name='harry',animal_type='hamster')
显示的给animal_type提供了实参,因此python忽略了形参的默认值

注意:使用默认值时,在形参列表中必须先列出没有默认值的形参,在列出有默认值得形参,这让python能正确解读位置实参

4.等效的函数调用:指定实参时可以使用位置方式,也可以使用关键字方式

def describe_pet(pet_name,animal_type='dog'):
print("My "+ animal_type+"'s is "+pet_name.title()+".")
#一条命为willie的小狗
describe_pet('willie')
describe_pet(pet_name='willie') #一只名为Harry的仓鼠
describe_pet('harry','hamster') --位置实参
describe_pet(pet_name='harry',animal_type='hamster')--关键字实参
describe_pet(animal_type='hamster',pet_name='harry')

三、返回值: return语句将值返回到调用函数的代码行

1.返回简单的值

2.让实参变成可选的

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
reutn full_name
musician=get_formatted_name('zilong','zhou')
print(musician) musician=get_formatted_name('xifeng','wang','lee')
print(musician)
为让中间名变成可选,可给形参middle_name一个默认值-空字符串,并在用户没有提供中间名时不使用这个实参

3.返回字典:函数可返回任何类型的值,包括列表和字典等较为复杂的数据结构

def build_person(first_name,last_name,age='')
person={'first_name':first_name,'last_name':last_name}
  if age:
    age=32
retun person
musician=build_person('yufang','ke',20)
print(musician)

4.将函数与while循环结合使用

def get_formatted_name(first_name,last_name)
full_name=first_name+' '+last_name
retun full_name while true:
print("please tell me your name|enter q to quit ")
first_name=input("first name: ")
if first_name == 'q':
break;
last_name=input("last name: ")
if last_name == 'q':
break;
formatted_named=get_formatted_name(first_name,last_name)
print(formatted_named)

四、传递列表

1.在函数中修改列表:3D打印模型公司需要打印的设计存储在一个列表中,打印后移到另一个列表中

def print_models(unprinted_designs,completed_models):
while unprinted_designs:
current_design=unprinted_designs.pop()
completed_models.append(current_design) def show_completed_models(completed_models):
print("the following models have been printed: ")
for completed_model in completed_models:
print(completed_model)
unprinted_designs=['iphone case','robot pendant','dodecahedron']
completed_models=[]
print_models(unprinted_designs,completed_models)
show_completed_models(completed_models)

2.禁止函数列表修改(源代码参--在函数中修改列表)

print_models(unprinted_designs[:],completed_models)

unprinted_designs[:]获得列表unprinted_designs的副本,而不是列表unprinted_designs的本身,列表completed_models也将打印包含打印好的列表名称,但函数所做的修改不会影响到列表unprinted_designs

五、传递任意数量的实参

1.简单示例

制作比萨时需要接受很多配料,但无法预先确定顾客要多少配料,下面形参toppings能够接受任意多个实参
def make_pizza(*toppings):
print(toppings)
make_pizza('peper')
make_pizza('peper','extra cheese')

2.结合使用位置实参和任意数量实参

def make_pizza(size,*toppings):
print("making a"+str(size)+"-inch pizza with the following toppings: ")
for topping in toppings:
print("-"+topping)
make_pizza(,'peper')
make_pizza(,'peper','extra cheese')

3.使用任意数量的关键字实参:将函数编写能够接受任意数量的键-值对--调用语句提供多少就接受多少

build_profile()函数接受名和姓,同事还接受任意数量的关键字实参
def build_profile(first,last,**user_infos):
profile={}
profile['first_name']=first
profile['last_name']=last
for key,value in user_infos:
profile[key]=value
retun profile user_profile=build_profile('albert','eisnst',location='princeton',field='physics')
print(user_profile)

六、将函数存储在模块中

函数的优点之一是使用它们可以和主程序分离;通过给函数指定描述性名称,可让主程序容易理解得多;你还可以将函数存储在称为模块的独立文件中,再将模块导入到主程序中。

import语句允许在当前运行的程序文件中使用模块中的代码

6.1导入整个模块

def make_pizza(size,*toppings):
print("making a"+str(size)+"-inch pizza with the following toppings: ")
for topping in toppings:
print("-"+topping)

接下来,我们在pizza.py文件所在目录创建另一个名为making_pizzas.py文件,这个文件导入刚创建的模块,再调用mkae_pizza()函数两次

import pizza
make_pizza(16,'peper')
make_pizza(15,'peper','extra cheese')
代码行import pizza让Python打开文件pizza.py,并将pizza.py文件中所有函数都复制到这个程序中

6.2 导入特定的函数

导入任意数量函数方法:from module import function_name;

对于前面making_pizzas.py示例,如果你只想导入使用的函数,代码将类似下面这样:

from pizza import make_pizza
make_pizza(16,'peper')
make_pizza(15,'peper','extra cheese')

6.3使用as给函数重命名

指定别名通用语法如下:
from module_name import function_name as fn
对于前面making_pizzas.py示例:
from pizza import make_pizza as mp
make_pizza(16,'peper')
make_pizza(15,'peper','extra cheese')

6.4使用as给模块指定别名

import pizza as p
make_pizza(16,'peper')
make_pizza(15,'peper','extra cheese')
给模块指定别名的通用方法如下:
import module_name as mn

6.5 导入模块中所有函数

使用*运算符可让python导入模块中的所有函数:

from pizza import *
make_pizza(16,'peper')
make_pizza(15,'peper','extra cheese')

6.6 函数编写指南

每个函数首先给函数指定描述性名称,且只在其中使用小写字母和下划线,并简要地阐述其功能注释,该注释应紧跟函数定义的后面

python函数用法的更多相关文章

  1. Python回调函数用法实例详解

    本文实例讲述了Python回调函数用法.分享给大家供大家参考.具体分析如下: 一.百度百科上对回调函数的解释: 回调函数就是一个通过函数指针调用的函数.如果你把函数的指针(地址)作为参数传递给另一个函 ...

  2. Python成长之路第二篇(1)_数据类型内置函数用法

    数据类型内置函数用法int 关于内置方法是非常的多这里呢做了一下总结 (1)__abs__(...)返回x的绝对值 #返回x的绝对值!!!都是双下划线 x.__abs__() <==> a ...

  3. python函数的用法

    python函数的用法 目录: 1.定义.使用函数 1.函数定义:def 2.函数调用:例:myprint() 3.函数可以当作一个值赋值给一个变量 例:a=myprint()    a() 4.写r ...

  4. python iter函数用法

    iter函数用法简述 Python 3中关于iter(object[, sentinel)]方法有两个参数. 使用iter(object)这种形式比较常见. iter(object, sentinel ...

  5. python之函数用法setdefault()

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #python之函数用法setdefault() #D.get(k,d) #说明:k在D中,则返回 D[K], ...

  6. python之函数用法fromkeys()

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #python之函数用法fromkeys() #fromkeys() #说明:用于创建一个新字典,以序列seq ...

  7. python之函数用法get()

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #python之函数用法get() #http://www.runoob.com/python/att-dic ...

  8. python之函数用法capitalize()

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #python之函数用法capitalize() #capitalize() #说明:将字符串的第一个字母变成 ...

  9. python之函数用法isupper()

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #python之函数用法isupper() #http://www.runoob.com/python/att ...

随机推荐

  1. 彻底解决MacOS上应用程序快捷键冲突的问题,自定义快捷键设置

    1看图操作 上面选择好你要修改的应用程序的快捷键 ,我以Chrome为例子 最后点击下ADD 然后回到Chrome的菜单,发现刷新页的快捷键变成了F5 注意,快捷键的名字要和你Chrome菜单上的名字 ...

  2. Luogu P4204 神奇口袋 题解报告

    题目传送门 [题目大意] 一个口袋里装了t种颜色的球,第i种颜色的球的数目为a[i],每次随机抽一个小球,然后再放d个这种颜色的小球进口袋. 给出n个要求,第x个抽出的球颜色为y,求满足条件的概率. ...

  3. day 19 - 1 模块

    collections 模块 在内置数据类型(dict.list.set.tuple)的基础上,collections 模块还提供了几个额外的数据类型:Counter.deque.defaultdic ...

  4. jetty切换tomcat中文乱码

    项目中文在jetty下正常,换tomcat下出现乱码. 问题是web.xml中的encodingFilter不是第一个,要设置为第一个 <filter> <filter-name&g ...

  5. Java并发编程之美之并发编程线程基础

    什么是线程 进程是代码在数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位,线程则是进程的一个执行路径,一个进程至少有一个线程,进程的多个线程共享进程的资源. java启动main函数其实就 ...

  6. python&django 实现页面中关联查询小功能(基础篇)

    效果 实现效果图如下,根据过滤条件查询相关信息. 知识点 1.配置URL,在路由中使用正则表达式 2.过滤查询 代码 setting.py from django.contrib import adm ...

  7. python爬虫得到unicode编码处理方式

    在用python做爬虫的时候经常会与到结果中包含unicode编码,需要将结果转化为中文,处理方式如下 str.encode('utf-8').decode('unicode_escape')

  8. Python3的保留字

    Python3的保留字 false none true and 表示条件的并列,并且条件全部成立 as assert break class continue def del elif else ex ...

  9. java学习笔记06-条件语句

    java条件语句 if...else 单独使用if if(布尔表达式){ 如果布尔表达式为true,执行花括号里的代码 } public static void main(String[] args) ...

  10. 不能忽视 php warning

    2018-12-5 10:50:22 星期三 遇到一个问题: 前一行是取数组中的某一个值, 后一行是用heredoc输出一串javascript脚本; 因为取数组中值的时候键不存在, 导致后续输出的j ...