Python编程学习笔记(五)

八、函数

1.定义函数:def 函数名 (自变量):

 一个打印问候语的简单函数:

#定义函数:def  函数名 (自变量)
def greet_user():
    """显示简单的问候语"""
    print("Hello!")

#调用函数
greet_user()

 输出结果:

Hello!

(1)向函数传递信息:加入uesrname

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

greet_user('bob')

输出结果:

Hello, Bob!

(2)实参和形参
  username:形参
  bob:实参

2.传递实参

(1)位置实参——基于实参的顺序
注:可多次调用;注意顺序不要出错

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')
describe_pet('dog','willie')

输出结果:

I have a hamster(仓鼠).
My hamster(仓鼠)'s name is Harry.

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

(2)关键字实参——名称-值对
注:顺序可随意更换

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

输出结果:

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

(3)默认值
注:可修改

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('willie')
describe_pet('harry','hamster')

输出结果:

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

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

说明:许多调用方式是等效的;注意避免实参错误。

3.返回值 return

(1)返回简单值

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

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

输出结果:

John Lee Hooker

(2)让实参变成可选的
  并非所有人都有中间名,所以要把中间名变成可选的。可给实参middle_name指定一个默认值——空字符串,在没有中间名时不使用这个实参。
注:要把middle_name移到形参列表的末尾。

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

(3)返回字典

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=27)
print(musician)
musician=build_person('jenny','bob')
print(musician)

输出结果:

{'first': 'jimi', 'last': 'hendrix', 'age': 27}
{'first': 'jenny', 'last': 'bob'}

(4)结合使用函数和while循环

def get_formatted_name(first_name,last_name):
    full_name=first_name+' '+last_name
    return full_name.title()

while True:
    print("\nPlease input you 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 input you name:
(enter 'q' at any time to quit)
First name: jimi
Last name: hendrix

Hello, Jimi Hendrix!

Please input you name:
(enter 'q' at any time to quit)
First name: jenny
Last name: q

4.传递列表

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!

(1)在函数中修改列表

def print_models(unprinted_designs,completed_models):
    """
    模拟打印每个设计,直到没有未打印的设计为止
    打印每个设计后,都将其移到列表completed_models中
    """
    while unprinted_designs:
        current_design=unprinted_designs.pop()
        
        #模拟根据设计制作3D打印模型的过程
        print("Priting 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)

输出结果:

Priting model:dodecahedron
Priting model:robot pendant
Priting model:iphone case

The following models have been printed:
dodecahedron
robot pendant
iphone case

(2)禁止函数修改列表——切片表示法[:]创建列表的副本
  主函数中:

print_models(unprinted_designs[:],completed_models)

  即可只改变副本而不改变原件。

5.传递任意数量的实参

  形参名前加* 创建空元组
       ** 创建空字典

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

make_pizza('pepperoni')
make_pizza('apple','mushrooms','cheese','eggs')

输出结果:

('pepperoni',)
('apple', 'mushrooms', 'cheese', 'eggs')

(1)结合使用位置实参和任意数量实参(任意数量实参放到最后)

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

make_pizza(12,'pepperoni')
make_pizza(16,'apple','mushrooms','cheese','eggs')

输出结果:

Make a 12-inch pizza with the following toppings:
-pepperoni

Make a 16-inch pizza with the following toppings:
-apple
-mushrooms
-cheese
-eggs

(2)使用任意数量的关键字实参

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', 
                           age='30',
                           hight='170')
print(user_profile)

输出结果:

{'first_name': 'albert', 'last_name': 'einstein', 'age': '30', 'hight': '170'}

6.将函数存储在模块中 import 调用

(1)导入整个模块 module_name.function_name()
pizza.py文件:

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

在pizza.py所在的目录中创建另一个名为making_pizzas.py的文件:

import pizza

#指定导入的模块的名称pizza 和函数名make_pizza()
pizza.make_pizza(12,'pepperoni')
pizza.make_pizza(16,'apple','mushrooms','cheese','eggs')

输出结果:

Make a 12-inch pizza with the following toppings:
-pepperoni

Make a 16-inch pizza with the following toppings:
-apple
-mushrooms
-cheese
-eggs

(2)导入特定的函数 from module_name import function_name0, function_name1, function_name2
making_pizzas.py:

from pizza import make_pizza

make_pizza(12,'pepperoni')
make_pizza(16,'apple','mushrooms','cheese','eggs')

(3)使用as给函数指定别名 from module_name import function_name as fn
making_pizzas.py:

from pizza import make_pizza as mp

mp(12,'pepperoni')
mp(16,'apple','mushrooms','cheese','eggs')

(4)使用as给模块指定别名 import module_name as mn
making_pizzas.py:

import pizza as p

p.make_pizza(12,'pepperoni')
p.make_pizza(16,'apple','mushrooms','cheese','eggs')

(5)导入模块中的所有函数 from module_name import *
making_pizzas.py:

from pizza import *

make_pizza(12,'pepperoni')
make_pizza(16,'apple','mushrooms','cheese','eggs')

 
注意等号两边的空格不要随意添加!

参考文献:袁国忠,Python编程:从入门到实践

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值