控制语句
流程控制语句
流程控住语句常用的是 if/else
和 match
。
if/else
:
a=3
b=5
if a<b:
print("a<b") # a<b
elif a==b:
print("a==b")
else:
print("a>b")
match
:
match语句是Python 3.10+引入的新语法。
def http_status(status):
match status:
case 200:
return "OK"
case 404:
return "Not Found"
case 500:
return "Server Error"
case _: # 默认情况
return "Unknown Status"
print(http_status(200)) # OK
print(http_status(404)) # Not Found
print(http_status(503)) # Unknown Status
循环语句
循环语句一般常用的是 for
循环和 while
循环。
for
:
# 遍历列表
for fruit in ["apple", "banana", "cherry"]:
print(fruit) # apple banana cherry
# 遍历字符串
for char in "Python":
print(char) # P y t h o n
# 遍历字典
person = {"name": "Alice", "age": 25, "city": "New York"}
for key, value in person.items():
print(f"{key}: {value}") # name: Alice age: 25 city: New York
# 遍历范围
for i in range(1, 6): # 从1到5
print(i) # 1 2 3 4 5
while
:
count = 0
while count < 5:
# break中断
if(count == 3):
break
print(count) # 0 1 2
count += 1