1. 简单的while示例
current_number=1 while current_number<=5 : print(current_number) current_number+=1
2.使用标志
active=True num =1 num_end=10 while active: print(num) num+=1 if num>num_end: active=False
3.使用break 退出循环
active=True num =1 num_end=10 while active: print(num) num+=1 if num>num_end: break
打印效果与上图一样
4.在循环中使用continue
current_number=0 while current_number<10: current_number+=1 if current_number%2==0: continue print(current_number)
备注:在Sublime Text等一些编辑器,不小心使用程序无限循环时,再按Ctrl + C,这样应该能够结束无限循环。
5. while处理列表
# 列表使用whlie ,在列表之间移动元素 unconfirmed_users = ['alice', 'brian', 'candace'] confirmed_users = [] while unconfirmed_users: current_user=unconfirmed_users.pop() print (F'Verifying user:{current_user.title()}') confirmed_users.append(current_user) for user in confirmed_users: print(user.title())
#删除列表中指定元素 pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] while 'cat' in pets: pets.remove('cat') print(pets)
6.while 处理字典
#字典使用whlie ,在字典之间移动元素 unconfirmed_users = {'name':['alice', 'brian', 'candace']} confirmed_users={} while unconfirmed_users['name']: current_user=unconfirmed_users['name'].pop() print(f"Verifying user: {current_user.title()}") if confirmed_users.get('name')==None: confirmed_users['name']=[current_user] else: confirmed_users['name'].append(current_user) for confirmed_user in confirmed_users['name']: print(confirmed_user.title())
标签:confirmed,users,python,current,while,num,user From: https://www.cnblogs.com/MrHSR/p/16393664.html