Python3——分支、循环
说在前面
python中的代码块使用缩进来区分,而不是其他类C语言中使用{ code }来表示一个代码块。
python中使用的缩进是4个空格,相邻且相同缩进的代码属于同一级。
if 、elif、else
a = True
b = False
if a == True:
if b == False:
print("a is True and b is False")
else:
print("a is True and b is True")
elif a == False:
if b == False:
print("a is False and b is False")
else:
print("a is False and b is True")
else:
print("something wrong")
注意:
1、python中的判断条件不需要使用()括起来,直接跟在if、elif的后面,要有一个空格和前面的if、elif分隔。
2、python中if和elif后面的条件,以及满足条件后,要执行的语句,之间使用“:”来分隔。
3、使用缩进来表示层级、嵌套关系。
4、可以使用pass占位语句,不会进行任何操作。
5、python中没有其他语言中的switch、case结构。
6、python中没有else if、只有elif(和shell一样)
while
while和if的结构很相似。
#计算0到10的总和
cnt = 0
sum = 0
while cnt <= 10:
sum += cnt
cnt += 1
print("the result is", sum)
需要注意的是,python的while中,在循环条件不满足的时候,支持一个else操作。
#计算0到10的总和
cnt = 0
sum = 0
while cnt <= 10:
sum += cnt
cnt += 1
else:
print("the value of cnt large than 10")
print("the result is", sum)
#输出
#the value of cnt large than 10
#the result is 55
其实这个操作,看自己的习惯吧,即使不用else,在while循环的后面写一条语句,也会顺序执行到。
注意不要尝试在else中修改迭代器的值,尝试再次进入循环。这是错误的想法,因为,只有当循环不满足条件的时候,才会执行到else,之后不会再进入到while中。
比如下面的做法是错误的。
#计算0到10的总和
cnt = 0
sum = 0
first_time = 0
while cnt <= 10:
sum += cnt
cnt += 1
else:
#如果是第一次不满足while循环的条件,就将cnt置为1
#尝试再次进入上面这个while循环,但是会失败
if first_time == 0:
cnt = 1
first_time = 1
print("the value of cnt is", cnt)
print("the result is", sum)
# 输出
# the value of cnt is 1
# the result is 55
注意:
1、python中没有do while循环。
2、python中没有goto语句,所以不能在循环中使用goto到其他地方。
3、循环条件如果是数值的自增或者自减的时候,注意python中没有“--”和“++”运算符,所以不要尝试使用i++或者i--,包括++i,--i,这些都是不支持的。还是老老实实用-=或者+=吧。
4、while后面的else表示,整个循环正常结束,并不是使用break强制退出的,这里可以做其他处理
for
for主要用来“遍历”。遍历的对象可以是:list、tuple、set、dict
for fruit in ["apple", "banana", "orange", "pear"]:
if fruit == "orange":
print("catch the orange")
break # break打断循环后,不会执行与for对应的else语句
elif fruit == "banana":
print("discard the banana")
continue
else:
print(fruit)
print("print a fruit")
else:
print("for end")
# 输出
# apple
# print a fruit
# discard the banana
# catch the orange
# 注意没有打印else中的for end
for item in [[1, 2, 3], [4,5,6]]:
for i in item:
if i == 2:
break #打断内层循环,并不会打破外层循环
else:
print(i, end=" ")
else:
print("printed all list")
# 输出
# 1 4 5 6 printed all list
其他语言中的for循环,可以指定循环的次数,以及每次循环后的迭代器的操作。python中只有一种格式,但是可以使用下面的一些方法实现他们的做法。
使用range(start, end, step=1)生成一个
for x in range(0, 10):
print(x, end=" ")
# 0 1 2 3 4 5 6 7 8 9
for x in range(10, 0, -1):
print(x, end=" ")
# 10 9 8 7 6 5 4 3 2 1
for x in range(0, 10, 2):
print(x, end=" ")
# 0 2 4 6 8
实现其他语言中的for循环
a = ["apple", "orange", "banana", "pear"]
for index in range(0, len(a)):
print(a[index])
等同于其他语言中的for:
for (int i = 0; i < len(a); i++) {
print a[i]
}
浙公网安备 33010602011771号