条件、循环

0 阅读1分钟

条件判断

age = 3
if age >= 18:
    print('adult')
elif age >= 6:
    print('teenager')
else:
    print('kid')

match

针对某个变量匹配若干种情况,可以用match

score = 80
match score:
    case 10:
        print('A')
    case 80:
        print('B')
    case _: # _表示匹配到其他任何情况
        print('C')

match语句的case非常灵活

age = 15

match age:
    case x if x < 10:
        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.')

循环

for循环

names = ['Bob', 'Tom', 'Jerry']
for name in names:
    print(name)

while循环

break 和 continue

sum = 0
n = 0
while n < 100:
    sum = sum + n
    n = n + 1
print(sum)