if语句
非零数值、非空字符串、非空list等,会判断为
True
,否则为False
age = 3
if age >= 18:
print('adult')
elif age >= 6:
print('teenager')
else:
print('kid')
match语句
score = 'B'
match score:
case 'A':
print('score is A.')
case 'B':
print('score is B.')
case 'C':
print('score is C.')
case _: # _表示匹配到其他任何情况
print('score is ???.')
match
语句除了可以匹配简单的单个值外,还可以匹配多个值、匹配一定范围,并且把匹配后的值绑定到变量
age = 8
match age:
case x if x < 10: # if x < 10 范围匹配,匹配到就将值绑定到变量x上
print(f'< 10 years old: {x}')
case 10:
print('10 years old.')
case 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18: # 多值匹配
print('11~18 years old.')
case 19:
print('19 years old.')
case _:
print('not sure.')
match
语句匹配列表
args = ['gcc', 'hello.c', 'world.c']
# args = ['clean']
# args = ['gcc']
match args:
# 如果仅出现gcc,报错:
case ['gcc']:
print('gcc: missing source file(s).')
# 出现gcc,且至少指定了一个文件:
case ['gcc', file1, *files]:
print('gcc compile: ' + file1 + ', ' + ', '.join(files))
# 仅出现clean:
case ['clean']:
print('clean')
case _:
print('invalid command.')
for-in循环
names = ['Michael', 'Bob', 'Tracy']
for name in names:
print(name)
sum = 0
for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
sum = sum + x
print(sum) # 55
range()
函数
r = range(1, 4)
print(type(r)) # <class 'range'>
print(list(r)) # [1, 2, 3]
print(list(range(5))) # [0, 1, 2, 3, 4]
while循环
sum = 0
n = 99
while n > 0:
sum = sum + n
n = n - 2
print(sum)
循环语句可以配合break
和continue
语句控制流程。
评论区