Python学习笔记05-函 数

定义函数

def greet_user():"""显示简单的问候语"""
 print("Hello!")
greet_user()

向函数传递信息

def greet_user(username):
    """ 显示简单的问候语 """
    print("Hello, " + username.title() + "!")
    greet_user('jesse')
Hello, Jesse!

传递参数

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

关键字实参

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(animal_type='hamster', pet_name='harry')

默认值

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')

等效的函数调用

describe_pet('willie')
describe_pet(pet_name='willie')

# 一只名为Harry的仓鼠
describe_pet('harry', 'hamster')
describe_pet(pet_name='harry', animal_type='hamster')
describe_pet(animal_type='hamster', pet_name='harry')

返回值

def get_formatted_name(first_name, last_name):
"""返回整洁的姓名"""
 full_name = first_name + ' ' + last_name
 return full_name.title()
 musician = get_formatted_name('jimi', 'hendrix')
print(musician)

让实参变成可选的

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)

Jimi Hendrix
John Lee Hooker

返回字典

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

def build_person(first_name, last_name):
"""返回一个字典,其中包含有关一个人的信息"""
 person = {'first': first_name, 'last': last_name}
 return person

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

结合使用函数和 while 循环

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


while True:
    print("\nPlease tell me your name:")
    f_name = input("First name: ")
    l_name = input("Last name: ")

    formatted_name = get_formatted_name(f_name, l_name)
    print("\nHello, " + formatted_name + "!")

向函数传递列表

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

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

禁止函数修改列表

function_name ( list_name [:])
print_models(unprinted_designs[:], completed_models)

传递任意数量的实参

*toppings


def make_pizza(*toppings):
"""打印顾客点的所有配料"""
    print(toppings)
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)


{'first_name': 'albert', 'last_name': 'einstein',
'location': 'princeton', 'field': 'physics'}

将函数存储在模块中

导入整个模块,要让函数是可导入的,得先创建模块。模块是扩展名为.py的文件
pizza.py

def make_pizza(size, *toppings):
"""概述要制作的比萨"""
    print("\nMaking 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')

这就是一种导入方法:只需编写一条 import 语句并在其中指定模块名,就可在程序中使用该
模块中的所有函数

导入特定的函数

你还可以导入模块中的特定函数,这种导入方法的语法如下:

from  module_name import  function_name

from  module_name import  function_0 ,  function_1 ,  function_2


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

使用 as 给函数指定别名

from pizza import make_pizza as mp

mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')

使用 as 给模块指定别名

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

导入模块中的所有函数

使用星号( * )运算符可让Python导入模块中的所有函数:

from pizza import *


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

编写函数时,需要牢记几个细节。应给函数指定描述性名称,且只在其中使用小写字母和下
划线。描述性名称可帮助你和别人明白代码想要做什么。给模块命名时也应遵循上述约定。
每个函数都应包含简要地阐述其功能的注释,该注释应紧跟在函数定义后面,并采用文档字
符串格式。文档良好的函数让其他程序员只需阅读文档字符串中的描述就能够使用它:他们完全
可以相信代码如描述的那样运行;只要知道函数的名称、需要的实参以及返回值的类型,就能在
自己的程序中使用它。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值