2021-12-18周报

目录

python

第八章函数

1.定义函数

2.传递实参

3.返回值

4.传递列表

5.传递任意数量的实参

6.将函数存储在模块中

毕设


python

第八章函数

1.定义函数

def greet_user(username):
   """显示简单的问候语"""
   print(f"hello,{username.title()}")

greet_user('jesse')

形参:函数定义中的变量

实参:函数调用中的变量

练习8-2

print('\n')
def favorite_book(title):
    print(f" one of my favorite books is {title}")
favorite_book('alice in wonderland')

2.传递实参

2.1位置实参

调用函数时,python必须将函数调用中的每个实参都关联到函数定义中的一个形参,这种关联方式是基于实参的顺序,这种方法叫做位置实参

print('\n')
def describe_pet(animal_type,pet_name):
    print(f"\nI have a {animal_type}")
    print(f"my{animal_type}'s name is {pet_name.title()}.")
describe_pet('hamster','harry')

2.2关键字实参

关键字实参是传递给函数的名称值对,因为直接在实参中将名称和值关联起来,所以向函数在传递实参时不会发生混淆

print('\n')
def describe_pet(animal_type,pet_name):
    print(f"\nI have a {animal_type}")
    print(f"my{animal_type}'s name is {pet_name.title()}.")
describe_pet(animal_type='hamster',pet_name='harry')

2.3默认值

编写函数是可以给形参指定默认值,如果调用函数没有提供实参,那么就使用默认值

print('\n')
def describe_pet(pet_name,animal_type='dog'):
    print(f"\nI have a {animal_type}")
    print(f"my{animal_type}'s name is {pet_name.title()}.")
describe_pet(pet_name='harry')

2.4等效的函数调用(混合使用上面三种方法)

print('\n')
describe_pet('willie')
describe_pet(pet_name='willie')

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

3.返回值

def get_formatted_name(first_name,last_name):
    full_name=f"{first_name} {last_name}"
    return full_name.title()

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

3.1 让实参变成可选的

def get_formatted_name(first_name,middle_name,last_name):
    full_name=f"{first_name} {middle_name} {last_name}"
    return full_name.title()

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

例子:并非所有人都有中间名,为了让中间名变成可选的,可以给形参middle_name指定一个空的默认值,并在用户没有提供中间名时不使用这个形参

为了get_formatted_name在没有提供中间名时依然可行,可将形参middle_name的默认值设置为空字符串,并将其移到形参列表的末尾

def get_formatted_name(first_name,last_name,middle_name=''):
    if middle_name:
        full_name=f"{first_name} {middle_name} {last_name}"
    else:
        full_name=f"{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)

3.2返回字典

def build_person(first_name,last_name):
    person={'first':first_name,'last':last_name}
    return person
musician=build_person('jimi','hendrix')
print(musician)

print('\n')
def build_person(first_name,last_name,age=None):          # 新增了一个可选形参age,并将其默认值设置为特殊值none
    person={'first':first_name,'last':last_name}          # (表示变量没有值)在条件测试时,none相当于false。
    if age:
        person['age']=age
    return person
musician=build_person('jimi','hendrix',age=27)
print(musician)

3.3结合使用函数和while循环

def get_formatted_name(first_name,last_name):
    person={'first':first_name,'last':last_name}
    return person

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(f"\nhello,{formatted_name}")

4.传递列表

例子:假设有一个用户列表,我们要问候其中的每位用户

def greet_users(names):
    for name in names:
        msg=f"hello,{name.title()}!"
        print(msg)

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

4.1在函数中修改列表

一家为用户提交设计制作的3d打印模型的公司,对需要打印的设计存储在一个列表中,打印后将移到另一个列表

首先是不使用函数实现

unprinted_designs=['a','b','c']
completed_models=[]

while unprinted_designs:
    current_design=unprinted_designs.pop()
    print(f"printing model:{current_design}")
    completed_models.append(current_design)

print("\nthe following models have been printed:")
for completed_model in completed_models:
    print(completed_model)

使用函数来实现

def print_model(unprinted_designs,completed_models):
    while unprinted_designs:
        current_design = unprinted_designs.pop()
        print(f"printing model:{current_design}")
        completed_models.append(current_design)
def show_complete_models(completed_models):
    print("\nthe following models have been printed:")
    for completed_model in completed_models:
        print(completed_model)

unprinted_designs=['a','b','c']
completed_models=[]

print_model(unprinted_designs,completed_models)
show_complete_models(completed_models)

4.2禁止函数修改列表

以上面为例,即使打印好了所有设计,也要保留原来未打印的设计列表

为了解决这个问题,可向函数传递列表的副本而非原件

function_name(list_name[:])

切片表示法[:]创建列表的副本,如果不想清空未打印的设计列表,可像下面这样调用 print_model(unprinted_designs[:],completed_models)

def print_model(unprinted_designs,completed_models):
    while unprinted_designs:
        current_design = unprinted_designs.pop()
        print(f"printing model:{current_design}")
        completed_models.append(current_design)
def show_complete_models(completed_models):
    print("\nthe following models have been printed:")
    for completed_model in completed_models:
        print(completed_model)

unprinted_designs=['a','b','c']
completed_models=[]

print_model(unprinted_designs[:],completed_models)
show_complete_models(completed_models)

5.传递任意数量的实参

有时候函数不知道需要接受多少个实参,好在python允许函数从调用语句中收集任意数量的实参

def make_pizza(*topppings):
    print(topppings)
make_pizza('a')
make_pizza('b','c','d')

形参*toppings让python创建一个名为toppings的空元祖,将所有收到的值封装到这个元祖中

def make_pizza(*toppings):
    print("\nMaking a pizza with the following toppings:")
    for topping in toppings:
        print(f"-{topping}")

make_pizza('a')
make_pizza('b','c','d')

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

如果让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后

python先匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参中。

def make_pizza(size,*toppings):
    print(f"\nMaking a {size}-inch pizza with the following toppings:")
    for topping in toppings:
        print(f"-{topping}")

make_pizza(16,'a')
make_pizza(12,'b','c','d')

基于上述函数定义,python将收到的第一个值赋给形参size,将其他所有值都存储在元祖toppings中

5.2使用任意数量的关键字实参

def build_profile(first,last,**user_info):
    user_info['first_name']=first
    user_info['last_name']=last
    return user_info
user_profile=build_profile('a','b',location='c',filed='d')
print(user_profile)

**user_info要求python创建一个名为user_info的空字典,将所有接收到的名称值对都放到这个字典中

6.将函数存储在模块中

使用函数的优点之一是可将代码块与主程序分离。

还可以更进一步,将函数存储在称为模块的独立文件中,再将模块到导入到主程序中

6.1导入整个模块

模块是扩展名为.py的文件

创建文件pizza.py,在其中创建一个函数make_pizza(),这就是模块。

make_pizza()

def make_pizza(size,*toppings):
    print(f"\nMaking a {size}-inch pizza with the following toppings:")
    for topping in toppings:
        print(f"-{topping}")

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

import pizza

pizza.make_pizza(16,'a')
pizza.make_pizza(12,'a','b','c')

当使用上述import语句导入了名为module_name.py的整个模块,就可以使用下面的语法,来使用其中任何一个函数

module_name.function name()

6.2导入特定的函数

from module_name import function_name

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

from module_name import function_0,function_1,function_2

以上面为例

from pizza import make_pizza
make_pizza(16,'a')
make_pizza(12,'b','c','d')

6.3使用as给函数指定别名

from pizza import make_pizza as mp
mp(16,'a')
mp(12,'b','c','d')

6.4使用as给模块指定别名

import pizza as p
p.make_pizza(16,'a')
p.make_pizza(12,'b','c','d')

6.5导入模块中所有的函数

from pizza import *
make_pizza(16,'a')
make_pizza(12,'b','c','d')

使用并非自己编写的大型模块是,最好不要采用这种导入方式

毕设

搭建深度学习pytorch环境,运行循环神经网络模型

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值