目录
if条件
if 条件:
语句组
if-else条件
if 条件:
语句组1
else:
语句组2
if-elif-else条件
if 条件1:
语句组1
elif 条件n:
语句n
else:
语句n+1
三元运算符
表达式1 if 条件 else 表达式2
match条件
match 语句接受一个表达式并将它的值与以一个或多个 case 语句块形式给出的一系列模式进行比较。类似于其它语言的switch语句。
def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Something's wrong with the internet"
请注意最后一个代码块: “变量名” _
被作为 通配符 并必定会匹配成功。
while循环
while 循环条件:
语句组
[else:
语句组]
for-in循环
类似其它语言的for和foreach的总和。
for 迭代变量 in 序列:
语句组
[else:
语句组]
循环技巧
enumerate()
函数
在序列中循环时,用 enumerate()
函数可以同时取出位置索引和对应的值:
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print(i, v)
...
0 tic
1 tac
2 toe
zip()
函数
同时循环两个或多个序列时,用 zip()
函数可以将其内的元素一一匹配:
>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
... print('What is your {0}? It is {1}.'.format(q, a))
...
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.
reversed()
函数
逆向循环序列时,先正向定位序列,然后调用 reversed()
函数:
>>> for i in reversed(range(1, 10, 2)):
... print(i)
...
9
7
5
3
1
sorted()
函数
按指定顺序循环序列,可以用 sorted()
函数,在不改动原序列的基础上,返回一个重新的序列:
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for i in sorted(basket):
... print(i)
...
apple
apple
banana
orange
orange
pear
set()
函数
使用 set()
函数去除序列中的重复元素。
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
... print(f)
...
apple
banana
orange
pear
items()
方法
在字典中循环时,用 items()
方法可同时取出键和对应的值:
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
... print(k, v)
...
gallahad the pure
robin the brave
break跳转
break 强行退出循环体,不再执行循环体中剩余的语句。
break
continue跳转
continue 语句用来结束本次循环,跳过本次循环体中未执行的语句,继续下次循环,直至结束。
continue
pass跳转
pass 语句不执行任何操作。语法上需要一个语句,但程序不实际执行任何动作时,可以使用该语句。
>>> while True:
... pass # Busy-wait for keyboard interrupt (Ctrl+C)
...
>>> class MyEmptyClass:
... pass
...
>>> def initlog(*args):
... pass # Remember to implement this!
...
return跳转
return 语句用来返回值,如果没有返回值可return None或省略。
return
原创文章,作者:huoxiaoqiang,如若转载,请注明出处:https://www.huoxiaoqiang.com/python/pythonlang/2716.html