1 while 循环
语法
while 条件: 执行代码。。。
简单吧, while
就是当的意思,当山峰没有棱角的时候,当河水。。。,sorry , while
指 当其后面的条件 成立 ,就执行while
下面的代码
- 从0打印到100的程序,每循环一次,+1
#!/usr/bin/env python #$ coding:utf-8 $ #__Author__:Peter Du count = 0 while count <=100: print("loop",count) count += 1 print("----loop end----")
结果
count = 0 while count<= 100: if count % 2 ==0: print("loop",count) count += 1 print("----loop end----") #运行结果 loop 82 loop 84 loop 86 loop 88 loop 90 loop 92 loop 94 loop 96 loop 98 loop 100 ----loop end----
#第50次不打印,第60-80打印对应值的平方 count = 0 while count <= 100: if count == 50: pass elif 60 <= count <= 80: print("loop",count**2) else: print("loop",count) count += 1 print("----loop end----") #运行结果 loop 46 loop 47 loop 48 loop 49 loop 51 loop 52 loop 53 loop 54 loop 55 loop 56 loop 57 loop 58 loop 59 loop 3600 loop 3721 loop 3844 loop 3969 loop 4096 loop 4225
2 死循环:dead loop
有一种循环叫死循环,一经运行,就一直运行
while 是只要后边条件成立,(也就是条件结果为真)就一直执行,怎么让条件为真呢?
count = 0 while True: #True本身就是真呀 print("你是风儿我是沙,缠缠绵绵到天涯...",count) count +=1
3 循环终止语句
如果在循环过程中,因某些原因,不想循环,需用break 或者 continue 语句
- break 用于结束一个循环,跳出循环体执行循环后面的语句
- continue 和break 有点类似,区别在于continue 只是终止本次循环,接着还执行后面的循环,break 则完全终止循环
break 例子
count = 0 while count <= 100: print("loop",count) if count == 5: break count += 1 print("---out of while loop---") #运行结果 loop 0 loop 1 loop 2 loop 3 loop 4 loop 5 ---out of while loop---
continue 案例
count = 0
while count <= 100:
print("loop",count)
if count == 5:
continue
count += 1
print("---out of while loop---")
#运行结果
loop 0 loop 1 loop 2 loop 3 loop 4 loop 5 loop 5 loop 5 loop 5 loop 5 loop 5 # 一直循环下去 ...
continue 案例2
count = 0 while count <= 100: count += 1 if count > 5 and count <95: continue print("loop ",count) #运行结果 loop 1 loop 2 loop 3 loop 4 loop 5 loop 95 loop 96 loop 97 loop 98 loop 99 loop 100 loop 101 Process finished with exit code 0
3 猜年龄
练习1
age = 22 n=0 while n < 3: print("input you age") user_age = int(input()) if user_age < age: print("small") elif user_age > age: print("big") else: print("bingo") break n += 1 if n==3: choice = input("请问你还想继续游戏吗?y|n") if choice=='y': n=0 else: break
#运行结果
input you age
10
small
input you age
30
big
input you age
22
bingo
Process finished with exit code 0
练习2
from random import randint num = randint(1,100) print("请输入你的数字") bingo = False while bingo == False: user_num = int(input()) if user_num < num: print("small") elif user_num > num: print("big") else: print("bingo") bingo = True #运行结果 请输入你的数字 10 small 50 big 30 small 40 big 35 bingo Process finished with exit code 0
4 while ...else 语法
与其它语言else 一般只与if 搭配不同,在Python 中还有个while ...else 语句
while 后面的else 作用是指,当while 循环正常执行完,中间没有被break 中止的话,就会执行else后面的语句