侧边栏壁纸
博主头像
秋之牧云 博主等级

怀璧慎显,博识谨言。

  • 累计撰写 73 篇文章
  • 累计创建 43 个标签
  • 累计收到 6 条评论

目 录CONTENT

文章目录

循环和流程控制

秋之牧云
2024-06-15 / 0 评论 / 0 点赞 / 37 阅读 / 0 字

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)

循环语句可以配合breakcontinue 语句控制流程。

0

评论区