python之流程控制简介
简述:流程控制即为控制流程,即为控制程序的执行流程,分为三种流程结构,分别为顺序结构(代码从上到下按顺序执行),分支结构(if判断),循环结构(for循环和while循环)
一、if语法
1.什么是if判断
可以让计算机拥有判断能力,通过判断事物的真假,对错,是否可行等,根据不同的结果执行不同的代码块从而获得不同的结果
2.if语法
-
第一种:if 条件: # if条件结尾必须加冒号
代码块 # 同一if条件下的代码快必须缩进,用四个空格表示
例子:age_ger = 17if age_ger < 18: print("哥哥带你看金鱼")
-
第二种: if 条件:
代码块1
else : # 表示条件不成立执行else的代码块
代码块2
例子:age_ger = 19if age_ger <= 18: print("哥哥带你看金鱼")else: print("阿姨再见")
-
第三种:if 条件1:
代码块1
elif 条件2:
代码块2
elif 条件3:
代码块3
...... # 可以有很多个条件
else:
代码块
例子:age_ger = 19if age_ger <= 18: print("哥哥带你看金鱼")elif age_ger <= 24: print("小姐姐加个微信吗?")else: print("阿姨再见")
-
第四种:if 条件1:
代码块1
if 条件2: # if 条件可以嵌套
代码块2
else:
代码块3
else:
代码块4
示例:age_ger = 19is_beautiful = 0if age_ger <= 18: print("哥哥带你看金鱼")elif age_ger <= 24: print("小姐姐加个微信吗?") if is_beautiful: print("小姐姐我请你看电影吧") else: print('对不起加错了')else: print("阿姨再见")
补充:流程控制里面,0,None,[],'',{}都可以做为False用,1可以做True用
二、while循环语法
1.什么是while循环'
while循环称之为条件循环,只要满足条件,程序会一直循环执行下去
2.while语法
while True:
代码块 # 只要while的条件成立就可以一直循环执行代码块里面的程序
注意:continue:表示跳过这次循环,执行下次循环,不论continue下面还有多少代码(指同层级的)
break:表示结束当前while层的循环
当然在while套嵌循环里面也可以使用continue和break
示例1.count = 0while count <10: count +=1 if count == 7: continue print(count,end="*") 1*2*3*4*5*6*8*9*10* # countinue表示跳过当前循环执行下次循环count = 0while count <10: count +=1 if count == 7: break print(count,end="*") # 表示结束当前循环 1*2*3*4*5*6*
-
whie + else表示如果while正常执行完毕就会执行else里面代码块的的内容,如果被类似于break等以非正常形式打断程序,就不会执行else里面的内容
count = 0while count <= 5 : count += 1 print("Loop",count)else: print("循环正常执行完啦")print("-----out of while loop ------")输出Loop 1Loop 2Loop 3Loop 4Loop 5Loop 6循环正常执行完啦 #没有被break打断,所以执行了该行代码-----out of while loop ------
如果执行过程中被break,就不会执行else的语句
count = 0while count <= 5 : count += 1 if count == 3: break print("Loop",count)else: print("循环正常执行完啦")print("-----out of while loop ------")输出Loop 1Loop 2-----out of while loop ------ #由于循环被break打断了,所以不执行else后的输出语句
-
while循环嵌套+tag的使用
针对嵌套多层的while循环,如果我们的目的很明确就是要在某一层直接退出所有层的循环,其实有一个窍门,就让所有while循环的条件都用同一个变量,该变量的初始值为True,一旦在某一层将该变量的值改成False,则所有层的循环都结束
username = "jason"password = "123"count = 0tag = Truewhile tag: inp_name = input("请输入用户名:") inp_pwd = input("请输入密码:") if inp_name == username and inp_pwd == password: print("登陆成功") while tag: cmd = input('>>: ') if cmd == 'quit': tag = False # tag变为False, 所有while循环的条件都变为False break print('run <%s>' % cmd) break # 用于结束本层循环,即第一层循环 else: print("输入的用户名或密码错误!") count += 1
三、for循环语法
1.什么是for循环
for循环给我们提供一种不依赖于索引的取值方式,for循环可以做的事while循环都可以做,之所以用for循环是因为在循环取值(遍历值)时比while要简洁,for循环的语法结构为for 变量 in 容器对象,容器对象中有多少值就会循环几次。
2.for语法
注意:info = {'name':'sean', 'age':18}for i in info: print(i) # 打印字典循环时只能打印出key print(info[i]) # 索引时可以将value打印出来 nameseanage18
while语法和for语法的一个简单对比
简单版:for循环的实现方式for count in range(6): # range(6)会产生从0-5这6个数 print(count) # 复杂版:while循环的实现方式count = 0while count < 6: print(count) count += 1