Python学习(十)Python 函数

Python 函数

Python 函数

函数:带名字的代码块,用于完成具体工作。

函数:数学解释 == function()

计算机中函数: 计算机所有语言函数 == subroutine(子程序),procedure(过程)

作用:

  1. 减少重复代码
  2. 方便修改,更易扩展
  3. 保持代码一致性

函数格式:

def 函数名(参数列表):

函数体 < br >< br >


函数命名规则:

  1. 函数名必须以下划线或字母开头,可以包含任意字母、数字或下划线的组合,不能使用任何的标点符号
  2. 函数名是区分大小写的
  3. 函数名不能使用保留字(系统定义的函数如:print等)

定义函数

打印问候语的简单函数

def greet_user():
    """Display a simple greeting."""
    print("Hello, Jesse !")
greet_user()
Hello, Jesse !

向函数传递信息

def greet_user(username):
    """Display a simple greeting."""
    print("Hello, %s !"%(username.title()))
greet_user('jesse')
Hello, Jesse !

形参:代码块中定义的参数,如上文中的“username”

实参:调用函数时给函数传递的具体信息,如上文中“jesse”


形参和实参之间的关系

默认:实参和形参是一一对应的,定义几个形参就需要输入几个实参,顺序要和形参一致。

关键字实参传递:可指定你要为那个形参传递什么参数,如上文可写成“greet_user(username = 'jesse')”


函数返回值

返回值:函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个或一组值。函数返回的值称为返回值


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

注意:

  1. 函数执行过程中只要遇到return语句,就会停止执行并返回结果,也可以理解为return语句代表函数的结束。
  2. 如果未在函数中指定return,那么这个函数的返回值为“None”
  3. return多个对象,解释器会把多个对象组装成一个元组作为一个整体结果输出。

返回简单函数值

def get_formatted_name(first_name, last_name, middle_name):

"""Return a full name, neatly formatted."""

full_name = "%s %s %s"%(first_name,middle_name,last_name)

return full_name.title()

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

print(musician)

结果:

John Lee Hooker
实参变成可选参数

实参变成可选参数,必须赋予可选参数一个默认值

定义middle_name='',当 middle_name 这个实参不存在时使用默认值空。

为了输出结果整洁,使用if判断middle_name存在时执行三个传参的格式,不存在执行两个传参的格式

def get_formatted_name(first_name, last_name, middle_name=''):

判断传参

"""Return a full name, neatly formatted."""
    if middle_name:
        full_name = "%s %s %s"%(first_name,middle_name,last_name)
    else:
        full_name = "%s %s"%(first_name,last_name)
    return full_name.title()

调用函数并传参

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

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

结果显示整洁

Jimi Hendrix
John Lee Hooker
返回字典

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

def build_person(first_name, last_name, age=''):

"""Return a dictionary of information about a person."""

person = {'first': first_name, 'last': last_name}

#判断age值是否为空
if age:

person['age'] = age

return person

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

print(musician)

{'first': 'jimi', 'last': 'hendrix', 'age': 27}
结合使用函数和while循环

def get_formatted_name(first_name, last_name, middle_name=''):

"""Return a full name, neatly formatted."""

if middle_name:

full_name = "%s %s %s"%(first_name,middle_name,last_name)

else:

full_name = "%s %s"%(first_name,last_name)

return full_name.title()

while True:

print(" Please tell me your name :")

print("(entre 'q' at any time to quit)")

f_name = input("First name :")

if f_name == 'q' :

break

l_name = input("Last name :")

if l_name == 'q' :

break

musician = get_formatted_name(f_name, l_name)

print("Hello, %s !"%(musician))

Please tell me your name :
(entre 'q' at any time to quit)
First name :eric
Last name :matthes
Hello, Eric Matthes !
传递列表到函数

个性化问候

def greet_users(names):

"""Print a simple greeting to each user in the list."""

for name in names:

msg = "Hello, " + name.title() + "!"

print(msg)

usernames = ['hannah', 'ty', 'margot']

greet_users(usernames)

Hello, Hannah!
Hello, Ty!
Hello, Margot!
在函数中修改列表

将列表传递给函数后,函数可对其进行修改。

函数对列表做的任何修改时永久的,能够高效的处理大量数据

def print_models(unprinted_designs, completed_models):
    """
    Simulate printing each design, until there are none left.
    Move each design to completed_models after printing.
    """
    while unprinted_designs:
        current_design = unprinted_designs.pop()
    
        # Simulate creating a 3d print from the design.
        print("Printing model: " + current_design)
        completed_models.append(current_design)
        
def show_completed_models(completed_models):
    """Show all the models that were printed."""
    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)

执行结果:

Printing model: dodecahedron
Printing model: robot pendant
Printing model: iphone case

The following models have been printed:
dodecahedron
robot pendant
iphone case
禁止函数修改列表

函数传递列表的副本可以保留原始列表的内容不变,除非理由充分需要使用列表副本,否则还是要将原始列表传递给函数。

创建列表副本需要花时间与内存创建副本,不创建副本可以提高效率,在处理大型列表时尤其重要。

传递任意数量的实参

Python允许函数从调用语句中收集任意数量的实参

函数中形参“ *toppings ” ,不论实参传递了多少个都会收入囊中

def make_pizza(size, *toppings):
    """Summarize the pizza we are about to make."""
    print("
Making a " + str(size) +
          "-inch pizza with the following toppings:")
    for topping in toppings:
        print("- " + 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
使用位置实参和任意数量的关键字实参

def build_profile(first, last, **user_info):

"""Build a dictionary containing everything we know about a user."""

profile = {}

profile['first_name'] = first

profile['last_name'] = last

for key, value in user_info.items():

profile[key] = value

return profile

user_profile = build_profile('albert', 'einstein',location='princeton',field='physics')

print(user_profile)

{'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}
  • *args:无命名参数
  • **kwargs:有命名参数,例如字典
def f (*args,**kwargs):
    # pass
    for i,id in kwargs.items():
        print("%s: %s"%(i,id))
    print(args)
f(1,2,3,[123,4],name='jorbabe',aut='abc')
name: jorbabe
aut: abc
(1, 2, 3, [123, 4])

将函数存储在模块中

函数的优点:使用函数可以将代码块和主程序分离,通过给与函数指定描述性名称,使主程序更容易理解。

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

函数模块导入

·1、导入整个模块 同级目录调用函数模块。

  • 创建模块

    模块是扩展名称“.py”的文件,包含要导入程序的代码
    
    如创建包含函数make_pizza()的模块pizza
    
    编写模块:pizza.py
    
    def make_pizza(size, *toppings):
        """Summarize the pizza we are about to make."""
        print("
    Making a " + str(size) +
              "-inch pizza with the following toppings:")
        for topping in toppings:
            print("- " + topping)
  • 调用模块:making_pizzas.py

    import pizza
    
    pizza.make_pizza(16, 'pepperoni')
    pizza.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

模块导入方式,仅需一个import语句,就可将该模块中所有的函数导入,该导入方式可以在代码中使用,module_name.function_name()调用任意一个模块中的函数,如上文中的 pizza.make_pizza(16, 'pepperoni')

·2、导入特定函数

  • 导入方式 from module_name import function_name

    如上文中可使用:
    
    from pizza import make_pizza
    make_pizza(16, 'pepperoni')
    make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

·3、使用as给函数指定别名

  • 导入方式 from module_name import function_name as xxx

    如上文中可使用:
    
    from pizza import make_pizza as mp
    mp(16, 'pepperoni')
    mp(12, 'mushrooms', 'green peppers', 'extra cheese')

·4、使用as给模块指定别名

  • 导入方式 import module_name as xxx

    如上文中可使用:
    
    import pizza as p
    
    p.make_pizza(16, 'pepperoni')
    p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

·5、导入模块中所有函数

  • 导入方式 from module_name import *

    如上文中可使用:
    
    from pizza import *
    make_pizza(16, 'pepperoni')
    make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

函数编写指南

形参的默认值等号两端不要有空格

def function_name(parameter_0,parameter_1='value')

原文地址:https://www.cnblogs.com/jorbabe/p/8733800.html