3. 分支与循环
3.1 分支结构
if
语句的五种语法
# 1
if condition:
statement(s)
# 2
if condition:
statement(s)
else:
statement(s)
# 3
if condition1:
statement(s)
elif conditions2:
statement(s)
elif condition3:
statement(s)
# 4
if condition1:
statement(s)
elif conditions2:
statement(s)
elif condition3:
statement(s)
else:
statement(s)
# 5
statement(s) if condition else statement(s)
a = 3
b = 5
if a < b:
small = a
else:
small = b
# <=>
small = a if a < b else b
3.2 循环结构
while
循环语句
while condition:
statement(s)
sum = 0
i = 1
while i <= 100000:
sum += i
i += 1
print(sum) # 5000050000
break
语句(执行过程中遇到break
语句则跳出循环体,but只能跳出一层)
while True:
answer = input("主人可以停下来了么?")
if answer == "可以":
break
print("好累~~")
continue
语句(执行过程中遇到continue
语句则跳出本轮循环)
i = 0
while i < 10:
i += 1
if i % 2 == 0:
continue
print(i)
'''
1
3
5
7
9
'''
else
语句(当循环条件不再为真的时候,else
语句才会被执行,也就是说如果使用break
语句强制中止一个循环但循环条件依旧为真,则else
语句不会被执行)
i = 0
while i < 10:
i += 1
print("这是循环内,i为:", i)
else:
print("这是循环外")
'''
这是循环内,i为: 1
这是循环内,i为: 2
这是循环内,i为: 3
这是循环内,i为: 4
这是循环内,i为: 5
这是循环内,i为: 6
这是循环内,i为: 7
这是循环内,i为: 8
这是循环内,i为: 9
这是循环内,i为: 10
这是循环外
'''
i = 0
while i < 10:
i += 1
print("这是循环内,i为:", i)
if i == 5:
break
else:
print("这是循环外")
'''
这是循环内,i为: 1
这是循环内,i为: 2
这是循环内,i为: 3
这是循环内,i为: 4
这是循环内,i为: 5
'''
- 循环的嵌套
# 九九乘法表
i = 1
while i <= 9:
j = 1
while j <= i:
print(j, "*", i, "=", j*i, end = " ")
j += 1
print()
i += 1
'''
1 * 1 = 1
1 * 2 = 2 2 * 2 = 4
1 * 3 = 3 2 * 3 = 6 3 * 3 = 9
1 * 4 = 4 2 * 4 = 8 3 * 4 = 12 4 * 4 = 16
1 * 5 = 5 2 * 5 = 10 3 * 5 = 15 4 * 5 = 20 5 * 5 = 25
1 * 6 = 6 2 * 6 = 12 3 * 6 = 18 4 * 6 = 24 5 * 6 = 30 6 * 6 = 36
1 * 7 = 7 2 * 7 = 14 3 * 7 = 21 4 * 7 = 28 5 * 7 = 35 6 * 7 = 42 7 * 7 = 49
1 * 8 = 8 2 * 8 = 16 3 * 8 = 24 4 * 8 = 32 5 * 8 = 40 6 * 8 = 48 7 * 8 = 56 8 * 8 = 64
1 * 9 = 9 2 * 9 = 18 3 * 9 = 27 4 * 9 = 36 5 * 9 = 45 6 * 9 = 54 7 * 9 = 63 8 * 9 = 72 9 * 9 = 81
'''
for
循环语句
for each in "abcd":
print(each)
'''
a
b
c
d
'''
range()
函数
range(stop) # [0, stop)
for i in range(5):
print(i)
'''
0
1
2
3
4
'''
range(start, stop) # [start, stop)
for i in range(5, 10):
print(i)
'''
5
6
7
8
9
'''
range(start, stop, step) # [start, stop)中步长为step取值
for i in range(5, 10, 2):
print(i)
'''
5
7
9
'''
欢迎私信交流python(师从小甲鱼)