一文看懂Python的控制结构:For、While、If…都有了

开发 后端
传统Python语言的主要控制结构是for循环。然而,需要注意的是for循环在Pandas中不常用,因此Python中for循环的有效执行并不适用于Pandas模式。

 [[331673]]

 

传统Python语言的主要控制结构是for循环。然而,需要注意的是for循环在Pandas中不常用,因此Python中for循环的有效执行并不适用于Pandas模式。一些常见控制结构如下。

  • for循环
  • while循环
  • if/else语句
  • try/except语句
  • 生成器表达式
  • 列表推导式
  • 模式匹配

所有的程序最终都需要一种控制执行流的方式。本节介绍一些控制执行流的技术。

01 for循环

for循环是Python的一种最基本的控制结构。使用for循环的一种常见模式是使用range函数生成数值范围,然后对其进行迭代。

 

  1. res = range(3) 
  2. print(list(res)) 
  3.  
  4. #输出:[0, 1, 2] 

 

  1. for i in range(3): 
  2. print(i) 
  3.  
  4. '''输出: 
  5. ''
  • for循环列表

使用for循环的另一种常见模式是对列表进行迭代。

 

  1. martial_arts = ["Sambo","Muay Thai","BJJ"
  2. for martial_art in martial_arts: 
  3.     print(f"{ martial_art} has influenced\ 
  4.           modern mixed martial arts") 
  5.  
  6. '''输出: 
  7. Sambo has influenced modern mixed martial arts 
  8. Muay Thai has influenced modern mixed martial arts 
  9. BJJ has influenced modern mixed martial arts 
  10. ''

02 while循环

while循环是一种条件有效就会重复执行的循环方式。while循环的常见用途是创建无限循环。在本示例中,while循环用于过滤函数,该函数返回两种攻击类型中的一种。

 

  1. def attacks(): 
  2.     list_of_attacks = ["lower_body""lower_body"
  3.          "upper_body"
  4.     print("There are a total of {lenlist_of_attacks)}\ 
  5.           attacks coming!") 
  6.     for attack in list_of_ attacks: 
  7.         yield attack 
  8. attack = attacks() 
  9. count = 0 
  10. while next(attack) == "lower_body"
  11.     count +=1 
  12.     print(f"crossing legs to prevent attack #{count}"
  13. else
  14.     count += 1 
  15.     print(f"This is not lower body attack, \ 
  16. I will cross my arms forcount}") 
  17.  
  18. '''输出: 
  19. There are a total of 3 attacks coming! 
  20. crossing legs to prevent attack #1 
  21. crossing legs to prevent attack #2 
  22. This is not a lower body attack, I will cross my arms for #3 
  23. ''

03 if/else语句

if/else语句是一条在判断之间进行分支的常见语句。在本示例中,if/elif用于匹配分支。如果没有匹配项,则执行最后一条else语句。

 

  1. def recommended_attack(position): 
  2.     """Recommends an attack based on the position""" 
  3.     if position == "full_guard"
  4.         print(f"Try an armbar attack"
  5.     elif position == "half_guard"
  6.         print(f"Try a kimura attack"
  7.     elif position == "fu1l_mount"
  8.         print(f"Try an arm triangle"
  9.     else
  10.         print(f"You're on your own, \ 
  11.          there is no suggestion for an attack") 

 

  1. recommended_attack("full_guard")#输出:Try an armbar attack 

 

  1. recommended_attack("z_guard"
  2.  
  3. #输出:You're on your own, there is no suggestion for an attack 

04 生成器表达式

生成器表达式建立在yield语句的概念上,它允许对序列进行惰性求值。生成器表达式的益处是,在实际求值计算前不会对任何内容进行求值或将其放入内存。这就是下面的示例可以在生成的无限随机攻击序列中执行的原因。

在生成器管道中,诸如 “arm_triangle”的小写攻击被转换为“ARM_TRIANGLE”,接下来删除其中的下划线,得到“ARM TRIANGLE”。

 

  1.  def lazy_return_random_attacks(): 
  2.      """Yield attacks each time""" 
  3.      import random 
  4.      attacks = {"kimura""upper_body"
  5.             "straight_ankle_lock""lower_body"
  6.             "arm_triangle""upper_body"
  7.              "keylock""upper_body"
  8.              "knee_bar""lower_body"
  9.      while True
  10.          random_attack random.choices(list(attacks.keys())) 
  11.          yield random attack 
  12.  
  13. #Make all attacks appear as Upper Case 
  14. upper_case_attacks = \ 
  15.          (attack.pop().upper() for attack in \ 
  16.          lazy_return_random_attacks()) 

 

  1. next(upper-case_attacks) 
  2.  
  3. #输出:ARM-TRIANGLE 

 

  1. ## Generator Pipeline: One expression chains into the next 
  2. #Make all attacks appear as Upper Case 
  3. upper-case_attacks =\ 
  4.     (attack. pop().upper() for attack in
  5.     lazy_return_random_attacks()) 
  6. #remove the underscore 
  7. remove underscore =\ 
  8.     (attack.split("_")for attack in
  9.     upper-case_attacks) 
  10. #create a new phrase 
  11. new_attack_phrase =\ 
  12.     (" ".join(phrase) for phrase in
  13.     remove_underscore) 

 

  1. next(new_attack_phrase) 
  2.  
  3. #输出:'STRAIGHT ANKLE LOCK' 

 

  1. for number in range(10): 
  2.     print(next(new_attack_phrase)) 
  3.  
  4. '''输出: 
  5. KIMURA 
  6. KEYLOCK 
  7. STRAIGHT ANKLE LOCK 
  8. ''

05 列表推导式

语法上列表推导式与生成器表达式类似,然而直接对比它们,会发现列表推导式是在内存中求值。此外,列表推导式是优化的C代码,可以认为这是对传统for循环的重大改进。

 

  1. martial_arts = ["Sambo""Muay Thai""BJJ"
  2. new_phrases [f"mixed Martial Arts is influenced by \ 
  3.     (martial_art)" for martial_art in martial_arts] 

 

  1. print(new_phrases) 
  2. ['Mixed Martial Arts is influenced by Sambo', \ 
  3. 'Mixed Martial Arts is influenced by Muay Thai', \ 
  4. 'Mixed Martial Arts is influenced by BJJ'

06 中级主题

有了这些基础知识后,重要的是不仅要了解如何创建代码,还要了解如何创建可维护的代码。创建可维护代码的一种方法是创建一个库,另一种方法是使用已经安装的第三方库编写的代码。其总体思想是最小化和分解复杂性。

  • 使用Python编写库

使用Python编写库非常重要,之后将该库导入项目无须很长时间。下面这些示例是编写库的基础知识:在存储库中有一个名为funclib的文件夹,其中有一个_init_ .py文件。要创建库,在该目录中需要有一个包含函数的模块。

首先创建一个文件。

 

  1. touch funclib/funcmod.py 

然后在该文件中创建一个函数。

 

  1. """This is a simple module""" 
  2. def list_of_belts_in_bjj(): 
  3.     """Returns a list of the belts in Brazilian jiu-jitsu""" 
  4.     belts= ["white""blue""purple""brown""black"
  5.     return belts 

 

  1. import sys;sys.path.append(".."
  2. from funclib import funcmod 
  3. funcmod.list_of_belts_in-bjj() 
  4.  
  5. #输出:['white''blue''purple''brown''black'
  • 导入库

如果库是上面的目录,则可以用Jupyter添加sys.path.append方法来将库导入。接下来,使用前面创建的文件夹/文件名/函数名的命名空间导入模块。

  • 安装第三方库

可使用pip install命令安装第三方库。请注意,conda命令(

https://conda.io/docs/user-guide/tasks/manage-pkgs.html)是pip命令的可选替代命令。如果使用conda命令,那么pip命令也会工作得很好,因为pip是virtualenv虚拟环境的替代品,但它也能直接安装软件包。

安装pandas包。

 

  1. pip install pandas 

另外,还可使用requirements.txt文件安装包。

 

  1. > ca requirements.txt 
  2. pylint 
  3. pytest 
  4. pytest-cov 
  5. click 
  6. jupyter 
  7. nbval 
  8.  
  9. > pip install -r requirements.txt 

下面是在Jupyter Notebook中使用小型库的示例。值得指出的是,在Jupyter Notebook中创建程序代码组成的巨型蜘蛛网很容易,而且非常简单的解决方法就是创建一些库,然后测试并导入这些库。

 

  1. """This is a simple module""" 
  2.  
  3. import pandas as pd 
  4.  
  5. def list_of_belts_in_bjj(): 
  6.     """Returns a list of the belts in Brazilian jiu-jitsu""" 
  7.  
  8.     belts = ["white", "blue", "purple", "brown", "black"] 
  9.     return belts 
  10.  
  11. def count_belts(): 
  12.     """Uses Pandas to count number of belts""" 
  13.  
  14.     belts = list_of_belts_in_bjj() 
  15.     df = pd.Dataframe(belts) 
  16.     res = df.count() 
  17.     count = res.values.tolist()[0] 
  18.     return count 

 

  1. from funclib.funcmod import count_belts 

 

  1. print(count_belts()) 
  2.  
  3. #输出:5 

可在Jupyter Notebook中重复使用类并与类进行交互。最简单的类类型就是一个名称,类的定义形式如下。

 

  1. class Competitor: pass 

该类可实例化为多个对象。

 

  1. class Competitor: pass 

 

  1. conor = Competitor() 
  2. conor.name = "Conor McGregor" 
  3. conor.age = 29 
  4. conor.weight = 155 

 

  1. nate = Competitor() 
  2. nate.name = "Nate Diaz" 
  3. nate.age = 30 
  4. nate.weight = 170 

 

  1. def print_competitor _age(object): 
  2.     """Print out age statistics about a competitor""" 
  3.  
  4.     print(f"{object.name} is {object.age} years old"

 

  1. print_competitor_age(nate) 
  2.  
  3. #输出:Nate Diaz is 30 years old 

 

  1. print_competitor_age(conor) 
  2.  
  3. #输出:Conor McGregor is 29 years old 
  • 类和函数的区别

类和函数的主要区别包括:

  • 函数更容易解释。
  • 函数(典型情况下)只在函数内部具有状态,而类在函数外部保持不变的状态。
  • 类能以复杂性为代价提供更高级别的抽象。

 

责任编辑:华轩 来源: 今日头条
相关推荐

2019-07-01 09:22:15

Linux操作系统硬件

2019-05-22 09:50:42

Python沙箱逃逸网络攻击

2020-03-31 14:40:24

HashMap源码Java

2019-09-03 10:40:23

数据结构HTML编程

2016-08-18 00:21:12

网络爬虫抓取网络

2019-05-08 15:02:11

Android 10安卓谷歌

2023-07-14 08:00:00

ORMRust ORMSQL

2021-08-02 06:56:19

TypeScript编程语言编译器

2017-07-28 09:11:14

HIVEHBASE区别

2018-05-31 09:46:04

车联网智能交通ITS

2019-09-25 08:51:44

Python收藏算法

2021-02-08 22:23:16

云计算办公硬件

2022-03-29 08:02:01

数字孪生能源程序

2019-06-26 11:10:47

Python数据分析Excel

2021-05-12 15:16:17

JUCAQSJava

2021-02-21 11:25:17

云计算IaaSPaaS

2021-05-11 10:40:29

JUCAQSJava

2023-04-10 11:35:31

评估模型业务流程

2022-04-26 13:41:16

区块链比特币数据库

2023-12-18 10:45:31

点赞
收藏

51CTO技术栈公众号