Python基本语法——基本控制结构
1. 分支
-
python的分支结构只有if语句,没有switch case语句
-
if语句的基本结构如下:
if condition1: statement1 elif condition2: statement2 else: statement3
-
永真和永假分别使用True和False来表示
2. 循环
-
for循环
# 以下标来遍历 for i in range(0, len(a): print(a[i]) # 直接遍历元素: for value in a: print(value) # 可以在循环后面加上else表示不满足循环条件时执行 for x in a: print(x) else: print("For is end!")
-
while循环
# 普通的while循环 i = 0 while i < 10: print("This is ", i, "times!") i = i + 1 # 永真式 while True: doSomething # 带else在循环条件不成立时使用 i = 0 while < 100: print("Hello World!") i = i + 1 else: print("While loop is end!")
-
循环中也有break和continue关键字来跳出循环与跳过一轮循环
i = 0 while i < 100: i = i + 1 if i > 20 and i < 40: continue elif i > 90: break else: print("Hello World!")
3. 函数
-
函数使用def关键字来定义:
def add(x, y): return x + y # 调用 a = add(1, 4)
-
也可以定义任意参数的函数:
def add(*arges): result = 0 for x in arges: result = result + x return result # 调用 a = add(1, 2, 3, 4, 5, 6, 7, 8)
-
也可以使用字典传参
def add(**arges): result = 0 for key, value in arges.items(): if key == "fish": result = result + value * 3 elif key == "pig": result = result + value * 300 else: result = result + value * 40 return result # 调用 a = add(fish=10, chinck=20, pig=1)