一, while 循环
1)语法:
while 条件:
代码块
改变条件的表达式
需求点: 打印 100 遍 hello python
- # 定义一个变量 i 用来记数, 记录打印了多少遍 hello python
- i = 0
- while i<100:
- i = i + 1
- print("这是第 {} 遍打印: hello python".format(i))
运行结果:
2)死循环: 内部条件一直满足(使用 while 循环时注意死循环)
- while True:
- print("hellp python")
3)终止循环(包括死循环), 使用关键字: break(只能用在循环里面)
需要点: 当打印到第 50 遍的时候, 循环结束
- i = 0
- while i<100:
- i = i + 1
- print("这是第 {} 遍打印: hello python".format(i))
- if i == 50:
- break #条件满足直接跳出循环, 后面循环中的代码将不再执行
- print("----------end:{}--------".format(i))
- print("-------- 循环体之外的代码 --------")
运行结果:
4)中止当前本轮循环, 使用关键字 continue
中止当前本轮循环的, 进行下一轮循环的条件判断(他会执行到 continue 之后, 会直接回到 while 后面添加判读)
例如:
- i = 0
- while i < 100:
- i = i + 1
- print("这是第 {} 遍打印: hello python".format(i))
- if i == 50:
- continue
- print("----------end:{}--------".format(i))
- print("-------- 循环体之外的代码 --------")
运行结果:
5)while 循环案例
需求点: 使用 while 循环实现登录
- # 先定义已存在用户以及密码
- user_info = {
- "user":"python26","pwd":"lemonban"
- }
- # 使用 while 循环
- while True:
- username = input("请输入账号:")
- password = input("请输入密码:")
- # 判断账号密码是否正确
- if username == user_info["user"] and password == user_info["pwd"]:
- print("登录成功")
- break # 登录成功退出循环
- else:
- print("账号或密码错误")
运行结果:
Python 全栈自动化系列之 Python 编程基础(while 循环)
来源: http://www.bubuko.com/infodetail-3377386.html