while循环简介
for循环用于对集合中的每个元素的一个代码块;
while循环不断的运行,直到指定的条件不满足为止。
使用while循环
while数数,从1-5
current = 1
while current <= 5 :
print(current)
current += 1
1
2
3
4
5
用户选择何时退出
标志:判断整个程序是否处于活跃状态的变量称为标志。
标志值:
False:让程序停止运行
True:让程序继续运行
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
active = True
while active:
message = input(prompt) if message == 'quit': active = False else: print(message)
输入值为“quit”时 active='quit' 程序结束。
Tell me something, and I will repeat it back to you: Enter 'quit' to end the program. hello hello Tell me something, and I will repeat it back to you: Enter 'quit' to end the program. quit
break·continue
命令 | 作用 |
---|---|
Break | 跳出当前循环,不在运行循环中剩余代码 |
continue | 跳出循环,返回循环的头部,继续运行下一次循环 |
current_number = 1
while current_number < 10:
current_number += 1
#当数字是偶数时跳过本次循环使用continue,退出整个循环使用break if current_number % 2 == 0: break # continue print(current_number)
while循环处理列表与字典
for循环是一种遍历列表的有效方式,但在for循环中不应该修改列表,否则将导致Python难以跟踪其中的元素。
便历列表的同时进行修改可以使用while循环 while循环同列表字典结合使用,可收集、存储并组织大量输入,供以后查看和使用
while循环处理列表元素移动
# Start out with some users that need to be verified,
# and an empty list to hold confirmed users. unconfirmed_users = ['alice', 'brian', 'candace'] confirmed_users = [] # Verify each user, until there are no more unconfirmed users. # Move each verified user into the list of confirmed users. while unconfirmed_users: current_user = unconfirmed_users.pop() print("Verifying user: " + current_user.title()) confirmed_users.append(current_user) # Display all confirmed users. print("\nThe following users have been confirmed:") for confirmed_user in confirmed_users: print(confirmed_user.title())
Verifying user: Candace
Verifying user: Brian
Verifying user: Alice
The following users have been confirmed:
Candace
Brian
Alice
while循环删除列表中特定值
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] print(pets) while 'cat' in pets: pets.remove('cat') print(pets)
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] ['dog', 'dog', 'goldfish', 'rabbit']
使用用户输入来填充字典
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Author:Jor Babe
responses = {}
# Set a flag to indicate that polling is active.
# s设置一个标志,指出调查是否继续 polling_active = True while polling_active: # Prompt for the person's name and response. # 提示输入被调查者的名字和回答 name = input("\nWhat is your name? ") response = input("Which mountain would you like to climb someday? ") # Store the response in the dictionary: # 将调查存储在字典中 responses[name] = response # Find out if anyone else is going to take the poll. # 是否还有继续参加调查者 repeat = input("Would you like to let another person respond? (yes/ no) ") if repeat == 'no': polling_active = False # Polling is complete. Show the results. # 调查结束,显示调查结果 print("\n--- Poll Results ---") for name, response in responses.items(): print(" %s would like to climb %s ."%(name,response))