Python学习笔记之函数

这篇博客详细介绍了Python中函数的编写、参数传递、返回值、列表操作以及模块的导入与使用。通过示例展示了如何定义和调用函数,包括如何处理可变数量的实参,并演示了如何在不同场景下使用`*`和`**`来传递参数。此外,还讲解了如何导入和使用外部模块,包括从模块中导入特定函数、给函数和模块指定别名以及导入模块的所有函数。
摘要由CSDN通过智能技术生成

函数的相关使用

##  函数的编写
def greet_user(username):  # def 定义一个函数
    """显示简单的问候语"""
    print("Hello, " + username.title() + "!")
greet_user('dong')

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)

##  返回字典
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', '27')
print(musician)

##  传递列表
def greet_users(names):
    """向列表中的每位用户都发出简单的问候"""
    for name in names:
        msg = "Hello, " + name.title() + "!"
        print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)

##  函数中修改列表
def print_models(unprinted_designs, completed_models):
    """
    模拟打印每个设计,直到没有未打印的设计为止
    打印每个设计后,都将其移到列表completed_models中
    """
    while unprinted_designs:
        current_design = unprinted_designs.pop()
        # 模拟根据设计制作3D打印模型的过程
        print("Printing model: " + current_design)
        completed_models.append(current_design)
        
def show_completed_models(completed_models):
    """显示打印好的所有模型"""
    print("\nThe 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)
# 如需保留unprinted_designs不被改变,用使用切片传递副本给函数,即unprinted_designs(:)

##  传递任意数量的实参
def make_pizza(*toppings):  # *是创建一个名为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')

##  结合使用位置实参和任意数量实参
def make_pizza(size, *toppings):
    """必须在函数定义中将接纳任意数量实参的形参放在最后"""
    """概述要制作的比萨"""
    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')

##  使用任意数量的关键字实参
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)

函数模块的相关使用

函数模块:

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

模块的使用:

import pizza
## 或者 from pizze import make_pizze
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

'''
导入模块中的特定函数
例如   from module_name import function_name
任意数量的函数,逗号分隔函数名
例如   from module_name import function_0, function_1, function_2
'''
print("----------")
## 使用 as 给函数指定别名
from pizza import make_pizza as mp
mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')

print("----------")
## 使用 as 给模块指定别名
import pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

print("----------")
## 导入模块中的所有函数  使用 *
from pizza import *
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值