python流程控制语法

2021-02-13 22:16

阅读:322

标签:break   pytho   分支   continue   got   span   默认   条件   迭代   

常用流程控制语法

  1. if...else...
  2. for...
  3. while...
  4. break语句及continue语句

一,条件分支结构

  • if...else...

    if:

      

    else:

      

    示例:

name = "cc"

username = input("Input name:")

if username == name:
    print("Welcom Login...")

else:
    print("Invalid name")
  • if...elif...else...

    

    if:

      

    elif:

      

    else:

      

    示例:

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

  

  

python流程控制语法

标签:break   pytho   分支   continue   got   span   默认   条件   迭代   

原文地址:https://www.cnblogs.com/coc-Life/p/12725367.html


评论


亲,登录后才可以留言!