Python支持三种控制流结构,包括条件语句、循环语句和异常处理语句。
条件语句用来根据不同的条件执行不同的代码。在Python中,条件语句包括if语句、else语句和elif语句。例如:
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
if x > 10:
print("x is greater than 10")
elif x > 5:
print("x is greater than 5 and less than or equal to 10")
循环语句用来重复执行一组代码。在Python中,循环语句包括for循环和while循环。例如:
for i in range(5):
print(i)
while x > 0:
print(x)
x -= 1
异常处理语句用来处理程序运行时出现的异常情况。在Python中,异常处理语句包括try-except语句和try-except-else语句。例如:
try:
raise ValueError("Something went wrong!")
except ValueError as e:
print("An error occurred:", e)
try:
x = 1 / 0
except ZeroDivisionError as e:
print("An error occurred:", e)
try:
x = 1 / 0
except ZeroDivisionError as e:
print("An error occurred:", e)
else:
print("No error occurred")
finally:
print("This code is always executed")
以上是Python的一些基本控制流结构,如果你想深入了解Python,可以阅读官方文档或参考相关教程。