python流程控制之while

本文详细介绍了Python中的while循环用法,包括基础语法、多个实例演示,以及如何使用break语句手动终止循环。通过阅读,读者可以深入理解while循环在Python编程中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

while用法

while 条件:
----pass

例子1
while 4>3:
  print('hello world')
  
'''
while是没有次数限制,不知道什么时候结束
只要满足条件就会无限打印 'hello world' 
'''
例子2
'''
当把 while 循环下面的子分支执行完毕以后,程序会返回while条件判断语句
是一个加强版的if
'''
while 4>3:
    print('你是谁')
    print('你吃饭了吗')
    print('吃过了')
例子3
cases = [
    {'url':'user/login','method':'get','param':'username,password'},
    {'url':'user/info','method':'post','param':'username,password'},
    {'url':'user/register','method':'post','param':'username,password'}
]

index = 0
while index < len(cases):
    print(cases[index])
    index += 1

执行结果:
{'url': 'user/login', 'method': 'get','param':'username,password'}
{'url': 'user/info', 'method': 'post', 'param':'username,password'}
{'url': 'user/register', 'method': 'post', 'param': 'username,password'}
break 手动终止循环
cases = [
    {'url':'user/login','method':'get','param':'username,password'}, 
    {'url':'user/info','method':'post','param':'username,password'},
    {'url':'user/register','method':'post','param':'username,password'}
]
index = 0
while True:
    print(cases[index])
    if index == 1:
        break
    index += 1

执行结果:
{'url': 'user/login', 'method': 'get', 'param': 'username,password'}
{'url': 'user/info', 'method': 'post', 'param': 'username,password'}		

因为cases的索引是 0,1,2 ,这里有个条件,如果索引等于1的时候,就直接终止循环所以结果只有两个

再来一个简单点的例子
'''当 a < 10 的时候停止循环'''

a = 0
while a < 10:
    print(a)
    a += 1

执行结果:
0,1,2,3,4,5,6,7,8,9
'''while 嵌套 if ,当a == 5 的时候跳出循环'''
a = 0
while True:
    print(a)
    if a == 5:
        break
    a += 1

执行结果:
0,1,2,3,4,5
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值