If…else的进阶,用几个程序来实现讲解。
用if猜数字:
#!/usr/bin/env python # -*- coding:utf-8 -*- #Author:Mclind
age = 56
guess_age = int(input("guess age:"))
if guess_age == age: print("yes, you got it.") elif guess_age > age: print("think smaller...") else: print("think bigger...")
|
输出:
guess age:23
think bigger...
|
解释:
如要需要判断多个条件,在if…else中添加elif,需要多少添加多少,如上文程序。
但是,这样程序只能执行一次就结束了,加入次数条件控制(程序的循环执行)。
while实现循环:
#!/usr/bin/env python # -*- coding:utf-8 -*- #Author:Mclind
count = 0 while True: print("count:", count) count = count + 1 #count += 1
|
输出:
count: 102609
count: 102610
count: 102611
count: 102612…
|
解释:
while条件为真(True永远为真),代码块就一直执行(程序无限执行)。(程序中count +=1与count = count + 1是等价的)。
加入while条件循环的猜数字:
#!/usr/bin/env python # -*- coding:utf-8 -*- #Author:Mclind
age = 56
while True: guess_age = int(input("guess age:")) if guess_age == age: print("yes, you got it.") elif guess_age > age: print("think smaller...") else: print("think bigger...")
|
输出:
guess age:56
yes, you got it.
guess age:23
think bigger...
|
解释:
无论猜对错,程序无限执行,不好,改进一下:
#!/usr/bin/env python # -*- coding:utf-8 -*- #Author:Mclind
age = 56
while True: guess_age = int(input("guess age:")) if guess_age == age: print("yes, you got it.") break elif guess_age > age: print("think smaller...") else: print("think bigger...")
|
输出:
guess age:67
think smaller...
guess age:56
yes, you got it.
Process finished with exit code 0
|
解释:
break:退出,结束循环。
此时程序猜对退出执行,但猜错的话还是无限猜下去,还是不好,再改进:
#!/usr/bin/env python # -*- coding:utf-8 -*- #Author:Mclind
age = 56
count = 0
while True: if count == 3: break guess_age = int(input("guess age:")) if guess_age == age: print("yes, you got it.") break elif guess_age > age: print("think smaller...") else: print("think bigger...")
count += 1
|
输出:
guess age:1
think bigger...
guess age:2
think bigger...
guess age:3
think bigger...
Process finished with exit code 0
|
解释:
程序猜对,或者猜错三次结束执行,但是还是很low:
#!/usr/bin/env python # -*- coding:utf-8 -*- #Author:Mclind
age = 56
count = 0
while count < 3: guess_age = int(input("guess age:")) if guess_age == age: print("yes, you got it.") break elif guess_age > age: print("think smaller...") else: print("think bigger...")
count += 1
|
程序稍好看一点点,输出略,同上一个代码是一样的功能,下面while再添加一个else
#!/usr/bin/env python # -*- coding:utf-8 -*- #Author:Mclind
age = 56
count = 0
while count < 3: guess_age = int(input("guess age:")) if guess_age == age: print("yes, you got it.") break elif guess_age > age: print("think smaller...") else: print("think bigger...")
count += 1 else: print("you have tried too many times... fuck off")
|
输出:
guess age:1
think bigger...
guess age:2
think bigger...
guess age:3
think bigger...
you have tried too many times... fuck off
Process finished with exit code 0
|
解释:
输入错误三次才打印print语句,while后可以接else语句,意思是如果while都正常走完了,那么执行else后的代码块,否则(如break结束循环了)就不再执行else后的代码块。