Python 函数


(1)定义函数

def greet_user1():
    """文档字符串的注释,描述函数做什么"""
    print("Hello!")

greet_user1()

输出

Hello!

(2)向函数传递信息

def greet_user2(username):
    """文档字符串的注释,描述函数做什么"""
    print("Hello, " + username.title() + "!")

greet_user2('pm')

输出

Hello, Pm!

在函数 greet_user2() 的定义中,变量 username 是一个形参,即函数完成其工作所需的一项信息。
在代码 greet_user2(‘pm’) 中,值 ‘pm’ 是一个实参。

(3)位置实参

def describe_pet(animal_type, pet_name):
    """显示宠物的信息"""
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")

describe_pet('hamster', 'harry')

输出

I have a hamster.
My hamster's name is Harry.

(4)关键字实参
关键字实参是传递给函数的名称-值对。你直接在实参中将名称和值关联起来了,因此向函数传递实参时不会混淆;
关键字实参的顺序无关紧要,因为Python知道各个值该存储到哪个形参中。

def describe_pet2(animal_type, pet_name):
    """显示宠物的信息"""
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")

describe_pet2(pet_name='harry', animal_type='hamster')

输出

I have a hamster.
My hamster's name is Harry.

(5)设置默认值 dog

def describe_pet3(pet_name, animal_type='dog'):
    """显示宠物的信息"""
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")

describe_pet3(pet_name='willie')

或者这样调用

describe_pet3('willie')

输出

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

使用默认值时,在形参列表中必须先列出没有默认值的形参,再列出有默认值的实参。
这让Python依然能够正确地解读位置实参。

(6)返回简单值

def get_formatted_name(first_name, last_name):
    """返回整洁的姓名"""
    full_name = first_name + ' ' + last_name
    return full_name.title()

musician = get_formatted_name('pm', 'lab')
print(musician)

输出

Pm Lab

(7)让实参变成可选的(让middle_name可选)

def get_formatted_name2(first_name, last_name, middle_name=''):
    """返回整洁的姓名"""
    if middle_name:  # Python将非空字符串解读为True
        full_name = first_name + ' ' + middle_name + ' ' + last_name
    else:
        full_name = first_name + ' ' + last_name
    return full_name.title()

musician = get_formatted_name2('jimi', 'hendrix')
print(musician)
musician = get_formatted_name2('john', 'hooker', 'lee')
print(musician)

输出

Jimi Hendrix
John Lee Hooker

(8)返回字典

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', age=8)
print(musician)

输出

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

(9)函数和 while 循环结合

def get_formatted_name3(first_name, last_name):
    """返回整洁的姓名"""
    full_name = first_name + ' ' + last_name
    return full_name.title()

while True:
    print("\nPlease tell me your name:")
    print("(enter '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
    formatted_name = get_formatted_name(f_name, l_name)
    print("\nHello, " + formatted_name + "!")

输出

Please tell me your name:
(enter 'q' at any time to quit)
First name: pm
Last name: lab

Hello, pm lab!

Please tell me your name:
(enter 'q' at any time to quit)
First name: q

(10)传递列表

def greet_users(names):
    """向列表中的每位用户都发出简单的问候"""
    for name in names:
        msg = "Hello, " + name.title() + "!"
        print(msg)

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

输出

Hello, Hannah!
Hello, Ty!
Hello, Margot!

(11)传递任意数量的实参
*toppings中的星号让Python创建一个名为 toppings 的空元组,并将收到的所有值都封装到这个元组中。

def make_pizza(*toppings):
    """打印顾客点的所有配料"""
    print(toppings)

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

输出

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

(12)可以将这条print语句替换为一个循环

def make_pizza2(*toppings):
    """概述要制作的比萨"""
    print("\nMaking a pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)

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

输出

Making a pizza with the following toppings:
- pepperoni

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

(13)使用任意数量的关键字实参
**user_info中的两个星号让Python创建一个名为user_info的空字典,并将收到的所有名称-值对都封装到这个字典中。

def build_profile(first, last, **user_info):
    """创建一个字典,其中包含我们知道的有关用户的一切"""
    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'}
将函数存储在模块中

(14)导入整个模块
pizza.py

def make_pizza_im(size, *toppings):
    """概述要制作的比萨"""
    print("\nMaking a " + str(size) +
          "-inch pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)

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

import pizza
pizza.make_pizza_im(16, 'pepperoni')
pizza.make_pizza_im(12, 'mushrooms', 'green peppers', 'extra cheese')

Python读取这个文件时,代码行import pizza让Python打开文件pizza.py,并将其中的所有函数都复制到这个程序中。
在making_pizzas.py中,可以使用pizza.py中定义的所有函数。
语法为:

module_name.function_name()

(15)导入特定的函数
语法为:

from module_name import function_name

通过用逗号分隔函数名,可根据需要从模块中导入任意数量的函数
语法为:

from module_name import function_0, function_1, function_2

对于前面的making_pizzas.py示例,如果只想导入要使用的函数,代码如下:

from pizza import make_pizza_im
make_pizza_im(16, 'pepperoni')
make_pizza_im(12, 'mushrooms', 'green peppers', 'extra cheese')

(16)使用 as 给函数指定别名
如果要导入的函数的名称可能与程序中现有的名称冲突,或者函数的名称太长,可指定别名。

from pizza import make_pizza_im as mp
mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')

语法为:

from module_name import function_name as fn

(17)使用 as 给模块指定别名

import pizza as p
p.make_pizza_im(16, 'pepperoni')
p.make_pizza_im(12, 'mushrooms', 'green peppers', 'extra cheese')

语法为:

import module_name as mn

(18)导入模块中的所有函数

from pizza import *
make_pizza_im(16, 'pepperoni')
make_pizza_im(12, 'mushrooms', 'green peppers', 'extra cheese')

语法为:

from module_name import *
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值