1. 程式人生 > 程式設計 >Python的控制結構之For、While、If迴圈問題

Python的控制結構之For、While、If迴圈問題

傳統Python語言的主要控制結構是for迴圈。然而,需要注意的是for迴圈在Pandas中不常用,因此Python中for迴圈的有效執行並不適用於Pandas模式。一些常見控制結構如下。

  • for迴圈
  • while迴圈
  • if/else語句
  • try/except語句
  • 生成器表示式
  • 列表推導式
  • 模式匹配

所有的程式最終都需要一種控制執行流的方式。本節介紹一些控制執行流的技術。

01 for迴圈

for迴圈是Python的一種最基本的控制結構。使用for迴圈的一種常見模式是使用range函式生成數值範圍,然後對其進行迭代。

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

for i in range(3): 
print(i) 
 
'''輸出: 
0 
1 
2 
''' 

for迴圈列表

使用for迴圈的另一種常見模式是對列表進行迭代。

martial_arts = ["Sambo","Muay Thai","BJJ"] 
for martial_art in martial_arts: 
 print(f"{ martial_art} has influenced\ 
   modern mixed martial arts") 
 
'''輸出: 
Sambo has influenced modern mixed martial arts 
Muay Thai has influenced modern mixed martial arts 
BJJ has influenced modern mixed martial arts 
''' 

02 while迴圈

while迴圈是一種條件有效就會重複執行的迴圈方式。while迴圈的常見用途是建立無限迴圈。在本示例中,while迴圈用於過濾函式,該函式返回兩種攻擊型別中的一種。

def attacks(): 
 list_of_attacks = ["lower_body","lower_body","upper_body"] 
 print("There are a total of {lenlist_of_attacks)}\ 
   attacks coming!") 
 for attack in list_of_ attacks: 
  yield attack 
attack = attacks() 
count = 0 
while next(attack) == "lower_body": 
 count +=1 
 print(f"crossing legs to prevent attack #{count}") 
else: 
 count += 1 
 print(f"This is not lower body attack,\ 
I will cross my arms for# count}") 
 
'''輸出: 
There are a total of 3 attacks coming! 
crossing legs to prevent attack #1 
crossing legs to prevent attack #2 
This is not a lower body attack,I will cross my arms for #3 
''' 

03 if/else語句

if/else語句是一條在判斷之間進行分支的常見語句。在本示例中,if/elif用於匹配分支。如果沒有匹配項,則執行最後一條else語句。

def recommended_attack(position): 
 """Recommends an attack based on the position""" 
 if position == "full_guard": 
  print(f"Try an armbar attack") 
 elif position == "half_guard": 
  print(f"Try a kimura attack") 
 elif position == "fu1l_mount": 
  print(f"Try an arm triangle") 
 else: 
  print(f"You're on your own,\ 
   there is no suggestion for an attack") 
recommended_attack("full_guard")#輸出:Try an armbar attack 
recommended_attack("z_guard") 
 
#輸出:You're on your own,there is no suggestion for an attack 

04 生成器表示式

生成器表示式建立在yield語句的概念上,它允許對序列進行惰性求值。生成器表示式的益處是,在實際求值計算前不會對任何內容進行求值或將其放入記憶體。這就是下面的示例可以在生成的無限隨機攻擊序列中執行的原因。

在生成器管道中,諸如 “arm_triangle”的小寫攻擊被轉換為“ARM_TRIANGLE”,接下來刪除其中的下劃線,得到“ARM TRIANGLE”。

def lazy_return_random_attacks(): 
  """Yield attacks each time""" 
  import random 
  attacks = {"kimura": "upper_body","straight_ankle_lock": "lower_body","arm_triangle": "upper_body","keylock": "upper_body","knee_bar": "lower_body"} 
  while True: 
   random_attack random.choices(list(attacks.keys())) 
   yield random attack 
 
#Make all attacks appear as Upper Case 
upper_case_attacks = \ 
   (attack.pop().upper() for attack in \ 
   lazy_return_random_attacks()) 
next(upper-case_attacks) 
 
#輸出:ARM-TRIANGLE 
## Generator Pipeline: One expression chains into the next 
#Make all attacks appear as Upper Case 
upper-case_attacks =\ 
 (attack. pop().upper() for attack in\ 
 lazy_return_random_attacks()) 
#remove the underscore 
remove underscore =\ 
 (attack.split("_")for attack in\ 
 upper-case_attacks) 
#create a new phrase 
new_attack_phrase =\ 
 (" ".join(phrase) for phrase in\ 
 remove_underscore) 
next(new_attack_phrase) 
 
#輸出:'STRAIGHT ANKLE LOCK' 
for number in range(10): 
 print(next(new_attack_phrase)) 
 
'''輸出: 
KIMURA 
KEYLOCK 
STRAIGHT ANKLE LOCK 
''' 

05 列表推導式

語法上列表推導式與生成器表示式類似,然而直接對比它們,會發現列表推導式是在記憶體中求值。此外,列表推導式是優化的C程式碼,可以認為這是對傳統for迴圈的重大改進。

martial_arts = ["Sambo","BJJ"] 
new_phrases [f"mixed Martial Arts is influenced by \ 
 (martial_art)" for martial_art in martial_arts] 
print(new_phrases) 
['Mixed Martial Arts is influenced by Sambo',\ 
'Mixed Martial Arts is influenced by Muay Thai',\ 
'Mixed Martial Arts is influenced by BJJ'] 

06 中級主題

有了這些基礎知識後,重要的是不僅要了解如何建立程式碼,還要了解如何建立可維護的程式碼。建立可維護程式碼的一種方法是建立一個庫,另一種方法是使用已經安裝的第三方庫編寫的程式碼。其總體思想是最小化和分解複雜性。

使用Python編寫庫

使用Python編寫庫非常重要,之後將該庫匯入專案無須很長時間。下面這些示例是編寫庫的基礎知識:在儲存庫中有一個名為funclib的資料夾,其中有一個_init_ .py檔案。要建立庫,在該目錄中需要有一個包含函式的模組。

首先建立一個檔案。

touch funclib/funcmod.py

然後在該檔案中建立一個函式。

"""This is a simple module""" 
def list_of_belts_in_bjj(): 
 """Returns a list of the belts in Brazilian jiu-jitsu""" 
 belts= ["white","blue","purple","brown","black"] 
 return belts 
import sys;sys.path.append("..") 
from funclib import funcmod 
funcmod.list_of_belts_in-bjj() 
 
#輸出:['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包。

pip install pandas

另外,還可使用requirements.txt檔案安裝包。

> ca requirements.txt 
pylint 
pytest 
pytest-cov 
click 
jupyter 
nbval 
 
> pip install -r requirements.txt 

下面是在Jupyter Notebook中使用小型庫的示例。值得指出的是,在Jupyter Notebook中建立程式程式碼組成的巨型蜘蛛網很容易,而且非常簡單的解決方法就是建立一些庫,然後測試並匯入這些庫。

"""This is a simple module""" 
 
import pandas as pd 
 
def list_of_belts_in_bjj(): 
 """Returns a list of the belts in Brazilian jiu-jitsu""" 
 
 belts = ["white","black"] 
 return belts 
 
def count_belts(): 
 """Uses Pandas to count number of belts""" 
 
 belts = list_of_belts_in_bjj() 
 df = pd.Dataframe(belts) 
 res = df.count() 
 count = res.values.tolist()[0] 
 return count 
from funclib.funcmod import count_belts 
print(count_belts()) 
 
#輸出:5 

可在Jupyter Notebook中重複使用類並與類進行互動。最簡單的類型別就是一個名稱,類的定義形式如下。

class Competitor: pass

該類可例項化為多個物件。

class Competitor: pass 
conor = Competitor() 
conor.name = "Conor McGregor" 
conor.age = 29 
conor.weight = 155 
nate = Competitor() 
nate.name = "Nate Diaz" 
nate.age = 30 
nate.weight = 170 
def print_competitor _age(object): 
 """Print out age statistics about a competitor""" 
 
 print(f"{object.name} is {object.age} years old") 
print_competitor_age(nate) 
 
#輸出:Nate Diaz is 30 years old 
print_competitor_age(conor) 
 
#輸出:Conor McGregor is 29 years old 

類和函式的區別

類和函式的主要區別包括:

  • 函式更容易解釋。
  • 函式(典型情況下)只在函式內部具有狀態,而類在函式外部保持不變的狀態。
  • 類能以複雜性為代價提供更高級別的抽象。

總結

到此這篇關於Python的控制結構:For、While、If…的文章就介紹到這了,更多相關Python控制結構 If、While、For內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!