第四章 了不起的分支和循环
本章节内容:
分支与循环
我们所看过的程序中,总是有一系列语句从上到下精确排列,并交由 Python忠实地执行。如果你想改变这一工作流程,应该怎么做?就像这样的情况:你需要程序作出一些决定,并依据不同的情况去完成不同的事情,例如依据每天时间的不同打印出 '早上好''Good Morning' 或 '晚上好' 'Good Evening'?正如你可能已经猜测到的那番,这是通过控制流语句来实现的。在 Python 中有三种控制流语句—— if、for 和 while 。
加载背景音乐 播放背景音乐(设置单曲循环) 我方飞机诞生 interval = 0 while True: if 用户是否点击了关闭按钮: 退出程序 interval += 1 if interval == 50: interval = 0 小飞机诞生 小飞机移动一个位置 屏幕刷新 if 用户鼠标产生移动: 我方飞机中心位置 = 用户鼠标位置 屏幕刷新 if 我方飞机与小飞机发生肢体冲突: 我方挂,播放撞机音乐 修改我方飞机图案 打印“Game over” 停止背景音乐,最好淡出
缩进
缩进是python的灵魂。缩进的严格要求使得python的代码显得非常精简并且有层次。Python开发者有意让违反了缩排規則的程序不能通过编译,以此来强迫程序员养成良好的编程习惯。並且Python 語言利用缩排表示语句块的开始和结束(Off-side 规则),而非使用花括号或者某种关键字。增加缩表示语句块的开始,而減少缩排则表示语句块的结束。缩排成为了语法的一部分。例如 if 语句,根剧 PEP 的规定,必须使用 4 个空格来表示每级缩排。使用 Tab 字符和其它数目的空格虽然都可以编译通过,但不符合编码规范。支持 Tab 字符和其它数目的空格仅仅是为兼容很旧的 Python 程式和某些有问题的编辑程式。
从上面的这段话中,提炼出几个关键点:
• 必须要通过缩进方式来表示语句块的开始和结束
• 缩进用四个空格(建议使用Tab键缩进)
提示:
1 Tab按键的使用:
2 1、缩进
3 2、IDLE会提供一些建议,例如输入pr TAB会显示所有可能的命令提供参考
1、流程控制之if...else
if 语句
if,其含义就是:conj. (表条件)如果。if 发起的就是一个条件,它是构成条件语句的关键词。
|
1
|
age = 30if age >30: print('奔三了') |
if---else
if ---else---是一个条件分支
if 条件:
条件为真(True)执行的操作
else:
条件为假(False)执行的操作
age = 30
if age >30:
print('hello,uncle')
else:
print('hello,brother')
age_of_girl=18 height=171 weight=99 is_pretty=True success=False if age_of_girl >= 18 and age_of_girl < 22 and height > 170 and weight < 100 and is_pretty == True: if success: print('表白成功,在一起') else: print('算了吧,就这样子了') else: print('菇凉好')
if … elif … elif …else
可能会有零到多个 elif 部分,else 是可选的。关键字 ‘elif’ 是 ’else if’ 的缩写,这个可以有效地避免过深的缩进。if … elif … elif … 序列用于替代其它语言中的 switch 或 case 语句。注意:可以是if---elif --elif(没有else)
score = input('>>:') score = int(score) if score >=90: print('优秀') elif score>=80: print('良好') elif score>= 70: print('普通') else: print('很差')
if 条件1: 缩进的代码块 elif 条件2: 缩进的代码块 elif 条件3: 缩进的代码块 else: 缩进的代码块
练习一:比较一下三种方式的代码执行效率
#method1 score = int(input('请输入一个分数:')) if 100 >= score >= 90: print('A') if 90 > score >= 80: print('B') if 80 > score >= 60: print('C') if 60 > score >= 0: print('D') if score < 0 or score > 100: print('输入错误!') #method2 score = int(input('请输入您的分数:')) if 100 >= score >= 90: print('A') else: if 90 > score >= 80: print('B') else: if 80 > score >= 60: print('C') else: if 60 > score >= 0: print('D') else: print('输入错误!') #method3 score = int(input('请输入一个分数:')) if 100 >= score >= 90: print('A') elif 90 > score >= 80: print('B') elif 80 > score >= 60: print('C') elif 60 > score >= 0: print('D') else: print('输入错误!')
练习二:
#用户登陆验证 #!/usr/bin/env python name=input('请输入用户名字:') password=input('请输入密码:') if name == 'egon' and password == '123': print('egon login success') else: print('用户名或密码错误')
# 如果:今天是Monday,那么:上班 # 如果:今天是Tuesday,那么:上班 # 如果:今天是Wednesday,那么:上班 # 如果:今天是Thursday,那么:上班 # 如果:今天是Friday,那么:上班 # 如果:今天是Saturday,那么:出去浪 # 如果:今天是Sunday,那么:出去浪 #方式一: today=input('>>: ') if today == 'Monday': print('上班') elif today == 'Tuesday': print('上班') elif today == 'Wednesday': print('上班') elif today == 'Thursday': print('上班') elif today == 'Friday': print('上班') elif today == 'Saturday': print('出去浪') elif today == 'Sunday': print('出去浪') else: print('''必须输入其中一种: Monday Tuesday Wednesday Thursday Friday Saturday Sunday ''') #方式二: today=input('>>: ') if today == 'Saturday' or today == 'Sunday': print('出去浪') elif today == 'Monday' or today == 'Tuesday' or today == 'Wednesday' \ or today == 'Thursday' or today == 'Friday': print('上班') else: print('''必须输入其中一种: Monday Tuesday Wednesday Thursday Friday Saturday Sunday ''') #方式三: today=input('>>: ') if today in ['Saturday','Sunday']: print('出去浪') elif today in ['Monday','Tuesday','Wednesday','Thursday','Friday']: print('上班') else: print('''必须输入其中一种: Monday Tuesday Wednesday Thursday Friday Saturday Sunday ''')
2、流程控制之while
1 为何要用循环
#我们已经学会用if .. else 来猜年龄的游戏啦,但是只能猜一次就中的机率太小了,如果我想给玩家3次机会呢?就是程序启动后,玩家最多可以试3次,这个怎么弄呢?你总不会想着把代码复制3次吧。。。。 age_of_oldboy = 48 guess = int(input(">>:")) if guess > age_of_oldboy : print("猜的太大了,往小里试试...") elif guess < age_of_oldboy : print("猜的太小了,往大里试试...") else: print("恭喜你,猜对了...") #第2次 guess = int(input(">>:")) if guess > age_of_oldboy : print("猜的太大了,往小里试试...") elif guess < age_of_oldboy : print("猜的太小了,往大里试试...") else: print("恭喜你,猜对了...") #第3次 guess = int(input(">>:")) if guess > age_of_oldboy : print("猜的太大了,往小里试试...") elif guess < age_of_oldboy : print("猜的太小了,往大里试试...") else: print("恭喜你,猜对了...") #即使是小白的你,也觉得的太low了是不是,以后要修改功能还得修改3次,因此记住,写重复的代码是程序员最不耻的行为。 那么如何做到不用写重复代码又能让程序重复一段代码多次呢? 循环语句就派上用场啦
2 条件循环:while,语法如下
while 条件:
# 循环体
# 如果条件为真,那么循环体则执行,执行完毕后再次循环,重新判断条件。。。
# 如果条件为假,那么循环体不执行,循环终止
#打印0-10 count=0 while count <= 10: print('loop',count) count+=1 #打印0-10之间的偶数 count=0 while count <= 10: if count%2 == 0: print('loop',count) count+=1 #打印0-10之间的奇数 count=0 while count <= 10: if count%2 == 1: print('loop',count) count+=1
age_of_oldboy = 56 count = 0 while count <3: guess_age = int(input("guess age:") ) if guess_age == age_of_oldboy : print("yes, you got it. ") break elif guess_age > age_of_oldboy: print("think smaller...") else: print("think bigger!") count +=1 if count == 3: countine_confirm = input("do you want to keep guessing..?") if countine_confirm != 'n': count =0 else: print("you have tried too many times..fuck off")
3 死循环
import time
num=0
while True:
print('count',num)
time.sleep(1)
num+=1
4 循环嵌套与tag
tag=True while tag: ...... while tag: ........ while tag: tag=False
5、练习,要求如下:
1 循环验证用户输入的用户名与密码
2 认证通过后,运行用户重复执行命令
3 当用户输入命令为quit时,则退出整个程序
#实现一: name='egon' password='123' while True: inp_name=input('用户名: ') inp_pwd=input('密码: ') if inp_name == name and inp_pwd == password: while True: cmd=input('>>: ') if not cmd:continue if cmd == 'quit': break print('run <%s>' %cmd) else: print('用户名或密码错误') continue break #实现二:使用tag name='egon' password='123' tag=True while tag: inp_name=input('用户名: ') inp_pwd=input('密码: ') if inp_name == name and inp_pwd == password: while tag: cmd=input('>>: ') if not cmd:continue if cmd == 'quit': tag=False continue print('run <%s>' %cmd) else: print('用户名或密码错误')
6、while循环练习题
#1. 使用while循环输出1 2 3 4 5 6 8 9 10 #2. 求1-100的所有数的和 #3. 输出 1-100 内的所有奇数 #4. 输出 1-100 内的所有偶数 #5. 求1-2+3-4+5 ... 99的所有数的和 #6. 用户登陆(三次机会重试) #7:猜年龄游戏 要求: 允许用户最多尝试3次,3次都没猜对的话,就直接退出,如果猜对了,打印恭喜信息并退出 #8:猜年龄游戏升级版 要求: 允许用户最多尝试3次 每尝试3次后,如果还没猜对,就问用户是否还想继续玩,如果回答Y或y, 就继续让其猜3次,以此往复,如果回答N或n,就退出程序 如何猜对了,就直接退出
#题一 count=1 while count <= 10: if count == 7: count+=1 continue print(count) count+=1 count=1 while count <= 10: if count != 7: print(count) count+=1 #题目二 res=0 count=1 while count <= 100: res+=count count+=1 print(res) #题目三 count=1 while count <= 100: if count%2 != 0: print(count) count+=1 #题目四 count=1 while count <= 100: if count%2 == 0: print(count) count+=1 #题目五 res=0 count=1 while count <= 5: if count%2 == 0: res-=count else: res+=count count+=1 print(res) #题目六 count=0 while count < 3: name=input('请输入用户名:') password=input('请输入密码:') if name == 'egon' and password == '123': print('login success') break else: print('用户名或者密码错误') count+=1 #题目七 age_of_oldboy=73 count=0 while count < 3: guess=int(input('>>: ')) if guess == age_of_oldboy: print('you got it') break count+=1 #题目八 age_of_oldboy=73 count=0 while True: if count == 3: choice=input('继续(Y/N?)>>: ') if choice == 'Y' or choice == 'y': count=0 else: break guess=int(input('>>: ')) if guess == age_of_oldboy: print('you got it') break count+=1
count=1 res1 =0 res2=0 while count <= 10: if count % 2 == 0: res2 -= count # print(res2) elif count % 2 == 1: res1 += count count += 1 print(res1+res2)
3、流程控制之for
1 迭代式循环:for,语法如下
for i in range(10):
缩进的代码块
4、break 退出整个循环
while True:
print(1)
break
print(2)
上面的代码会先输出1,然后遇到break,就退出当前循环,所以不再打印出2了
5、continue退出当前循环
while True:
print(1)
continue
print(2)
6、丰富的else
6.1while+else
while count <3: guess_age = int(input("guess age:") ) if guess_age == age_of_oldboy : print("yes, you got it. ") break elif guess_age > age_of_oldboy: print("think smaller...") else: print("think bigger!") count +=1 else: print("you have tried too many times..fuck off")
age_of_oldboy = 56 count = 0 while count <3: guess_age = int(input("guess age:") ) if guess_age == age_of_oldboy : print("yes, you got it. ") break elif guess_age > age_of_oldboy: print("think smaller...") else: print("think bigger!") count +=1 if count == 3: countine_confirm = input("do you want to keep guessing..?") if countine_confirm != 'n': count =0 else: print("you have tried too many times..fuck off")
6.2for+else
age_of_oldboy = 56 for i in range(3): guess_age = int(input("guess age:") ) if guess_age == age_of_oldboy : print("yes, you got it. ") break elif guess_age > age_of_oldboy: print("think smaller...") else: print("think bigger!") else: print("you have tried too many times..fuck off")
作业:
[课后作业] 第007、008讲:了不起的分支和循环2 | 课后测试题及答案
[课后作业] 第009讲:了不起的分支和循环3 | 课后测试题
扩展阅读

浙公网安备 33010602011771号