python流程控制语法
常用流程控制语法
- if...else...
- for...
- while...
- break语句及continue语句
一,条件分支结构
- if...else...
if<条件判断>:
<执行1>
else:
<执行2>
示例:
name = "cc" username = input("Input name:") if username == name: print("Welcom Login...") else: print("Invalid name")
- if...elif...else...
if<条件判断1>:
<执行1>
elif<条件判断2>:
<执行2>
else:
<执行3>
示例:
age_of_cc = 23 in_age = int(input("age:")) if age_of_cc == in_age: print("yes,you got it...") elif age_of_cc > in_age: print("think bigger!") else: print("think smaller!")
二,for循环
- for <循环变量> in <可迭代对象>:
<循环体>
range(start_num,end_num,step_size)其中start_num为起始数,end_num为结束数,step_size为步长
不指定具体数据时,默认start_num为0,步长为1
示例:
for i in range(5): print(i)
输出结果为:
0 1 2 3 4
for i in range(1,10,3): print(i)
输出结果为:
1 4 7
#循环打印可迭代对象的值list2 = [1,2,3,4,5,6,7,8,9,10] for i in list2: print(i)
输出结果为:
1 2 3 4 5 6 7 8 9 10
三,while循环
- while True:
<循环体>
示例:
a = 1 while True: if a ==5: break print(a) a += 1
输出结果为:
1 2 3 4
四,结束及跳过循环
break为直接结束当前循环层
示例:
#外层循环执行5次for i in range(5): for j in range(5): #break结束循环不输出j的2,3,4 if j ==2: break print(j)
输出结果为:
0 1 0 1 0 1 0 1 0 1
continue为跳过本次循环
示例:
#外层循环执行5次 for i in range(5): for j in range(5): #continue跳过本次循环不输出j的2 if j ==2: continue print(j)
输出结果为:
0 1 3 4 0 1 3 4 0 1 3 4 0 1 3 4 0 1 3 4
相关推荐
elizabethxxy 2020-11-06
pythonxuexi 2020-10-30
retacnyue 2020-09-28
pythonxuexi 2020-09-06
Morelia 2020-09-04
zhaobig 2020-08-17
linkequa 2020-08-16
CloudXli 2020-08-14
kikaylee 2020-08-12
LowisLucifer 2020-08-09
xiesheng 2020-08-06
Tristahong 2020-08-05
CatherineC00 2020-08-01
Andrewjdw 2020-07-26
reallyr 2020-07-18
wordmhg 2020-07-16
yawei 2020-07-06
zlfing 2020-07-07