#!/usr/bin/env python # coding: utf-8 # # Table of Contents #
# # Python 流程控制 # ## if 条件判断 # # if 语句; 由 **if 关键字**、 **判定语句**、 **:冒号** 组成,判定一个条件是否成立。 # # 如果条件成立,则执行 **if** 下面缩进的代码, 如果不成立则执行 **else** 下面的缩进代码块 # In[1]: user = "liang" password = '123' user_name = input("Please input user name:") user_password = input("Password:") if user_name == user and user_password == password: print("Welcome login...") else: print("account or password error!") # **多条件判断:** # 通过 **elif 关键字** 添加一个条件, 可以使用多个 **elif** 来添加很多条件。 # # 如果 **if** 没有命中, 则判断 **elif** 中的条件,如果 if and 所有elif 中的条件都没有命中就会执行最后的else 下面的缩进代码块。 # In[2]: age = 12 num = 0 while True: if num < 5: guess_num = input("猜猜我的年龄:") if guess_num.isdigit(): if int(guess_num) == age: print("恭喜你,猜对了!") break elif int(guess_num) > age: print("大了!") else: print("小了") else: print("您的输入有误,请输入数字!") num += 1 else: print("尝试次数太多") break # In[3]: # 三元运算 (简单版的ifelse,中能写一行) name = "alex" if 1 == 10 else "SB" # 如果1=1为真那么name = alex,不然则name = SB print(name) # ## for 循环 # # for循环是Python中一个通用的序列迭代器,可以遍历任何有序的序列对象内的元素。for语句可以用于字符串、列表、元组、其他任何可迭代对象。 # # for循环首行定义了一个赋值目标,或者多个目标,以及你想遍历得对象。首行后面是你想要重复得代码块。 # # 当for循环时,会逐个将序列对象中的元素赋值给目标,然后为每个元素执行循环主体,循环主体一般使用赋值的目标来引用序列里面得元素。当循环体执行完后,控制权重新回到循环体顶端就会目标变量自动设成下一个元素,直到序列中最后一个元素后结束。 # In[4]: for i in range(5): print(i) # 在同途也可以通过 **break** 语句退出循环: # In[5]: for i in range(5): if i == 3: break print(i) # 还有 **continue** 语句,可以跳出一次循环,我们在写程序的时候可以设置一个if条件,满足了就跳过后续操作直接到下次循环: # In[6]: for i in range(5): if i == 3: continue print(i) # ## while 循环 # # 判断一个循环条件,如果为真则一直循环,所以也可以把条件设置为 **True** 变成无限循环,或者条件不为真循环结束,循环过程中遇到break则退出循环,遇到continue跳过当次循环。 # In[7]: count = 0 while True: # 将while循环条件设置为True,下面循环体会一直循环,直到天荒地老。 count += 1 print("你是风儿我是沙,缠缠绵绵到天涯...", count) if count == 10: print("去你妈的风和沙,你们这些脱了裤子是人,穿上裤子是鬼得臭男人..") break # 跳出循环,天荒地老得循环结束。 # In[8]: count = 0 while True: count += 1 if count > 10 and count < 15: # 10~115 之间得会执行下面的continue语句,不执行打印"你是风儿我是沙,缠缠绵绵到天涯。。。" continue print("你是风儿我是沙,缠缠绵绵到天涯...", count) if count == 20: print("去你妈的风和沙,你们这些脱了裤子是人,穿上裤子是鬼得臭男人..") break # In[9]: # while 动态条件 import time count = 0 run_forever = True while run_forever: # 设置一个动态的循环条件 count += 1 if count == 9: run_forever = False # 重置循环条件,这样下面得语句还能执行,只有回到开头得时候发现调节不满足才会不执行; #break # 用这个结束循环的话,到这个语句会立刻结束,下面的代码将不会执行; print("loop:", count) time.sleep(3) # time模块,等待10秒再进行下一步 # In[10]: # while嵌套,跳出多级循环 loop1 = 0 # 设定loop1 and loop2这两个计数器 loop2 = 0 flag = True while flag: loop1 += 1 print("loop1:", loop1) while True: loop2 += 1 if loop2 == 5: flag = False # 循环到子级里面,想退出,我退出这级退出得同时还需要让父级也退出不循环了,设置得这个循环条件就起到作用了,设置为False break # 跳出我自己这级循环 print('loop2:', loop2)