Python编程入门到实践 - 笔记( 8 章)

简介:

第 8 章主要练习了各种函数,内容如下

定义一个简单的函数

向函数传递信息

什么是形参

什么是实参

位置参数

多次调用函数

关键字实参

默认值参数

返回值 return

让参数编程可选的

返回字典

结合使用函数和 while 循环

传递列表

在函数中修改列表

传递任意数量的实参

传递任意数量的参数并循环打印

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

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

导入整个模块

导入特定的函数

使用 as 给函数指定别名

使用 as 给模块指定别名

导入模块中所有的函数



定义一个简单的函数

直接调用函数,就能打印

--------------------------

def greet_user():    
     print("Hello!")     
greet_user()

---------------------------

Hello!



向函数传递信息

username 只是一个形参

------------------------------------------------------

def greet_user(username):    
     print("Hello, " + username.title() + "!")     
greet_user('zhao')

------------------------------------------------------

Hello, Zhao!

 


什么是形参?

以上面的代码为例。username 就是形参,它只代表 greet_user 这个函数需要传递一个参数

至于它是叫 username 还是 nameuser 都无所谓

什么实参?

以上面的代码为例。’zhao’ 就是实参,一句话总结就是真正要让代码执行的参数



置实参

函数括号中指定了位置实参的顺序

输入参数必须按照形参提示操作

总之就是位置实参的顺序很重要

-------------------------------------------------------------------------------------------

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

-------------------------------------------------------------------------------------------

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



多次调用函数

------------------------------------------------------------------------------------------

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.



关键字实参

调用函数的时候,连同形参指定实参,就算是位置错了也能正常调用

------------------------------------------------------------------------------------------

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(pet_name='willie', animal_type='dog')

------------------------------------------------------------------------------------------

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

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



默认值

在设定函数 describe_pet 形参中指定一个参数,调用的时候

可以不用指定,默认就能调用

------------------------------------------------------------------------------------------

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

------------------------------------------------------------------------------------------

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


还可以更简单的调用

------------------------------------------------------------------------------------------

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

------------------------------------------------------------------------------------------

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



返回值

return  full_name.title()  将 full_name 的值转换为首字母大写格式

并将结果返回到函数调用行

变量 full_name  的行中两个 + 中间的单引号中间需要有一个空格

如果没有空格,打印出来的效果也是两个

-----------------------------------------------------------------

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



让参数变成可选的

Python将非空字符串解读为 True,如果没有 middle_name 参数,执行 else 代码

必须确保 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



返回字典

----------------------------------------------------------------

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

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

----------------------------------------------------------------

{'first': 'jimi', 'last': 'hendrix'}



以上面的代码为例,增加一个形参 age,并将其设置为空字符串

如果用户输入了姓名,就将其添加到字典中

-----------------------------------------------------------------    

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=18)    
print(musician)

-----------------------------------------------------------------

{'first': 'jimi', 'last': 'hendrix', 'age': 18}



结合使用函数和 while 循环

如果用户输入 q,可以随时退出

----------------------------------------------------------------------------------

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: zhao    
Last name: lulu

Hello, Zhao Lulu!

Please tell me your name:   
(enter 'q' at any time to quit)    
First name: q



传递列表

函数中的 greet_users( ) names 参数只是一个形参,

而实参则是要传入的列表

----------------------------------------------------

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!



在函数中修改列表

-------------------------------------------------------------------------------------------

unprinted_models = ['iphone case', 'robot pendant', 'dodecahedron']   
completed_models = []

while unprinted_models:   
     current_design = unprinted_models.pop()    
     print("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)

-------------------------------------------------------------------------------------------

Printing model: dodecahedron   
Printing model: robot pendant    
Printing model: iphone case

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


重新组织以上代码,用函数的方式调用

-------------------------------------------------------------------------------------------

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


   

传递任意数量的实参

-----------------------------------------------------------------------------

def make_pizza(*toppings):   
     print(toppings)

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

-----------------------------------------------------------------------------

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



传递任意数量的参数并循环打印

----------------------------------------------------------------------------

def make_pizza(*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')

----------------------------------------------------------------------------

Making a pizza with the following toppings:   
- pepperoni

Making a pizza with the following toppings:   
- 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(17, 'pepperoni')   
make_pizza(19, 'mushrooms', 'green peppers', 'extra cheese')

-----------------------------------------------------------------------------------------------------

Making a 17-inch pizza with the following toppings:   
- pepperoni

Making a 19-inch pizza with the following toppings:   
- mushrooms    
- green peppers    
- extra cheese



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

先定义一个空列表

for 循环中将参数添加到 profile 字典中,并用 return 返回

---------------------------------------------------------------

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



导入整个模块

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

----------------------------------------------------------------------------------------

Making a 16-inch pizza with the following toppings:   
- pepperoni

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



导入特定的函数

---------------------------------------------------------------------------------

from pizza import make_pizza

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  


  

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



导入模块中所有的函数

-----------------------------------------------------------------------------------

from pizza import *

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

本文转自   mlwzby   51CTO博客,原文链接:http://blog.51cto.com/aby028/1965495

相关文章
|
2天前
|
Python
在Python中快捷引入缺失包的技巧和实践
在Python中快捷引入缺失包的技巧和实践
9 0
|
2天前
|
人工智能 Python
Python中的反对称矩阵:理论、应用与代码实践
Python中的反对称矩阵:理论、应用与代码实践
17 1
|
3天前
|
存储 Python 容器
Python高级编程
Python集合包括可变的set和不可变的frozenset,用于存储无序、不重复的哈希元素。创建集合可使用{}或set(),如`my_set = {1, 2, 3, 4, 5}`。通过add()添加元素,remove()或discard()删除元素,如`my_set.remove(3)`。
|
3天前
|
机器学习/深度学习 数据采集 数据可视化
利用Python进行历史数据预测:从入门到实践的两个案例分析
利用Python进行历史数据预测:从入门到实践的两个案例分析
16 1
|
3天前
|
测试技术 Python
Python模块化方式编程实践
Python模块化编程提升代码质量,包括:定义专注单一任务的模块;使用`import`导入模块;封装函数和类,明确命名便于重用;避免全局变量降低耦合;使用文档字符串增强可读性;为每个模块写单元测试确保正确性;重用模块作为库;定期维护更新以适应Python新版本。遵循这些实践,可提高代码可读性、重用性和可维护性。
21 2
|
5天前
|
Java 开发者 索引
Python基础语法:类笔记
本篇博文是把自己在学习python类的过程中自己理解和笔记,一点一点总结的写出出来,做一个总结,加深对面向对象编程的理解。
|
8天前
|
机器学习/深度学习 人工智能 算法
【Python 机器学习专栏】强化学习在游戏 AI 中的实践
【4月更文挑战第30天】强化学习在游戏AI中展现巨大潜力,通过与环境交互和奖励信号学习最优策略。适应性强,能自主探索,挖掘出惊人策略。应用包括策略、动作和竞速游戏,如AlphaGo。Python是实现强化学习的常用工具。尽管面临训练时间长和环境复杂性等挑战,但未来强化学习将与其他技术融合,推动游戏AI发展,创造更智能的游戏体验。
|
8天前
|
机器学习/深度学习 自然语言处理 语音技术
【Python 机器学习专栏】Python 深度学习入门:神经网络基础
【4月更文挑战第30天】本文介绍了Python在深度学习中应用于神经网络的基础知识,包括神经网络概念、基本结构、训练过程,以及Python中的深度学习库TensorFlow和PyTorch。通过示例展示了如何使用Python实现神经网络,并提及优化技巧如正则化和Dropout。最后,概述了神经网络在图像识别、语音识别和自然语言处理等领域的应用,并强调掌握这些知识对深度学习的重要性。随着技术进步,神经网络的应用将持续扩展,期待更多创新。
|
8天前
|
机器学习/深度学习 运维 算法
【Python机器学习专栏】异常检测算法在Python中的实践
【4月更文挑战第30天】本文介绍了异常检测的重要性和在不同领域的应用,如欺诈检测和网络安全。文章概述了四种常见异常检测算法:基于统计、距离、密度和模型的方法。在Python实践中,使用scikit-learn库展示了如何实现这些算法,包括正态分布拟合、K-means聚类、局部异常因子(LOF)和孤立森林(Isolation Forest)。通过计算概率密度、距离、LOF值和数据点的平均路径长度来识别异常值。
|
8天前
|
机器学习/深度学习 数据采集 算法
【Python机器学习专栏】支持向量机(SVM)在Python中的实践
【4月更文挑战第30天】SVM是一种高效的监督学习算法,适用于分类和回归,尤其擅长处理高维和非线性问题。通过寻找最大边际超平面来分隔数据,SVM具有高效性、鲁棒性、灵活性和稀疏性等特点。