
导读:本文介绍Python中的常见控制结构。
-
for循环 -
while循环 -
if/else语句 -
try/except语句 -
生成器表达式 -
列表推导式 -
模式匹配
res = range(3)
print(list(res))
#输出:[0, 1, 2]
for i in range(3):
print(i)
'''输出:
0
1
2
'''
-
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
'''
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
'''
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
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
'''
martial_arts = ["Sambo", "Muay Thai", "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']
-
使用Python编写库
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']
-
导入库
-
安装第三方库
pip install pandas
> ca requirements.txt
pylint
pytest
pytest-cov
click
jupyter
nbval
> pip install -r requirements.txt
"""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", "blue", "purple", "brown", "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
-
类
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
-
类和函数的区别
类和函数的主要区别包括:
-
函数更容易解释。 -
函数(典型情况下)只在函数内部具有状态,而类在函数外部保持不变的状态。 -
类能以复杂性为代价提供更高级别的抽象。
📚推荐阅读 READ MORE
(点击下方图片阅读)
Python告诉你:粽子甜咸之争谁胜出?吃货最爱买谁家的粽子?

📌CDA课程咨询
喜欢本篇内容请点个“在看”哦!❤️

