Python学习记录6:基础知识-函数


本篇博客为 python学习记录系列博客内容,欢迎访问 python速成博客导航

👉不会吧,都2021年了还有人不会Python?三天急速入门教程!👈


一、关于函数的基本操作

  1. 关键字实参
    调用函数时,明确指出各个实参对应的形参,这样实参在括号内的位置就不重要了(否则与实参位置有关——也就是“位置实参”)
def describe_pet(pet_name, animal_type):
    """显示宠物的信息"""
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")

# 以下两次调用等价
describe_pet(animal_type='hamster', pet_name='harry')
describe_pet(pet_name='harry', animal_type='hamster')
  1. 默认值
    编写函数时,可以给每个形参指定默认值。在调用函数中给形参提供了实参时,Python将使用指定的实参值;否则,将使用形参的默认值。
    注意:由于位置实参的原因,未指定默认值的形参要放在指定了默认值的形参之前
def describe_pet(pet_name, animal_type='dog'):
    """显示宠物的信息"""
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")

describe_pet(pet_name='willie') # willie的种类是dog,便可以省略animal_type
describe_pet(pet_name='harry', animal_type='hamster') # 一只叫“harry”的仓鼠
  1. 返回简单值:使用return函数,同c/c++。
  2. 让实参变为可选的
# 将middle_name指定默认值——空字符串
# Python将非空字符串解读为True,空字符串解读为False
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('john', 'hooker', 'lee')
print(musician)
output:
Jimi Hendrix
John Lee Hooker
  1. 返回字典
def build_person(first_name, last_name, age=''):  # age作为可选实参
    """Return a dictionary of information about a person."""
    person = {'first': first_name, 'last': last_name} 
    if age:
        person['age'] = age # 在这里判断赋值
    return person

musician = build_person('jimi', 'hendrix', age=27)
print(musician)
  1. 传递列表(与c/c++逻辑相同):
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)
  1. 如果想把列表传递到函数处理,又不想函数修改列表,可以使用副本
    fuben = yuanjian[:]
  2. 传递任意数量的实参
    *toppings中的星号让python创建一个名为toppings的空元组,并将接收到的所有值都封装到这个元组中。
def make_pizza(*toppings):
    """概述要做的比萨"""
    print("\nMaking a pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)

make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
output:
Making a pizza with the following toppings:
- pepperoni

Making a pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese
  1. 结合位置实参使用任意数量实参
    结合使用时必须将接纳任意数量实参的形参放在最后
def make_pizza(size, *toppings):
    """Summarize the pizza we are about to make."""
    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', 'green peppers', 'extra cheese')
output:
Making a 16-inch pizza with the following toppings:
- pepperoni

Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese
  1. 使用任意数量的关键字实参
# **user_info创建了一个名为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)
output:
{'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}

二、将函数存储在模块内

  1. 导入整个模块
    假如有一段python代码定义了一个名为make_pizza的函数,代码文件被命名为pizza.py;我们在该代码所在目录中创建另一个名为test.py的文件,这个文件导入刚创建的模块→impor pizza,我们就可以使用pizza.py内的函数啦:
    pizza.make_pizza()
  2. 导入特定的函数
    我们也可以只导入函数,还是拿pizza.py举例,我们可以这样导入:
    from pizza import make_pizza
    于是我们就可以直接用make_pizza()函数了,且无需使用文件名+句点
  3. 使用 as函数指定别名
    如果要导入的函数的名称可能与程序中现有的名称冲突;或者函数名称太长,那我们就可以给它起一个别名。
    from pizza import make_pizza as mp
    这样我们调用make_pizza函数可以简写成mp()
  4. 使用 as模块指定别名
    import pizza as p
    于是调用函数也变得简单:
    p.make_pizza()
  5. 导入模块中的所有函数
    from pizza import *
    我们可以使用星号(*)导入模块中的所有函数。
    注意!最好不要这么做,因为你可能会遇到导入的函数、变量与现有工程中的重名的问题!
    
3、函数编写指南(一些建议):
  1. 应给函数指定描述性名称,且在其中使用小写字母和下划线;
  2. 每个函数都应包含简要地阐述其功能的注释(紧跟在函数定义后面),并采用文档字符串格式;
  3. 给形参指定默认值时,等号两边不要空格
  4. 对于函数调用中的关键字实参,等号两边也不要空格
  5. 如果程序或模块包含多个函数,可使用两个空行将相邻的函数分开;
  6. 所有的import语句都应该放在文件的开头,除非文件的开头是描述整个程序的注释。
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值