用户输入和while循环
- 函数input的工作原理
- while循环简介
- 使用while循环来处理列表和字典
一、函数input()工作原理
函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在一个变量中,以方便你使用。例如,下面的程序让用户输入一些文本,再将这些文本呈现给用户:
- message = input("Tell me something, and I will repeat it back to you: ")
- print(message)
函数input()接受一个参数:即要向用户显示的提示或说明,让用户知道该如何做。在这个示例中,Python运行第1行代码时,用户将看到提示Tell me something, and I will repeat it back to you: 。程序等待用户输入,并在用户按回车键后继续运行。输入存储在变量message中,接下来的print(message)将输入呈现给用户:
- Tell me something, and I will repeat it back to you: Hello everyone!
- Hello everyone!
1.使用input()来获取字符串输入
每当你使用函数input()时都应指定清晰而易于明白的提示,准确地指出你希望用户提供什么样的信息指出用户该输入任何信息的提示都行,如下所示:
- name = input("Please enter your name: ")
- print("Hello, " + name + "!")
通过在提示末尾(这里是冒号后面)包含一个空格,可将提示与用户输入分开,让用户清楚地知道其输入始于何处,如下所示:
- Please enter your name: Eric
- Hello, Eric!
2.使用int()来获取数值输入
使用函数input() 时,Python 将用户输入解读为字符串。请看下面让用户输入其年龄的解释器会话:
- >>> age = input("How old are you? ")
- How old are you? 21
- >>> age
- '21'
用户输入的是数字21 ,但我们请求Python 提供变量age的值时,它返回的是'21'—— 用户输入的数值的字符串表示。
你试图将输入用于数值比较时,Python 会引发错误。
- >>> age = input("How old are you? ")
- How old are you? 21
- >>> age >= 18
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- TypeError: unorderable types: str() >= int()
因为它无法将字符串和整数进行比较:不能将存储在age 中的字符串'21' 与数值18 进行比较。
为解决这个问题,可使用函数int() ,它让Python 将输入视为数值。函数int() 将数字的字符串表示转换为数值表示,如下所示:
- >>> age = input("How old are you? ")
- How old are you? 21
- >>> age = int(age)
- >>> age >= 18
- True
3.求模运算符
处理数值信息时,求模运算符(%)是一个很有用的工具,它将两个数相除并返回余数:
- >>> 4 % 3
- 1
- >>> 5 % 3
- 2
- >>> 6 % 3
- 0
- >>> 7 % 3
- 1
二、while循环简介
for循环用于针对集合中的每个元素都一个代码块,而while循环不断地运行,直到指定的条件不满足为止。
1.使用 while 循环
例如,下面的while循环从1数到5:
- a = 1
- while a <= 5:
- print(a)
- a += 1
- 1
- 2
- 3
- 4
- 5
2.让用户选择何时退出
可使用while循环让程序在用户愿意时不断地运行,如下面的程序所示。我们在其中定义了一个退出值,只要用户输入的不是这个值,程序就接着运行:
- prompt = "\nTell me something, and I will repeat it back to you:"
- prompt += "\nEnter 'quit' to end the program. "
- message = ""
- while message != 'quit':
- message = input(prompt)
- print(message)
- Tell me something, and I will repeat it back to you:
- Enter 'quit' to end the program. Hello everyone!
- Hello everyone!
- Tell me something, and I will repeat it back to you:
- Enter 'quit' to end the program. Hello again.
- Hello again.
- Tell me something, and I will repeat it back to you:
- Enter 'quit' to end the program. quit
- quit
3.使用标志
在前一个示例中,我们让程序在满足指定条件时就执行特定的任务。但在更复杂的程序中,很多不同的事件都会导致程序停止运行;下面来在前一节的程序中添加一个标志。我们把这个标志命名为active (可给它指定任何名称),它将用于判断程序是否应继续运行:
- 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)
我们将变量active设置成了True ,让程序最初处于活动状态。这样做简化了while语句,因为不需要在其中做任何比较—— 相关的逻辑由程序的其他部分处理。只要变量active为True,循环就将继续运行。
4.使用 break 退出循环
要立即退出while 循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用break 语句。break语句用于控制程序流程,可使用它来控制哪些代码行将执行,哪些代码行不执行,从而让程序按你的要求执行你要执行的代码。
例如,来看一个让用户指出他到过哪些地方的程序。在这个程序中,我们可以在用户输入'quit' 后使用break 语句立即退出while 循环:
- prompt = "\nPlease enter the name of a city you have visited:"
- prompt += "\n(Enter 'quit' when you are finished.) "
- while True:
- city = input(prompt)
- if city == 'quit':
- break
- else:
- print("I'd love to go to " + city.title() + "!")
以while True打头的循环将不断运行,直到遇到break语句。这个程序中的循环不断输入用户到过的城市的名字,直到他输入'quit' 为止。用户输入'quit' 后,将执行break语句,导致Python退出循环:
- Please enter the name of a city you have visited:
- (Enter 'quit' when you are finished.) New York
- I'd love to go to New York!
- Please enter the name of a city you have visited:
- (Enter 'quit' when you are finished.) San Francisco
- I'd love to go to San Francisco!
- Please enter the name of a city you have visited:
- (Enter 'quit' when you are finished.) quit
5.在循环中使用continue
要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句,它不像break语句那样不再执行余下的代码并退出整个循环。例如,来看一个从1 数到10 ,但只打印其中偶数的循环:我们首先将a设置成了0 ,由于它小于10 ,Python进入while循环。进入循环后,我们以步长1的方式往上数,因此a为1 。接下来,if 语句检查a与2 的求模运算结果。如果结果为0 (意味着a可被2 整除),就执行continue 语句,让Python 忽略余下的代码,并返回到循环的开头。如果当前的数字不能被2 整除,就执行循环中余下的代码,Python 将这个数字打印出来:
a = 0;
while a < 10:
a = a + 1
if a % 2 == 0:
continue
print(a)
1
3
5
7
9
6.避免无限循环
- # 这个循环将没完没了地运行!
- x = 1
- while x <= 5:
- print(x)
三、使用 while 循环来处理列表和字典
到目前为止,我们每次都只处理了一项用户信息:获取用户的输入,再将输入打印出来或作出应答;循环再次运行时,我们获悉另一个输入值并作出响应。然而,要记录大量的用户和信息,需要在while 循环中使用列表和字典。
for循环是一种遍历列表的有效方式,但在for循环中不应修改列表,否则将导致Python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用while循环。通过将while循环同列表和字典结合起来使用,可收集、存储并组织大量输入,供以后查看和显示。
1.在列表间移动元素
假设有一个列表,其中包含新注册但还未验证的网站用户;验证这些用户后,如何将他们移到另一个已验证用户列表中呢?一种办法是使用一个while 循环,在验证用户的同时将其从未验证用户列表中提取出来,再将其加入到另一个已验证用户列表中。代码可能类似于下面这样:
responses = {}
# 设置一个标志,指出调查是否继续
flag = True
while flag:
# 提示输入被调查者的名字和回答
name = input("\nWhat is your name? ")
response = input("Which mountain would you like to climb someday? ")
# 将答卷存储在字典中
responses[name] = response
# 看看是否还有人要参与调查
repeat = input("Would you like to let another person respond? (yes/ no) ")
if repeat == 'no':
flag = False
# 调查结束,显示结果
print("\n--- Results ---")
for name, response in responses.items():
print(name + " would like to climb " + response + ".")
未验证用户列表为空后结束循环,再打印已验证用户列表:
What is your name? a
Which mountain would you like to climb someday? aaa
Would you like to let another person respond? (yes/ no) yes
What is your name? b
Which mountain would you like to climb someday? bbb
Would you like to let another person respond? (yes/ no) no
--- Results ---
a would like to climb aaa.
b would like to climb bbb.
2.删除包含特定值的所有列表元素
在前面内容中,我们使用函数remove() 来删除列表中的特定值,这之所以可行,是因为要删除的值在列表中只出现了一次。如果要删除列表中所有包含特定值的元素,该怎么办呢?
假设你有一个宠物列表,其中包含多个值为'cat' 的元素。要删除所有这些元素,可不断运行一个while 循环,直到列表中不再包含值'cat' ,如下所示:
- 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']
3.使用用户输入来填充字典
可使用while 循环提示用户输入任意数量的信息。下面来创建一个调查程序,其中的循环每次执行时都提示输入被调查者的名字和回答。我们将收集的数据存储在一个字典中,以便将回答同被调查者关联起来:
- responses = {}
- # 设置一个标志,指出调查是否继续
- polling_active = True
- while polling_active:
- # 提示输入被调查者的名字和回答
- name = input("\nWhat is your name? ")
- response = input("Which mountain would you like to climb someday? ")
- # 将答卷存储在字典中
- responses[name] = response
- # 看看是否还有人要参与调查
- repeat = input("Would you like to let another person respond? (yes/ no) ")
- if repeat == 'no':
- polling_active = False
- # 调查结束,显示结果
- print("\n--- Poll Results ---")
- for name, response in responses.items():
- print(name + " would like to climb " + response + ".")
如果你运行这个程序,并输入一些名字和回答,输出将类似于下面这样:
- What is your name? Eric
- Which mountain would you like to climb someday? Denali
- Would you like to let another person respond? (yes/ no) yes
- What is your name? Lynn
- Which mountain would you like to climb someday? Devil's Thumb
- Would you like to let another person respond? (yes/ no) no
- --- Poll Results ---
- Lynn would like to climb Devil's Thumb.
- Eric would like to climb Denali.