控制流
代码布局不仅影响可读性,更体现了对代码质量的态度。一致的缩进、适当的空行、合理的行长度,这些细节共同构成了优雅的Python代码。
- 使用4个空格进行缩进
- 每行不超过79个字符
- 用空行分隔顶级函数和类定义
条件判断
条件判断是编程中非常基础且重要的概念,它允许我们根据不同的条件执行不同的代码块。
if, elif, else
if condition:
# 当条件为真时执行的代码块
elif condition:
# 当条件为假时执行的代码块
else:
# 当条件都不满足时执行的代码块
a = 62
print("exam score check:")
if a >= 60:
print("student pass")
elif a == 0:
print("student 0: not pass")
else:
print("student not pass")
一个例子
year = 1900
if year % 400 == 0:
print("This is a leap year!")
# 两个条件都满足才执行
elif year % 4 == 0 and year % 100 != 0:
print("This is a leap year!")
else:
print("This is not a leap year.")
# This is not a leap year.
my_list = [1, 2]
# 判断一个列表是否为空。
if len(my_list) > 0:
print("the first element is: ", my_list[0])
else:
print("no element.")
pass 语句
assert 语句
三元表达式(条件表达式)
expression1 if condition else expression2
三元表达式是一种简洁的条件赋值方式,相当于简化版的 if-else 语句。
循环
循环是编程中另一个重要的概念,它允许我们重复执行一段代码。
for 循环
# for 循环
total = 0
for i in range(100000):
total += i
print(total) # 4999950000
while 循环
while <condition>:
<statesments>
Python 会循环执行statesments,直到condition不满足为止。
i = 0
total = 0
while i <= 100:
total += i
i += 1
print(total) # 5050
举个例子,通过 while 遍历集合:
# 空容器会被当成False,因此可以用while循环读取容器的所有元素
plays = set(['Hamlet', 'Mac', 'King'])
while plays:
play = plays.pop()
print('Perform', play)
continue 语句
遇到 continue 的时候,程序会返回到循环的最开始重新执行。
values = [7, 6, 4, 7, 19, 2, 1]
for i in values:
if i % 2 != 0:
# 忽略奇数
continue
print(i)
# 6
# 4
# 2
break 语句
遇到 break 的时候,程序会跳出循环,不管循环条件是不是满足
command_list = ['start',
'1',
'2',
'3',
'4',
'stop',
'restart',
'5',
'6']
while command_list:
command = command_list.pop(0)
if command == 'stop':
break
print(command)
# start
# 1
# 2
# 3
# 4
异常处理
try & except &finally
捕捉不同的错误类型,尝试在下面输入框输入:-1,1,2,q
import math
while True:
try:
text = input('>')
if text[0] == 'q':
break
x = float(text)
y = 1 / math.log10(x)
print("1/log10({0}) = {1}".format(x, y))
except ValueError:
print("value must bigger than 0")
except ZeroDivisionError:
print("the value must not be 1")
try/catch 块还有一个可选的关键词 finally。
不管 try 块有没有异常, finally 块的内容总是会被执行, 而且会在抛出异常前执行,因此可以用来作为安全保证,
比如文件操作时,常在 finally 关闭文件。
try:
print(1 / 0)
except ZeroDivisionError:
print('divide by 0.')
finally:
print('finally was called.')
raise 语句
frame对except的影响
以下代码在 Python3.12.9 中依然存在。
e = 1
try:
0/0 # 此处会抛出错误,因为0不能被0除
except Exception as e:
# 此处会对覆盖e,并删除e
print(f'error info :{e}!')
print(e)
'''
输出:
error info :division by zero!
Traceback (most recent call last):
File "c:\Users\jiang\Desktop\todo\1.py", line 7, in <module>
print(e)
^
NameError: name 'e' is not defined
'''
下面的代码更有可能在生产环境中出现,原理相同,报错信息同样为:NameError: name 'e' is not defined
try:
e = eval(input("please input 0/0:"))
except Exception as e:
pass
finally:
print(e)
内置函数
以下函数大多为操作序列与控制流一起使用。
any函数、all函数
any函数和all函数用于判断一个序列中的元素是否都为真或有一个为真。通常与if语句一起使用。
any函数签名:any(iterable) -> bool
all函数签名:all(iterable) -> bool
参数说明:
iterable
:要判断的序列
返回值:
- any函数返回一个布尔值,如果序列中有一个元素为真,则返回True,否则返回False
- all函数返回一个布尔值,如果序列中所有元素都为真,则返回True,否则返回False
a = 10
b = -5
c = 0
print(all([a,b,c])) # False,都为真时为真
print(any([a,b,c])) # True,有一个为真时为真
range函数
range函数签名:range(start, stop, step) -> range
参数说明:
start
:起始值(可省略,默认为0)stop
:结束值step
:步长(可省略,默认为1,可正可负)
返回值:
- 返回一个range对象
for _ in range(10, 20, 2):
print(_)
# 10
# 12
# 14
for _ in range(10,0,-2):
print(_)
# 8
# 6
# 4
# 2
# 0
enumerate函数
enumerate函数用于遍历序列,同时获取序列的序号和值。
enumerate函数签名:enumerate(iterable, start=0) -> enumerate
参数说明:
iterable
:要遍历的序列start
:起始序号(可省略,默认为0)
返回值:
- 返回一个enumerate对象
for i, v in enumerate(['tic', 'tac', 'toe']):
print(i, v)
# 0 tic
# 1 tac
# 2 toe
for i, v in enumerate(['tic', 'tac', 'toe'], start=1):
print(i, v)
# 1 tic
# 2 tac
# 3 toe
zip函数
zip函数用于将多个序列的元素一一配对,返回一个zip对象。
zip函数签名:zip(iterable1, iterable2, ...) -> zip
参数说明:
iterable1, iterable2, ...
:要配对的序列
返回值:
- 返回一个zip对象
list_a = [1, 2, 3]
list_b = [4, 5, 6]
for a, b in zip(list_a, list_b):
print(a, b)
# 1 4
# 2 5
# 3 6