python基础(4)函数用法

学习内容

1.函数形参与实参
2.返回值
3.传递列表
4.传递任意数量实参
5.将函数存储在模块中

一.函数的形参和实参

首先,先介绍一个简单的问候语函数:

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

greet_user() 

运行结果为:

Hello! 

在上面我们可以看到函数是如何来定义的(用def来定义函数)
在函数中说明它的功能。
如上边的函数其功能就是输出一句问候语。
然后还可以向函数传递一些信息,在上边的例子基础上进行改动如下:

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

输出的结果为:

Hello, Jesse!

这里传递的‘jesse’是一个实参(真实的参数)。
而接受它的一个变量username中的值为形参。
在函数greet_user()的定义中,变量username是一个形参——函数完成其工作所需的一项信息。实参是调用函数时传递给函数的信息。我们调用函数时,将要让函数使用的信息放在括号内。
1.位置实参
调用函数时,Python必须将函数调用中的每个实参都关联到函数定义中的一个形参。为此,最简单的关联方式是基于实参的顺序。这种关联方式被称为位置实参。(即实参与形参一一对应,位置实参一定要注意实参与形参的对应顺序。)
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(animal_type='hamster', pet_name='harry') 

下边的俩种形式在关键字实参下均可以:

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

3.默认值
编写函数时,可给每个形参指定默认值。在调用函数中给形参提供了实参时,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')

上述例子中用了形参的默认值。在函数调用时并未给animal——type值,故运用形参默认值,一旦实参给与了值则形参默认值不在生效。

二.返回值

首先,函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个或一组值。函数返回的值被称为返回值。(返回值让你能够将程序的大部分繁重工作移到函数中去完成,从而简化主程序。)
1.返回简单的值
例如:

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) 

运行结果为:

Jimi Hendrix 

上述例子中,返回了full name的值于主程序中,而后打印。
2.让实参变成可选的
看如下的一段程序:

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):
    person = {'first': first_name, 'last': last_name}
    return person
musician = build_person('jimi', 'hendrix')
print(musician) 

运行结果为:

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:")
      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 tell me your name:
(enter 'q' at any time to quit)
First name: eric
Last name: matthes
Hello, Eric Matthes!
Please tell me your name:
(enter 'q' at any time to quit)
First name: q 

三.传递列表

1.简单传递
例如:

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! 

2.函数中修改列表
例如:

 def print_models(unprinted_designs, completed_models):
     while unprinted_designs:
           current_design = unprinted_designs.pop()
           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) 

运行结果为:

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

四.传递任意数量实参

1.预先不知道函数需要接受多少个实参,而Python恰好允许函数从调用语句中收集任意数量的实参。
例如:

def make_pizza(*toppings):
    print(toppings)

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

运行结果为:

('pepperoni',)
('mushrooms', 'green peppers', 'extra cheese') 

上述例子中的*toppings能够接受任意数量的实参,也就是创建了一个空的元组。
2.结合位置参和任意数量的实参
例如

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

运行结果为:

Making a 16-inch pizza with the following toppings:
- pepperoni
Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese

3.使用任意数量的关键字

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) 

**user_info是一个空字典
运行结果为:

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

五.将函数存储在模块中

函数的优点之一是,使用它们可将代码块与主程序分离。将函数存储在被称为模块的独立文件中,再将模块导入到主程序中。import语句允许在当前运行的程序文件中使用模块中的代码。
1.导入整个模块
要让函数是可导入的,得先创建模块。模块是扩展名为.py的文件,包含导入到程序中的代码。下面来创建一个包含函数make_pizza()的模块,即为文件pizza.py。

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

然后在文件pizza.py目录中创建一个为making_pizzas.py的文件这个文件导入刚创建的模块,再调用make_pizza()两次(调用时,可指定导入的模的名称pizza和函数名 make_pizza(),并用句点分隔它们):

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

运行结果为:

Making a 16-inch pizza with the following toppings:
- pepperoni
Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese 

2.导入模块中的特殊函数
对于前面的making_pizzas.py示例,如果只想导入要使用的函数,代码将类似于下面这样:

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

3.使用as给模块别名

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

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

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

由于导入了每个函数,可通过名称来调用每个函数,而无需使用句点表示法。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值