Python中 while 循环的用法

#while循环,不断地运行,直到指定的条件不满足为止。
count = 1
while count <=5:
    print(count)
    count += 1
'''
1
2
3
4
5
'''

#while 循环的退出可以使用标志flg退出,break退出等

#使用标志退出
count =  1
active = True
while active:
    print(count)
    if count >= 5:
        active =False
    else:
        count += 1
'''
1
2
3
4
5
'''

#break 退出
count = 1
while True:
    print(count)
    if count >= 5:
        break
    else:
        count += 1
'''
1
2
3
4
5
'''

#continue,返回到循环开头,并根据条件测试结果决定是否继续执行循环
count = 1
while count <= 5:
    if count % 2 ==0:
        count += 1
        continue
    else:
        print(count)
        count += 1
'''
1
3
5
'''

#在列表之间移动元素
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []

while unconfirmed_users:
    confirmed_user = unconfirmed_users.pop() #弹出列表末尾的元素
    print('confirmeduser:' + confirmed_user)
    confirmed_users.append(confirmed_user)  #在列表中添加元素
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
    print(confirmed_user.title())
'''
confirmeduser:candace
confirmeduser:brian
confirmeduser:alice

The following users have been confirmed:
Candace
Brian
Alice
'''

#删除列表中包特定的元素
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'catt']
print(pets)

while 'cat' in pets:
    pets.remove('cat')
print(pets)
'''
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'catt']
['dog', 'dog', 'goldfish', 'rabbit', 'catt']
'''
相关推荐
©️2020 CSDN 皮肤主题: 创作都市 设计师:CSDN官方博客 返回首页