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

相关文章
|
1天前
|
缓存 算法 数据处理
Python入门:9.递归函数和高阶函数
在 Python 编程中,函数是核心组成部分之一。递归函数和高阶函数是 Python 中两个非常重要的特性。递归函数帮助我们以更直观的方式处理重复性问题,而高阶函数通过函数作为参数或返回值,为代码增添了极大的灵活性和优雅性。无论是实现复杂的算法还是处理数据流,这些工具都在开发者的工具箱中扮演着重要角色。本文将从概念入手,逐步带你掌握递归函数、匿名函数(lambda)以及高阶函数的核心要领和应用技巧。
Python入门:9.递归函数和高阶函数
|
1天前
|
开发者 Python
Python入门:8.Python中的函数
### 引言 在编写程序时,函数是一种强大的工具。它们可以将代码逻辑模块化,减少重复代码的编写,并提高程序的可读性和可维护性。无论是初学者还是资深开发者,深入理解函数的使用和设计都是编写高质量代码的基础。本文将从基础概念开始,逐步讲解 Python 中的函数及其高级特性。
Python入门:8.Python中的函数
|
1天前
|
存储 SQL 索引
Python入门:7.Pythond的内置容器
Python 提供了强大的内置容器(container)类型,用于存储和操作数据。容器是 Python 数据结构的核心部分,理解它们对于写出高效、可读的代码至关重要。在这篇博客中,我们将详细介绍 Python 的五种主要内置容器:字符串(str)、列表(list)、元组(tuple)、字典(dict)和集合(set)。
Python入门:7.Pythond的内置容器
|
1天前
|
存储 索引 Python
Python入门:6.深入解析Python中的序列
在 Python 中,**序列**是一种有序的数据结构,广泛应用于数据存储、操作和处理。序列的一个显著特点是支持通过**索引**访问数据。常见的序列类型包括字符串(`str`)、列表(`list`)和元组(`tuple`)。这些序列各有特点,既可以存储简单的字符,也可以存储复杂的对象。 为了帮助初学者掌握 Python 中的序列操作,本文将围绕**字符串**、**列表**和**元组**这三种序列类型,详细介绍其定义、常用方法和具体示例。
Python入门:6.深入解析Python中的序列
|
1天前
|
知识图谱 Python
Python入门:4.Python中的运算符
Python是一间强大而且便捷的编程语言,支持多种类型的运算符。在Python中,运算符被分为算术运算符、赋值运算符、复合赋值运算符、比较运算符和逻辑运算符等。本文将从基础到进阶进行分析,并通过一个综合案例展示其实际应用。
|
1天前
|
程序员 UED Python
Python入门:3.Python的输入和输出格式化
在 Python 编程中,输入与输出是程序与用户交互的核心部分。而输出格式化更是对程序表达能力的极大增强,可以让结果以清晰、美观且易读的方式呈现给用户。本文将深入探讨 Python 的输入与输出操作,特别是如何使用格式化方法来提升代码质量和可读性。
Python入门:3.Python的输入和输出格式化
|
1天前
|
存储 Linux iOS开发
Python入门:2.注释与变量的全面解析
在学习Python编程的过程中,注释和变量是必须掌握的两个基础概念。注释帮助我们理解代码的意图,而变量则是用于存储和操作数据的核心工具。熟练掌握这两者,不仅能提高代码的可读性和维护性,还能为后续学习复杂编程概念打下坚实的基础。
Python入门:2.注释与变量的全面解析
|
机器学习/深度学习 人工智能 Python
|
23天前
|
存储 缓存 Java
Python高性能编程:五种核心优化技术的原理与Python代码
Python在高性能应用场景中常因执行速度不及C、C++等编译型语言而受质疑,但通过合理利用标准库的优化特性,如`__slots__`机制、列表推导式、`@lru_cache`装饰器和生成器等,可以显著提升代码效率。本文详细介绍了这些实用的性能优化技术,帮助开发者在不牺牲代码质量的前提下提高程序性能。实验数据表明,这些优化方法能在内存使用和计算效率方面带来显著改进,适用于大规模数据处理、递归计算等场景。
58 5
Python高性能编程:五种核心优化技术的原理与Python代码
|
2月前
|
Python
[oeasy]python055_python编程_容易出现的问题_函数名的重新赋值_print_int
本文介绍了Python编程中容易出现的问题,特别是函数名、类名和模块名的重新赋值。通过具体示例展示了将内建函数(如`print`、`int`、`max`)或模块名(如`os`)重新赋值为其他类型后,会导致原有功能失效。例如,将`print`赋值为整数后,无法再用其输出内容;将`int`赋值为整数后,无法再进行类型转换。重新赋值后,这些名称失去了原有的功能,可能导致程序错误。总结指出,已有的函数名、类名和模块名不适合覆盖赋新值,否则会失去原有功能。如果需要使用类似的变量名,建议采用其他命名方式以避免冲突。
52 14

热门文章

最新文章

推荐镜像

更多