《Python编程 从入门到实践》-基础知识总结6

用户输入和while循环

  • 函数input的工作原理
  • while循环简介
  • 使用while循环来处理列表和字典
-------------------------------------------------------

一、函数input()工作原理

 函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在一个变量中,以方便你使用。例如,下面的程序让用户输入一些文本,再将这些文本呈现给用户:

[python] view plain copy
  1. message = input("Tell me something, and I will repeat it back to you: ")  
  2. print(message)  

函数input()接受一个参数:即要向用户显示的提示或说明,让用户知道该如何做。在这个示例中,Python运行第1行代码时,用户将看到提示Tell me something, and I will repeat it back to you: 。程序等待用户输入,并在用户按回车键后继续运行。输入存储在变量message中,接下来的print(message)将输入呈现给用户:

[python] view plain copy
  1. Tell me something, and I will repeat it back to you: Hello everyone!  
  2. Hello everyone!  

1.使用input()来获取字符串输入


每当你使用函数input()时都应指定清晰而易于明白的提示,准确地指出你希望用户提供什么样的信息指出用户该输入任何信息的提示都行,如下所示:

[python] view plain copy
  1. name = input("Please enter your name: ")  
  2. print("Hello, " + name + "!")  

通过在提示末尾(这里是冒号后面)包含一个空格,可将提示与用户输入分开,让用户清楚地知道其输入始于何处,如下所示:

[python] view plain copy
  1. Please enter your name: Eric  
  2. Hello, Eric!  

2.使用int()来获取数值输入

使用函数input() 时,Python 将用户输入解读为字符串。请看下面让用户输入其年龄的解释器会话:

[python] view plain copy
  1. >>> age = input("How old are you? ")  
  2. How old are you? 21  
  3. >>> age  
  4. '21'  

用户输入的是数字21 ,但我们请求Python 提供变量age的值时,它返回的是'21'—— 用户输入的数值的字符串表示。

你试图将输入用于数值比较时,Python 会引发错误。

[python] view plain copy
  1. >>> age = input("How old are you? ")  
  2. How old are you? 21  
  3. >>> age >= 18  
  4. Traceback (most recent call last):  
  5. File "<stdin>", line 1in <module>  
  6. TypeError: unorderable types: str() >= int()  

因为它无法将字符串和整数进行比较:不能将存储在age 中的字符串'21' 与数值18 进行比较。

为解决这个问题,可使用函数int() ,它让Python 将输入视为数值。函数int() 将数字的字符串表示转换为数值表示,如下所示:

[python] view plain copy
  1. >>> age = input("How old are you? ")  
  2. How old are you? 21  
  3. >>> age = int(age)  
  4. >>> age >= 18  
  5. True  

3.求模运算符

处理数值信息时,求模运算符(%)是一个很有用的工具,它将两个数相除并返回余数:

[python] view plain copy
  1. >>> 4 % 3  
  2. 1  
  3. >>> 5 % 3  
  4. 2  
  5. >>> 6 % 3  
  6. 0  
  7. >>> 7 % 3  
  8. 1  
附注:如果你使用的是Python 2.7,应使用函数raw_input()来提示用户输入。这个函数与Python 3中的input()一样,也将输入解读为字符串。

二、while循环简介

for循环用于针对集合中的每个元素都一个代码块,而while循环不断地运行,直到指定的条件不满足为止。

1.使用 while 循环

例如,下面的while循环从1数到5:

[python] view plain copy
  1. a = 1  
  2. while a <= 5:  
  3.     print(a)  
  4.     a += 1  
输出:

[python] view plain copy
  1. 1  
  2. 2  
  3. 3  
  4. 4  
  5. 5  

2.让用户选择何时退出

可使用while循环让程序在用户愿意时不断地运行,如下面的程序所示。我们在其中定义了一个退出值,只要用户输入的不是这个值,程序就接着运行:

[python] view plain copy
  1. prompt = "\nTell me something, and I will repeat it back to you:"  
  2. prompt += "\nEnter 'quit' to end the program. "  
  3. message = ""  
  4. while message != 'quit':  
  5.     message = input(prompt)  
  6.     print(message)  
样例:

[python] view plain copy
  1. Tell me something, and I will repeat it back to you:  
  2. Enter 'quit' to end the program. Hello everyone!  
  3. Hello everyone!  
  4.   
  5. Tell me something, and I will repeat it back to you:  
  6. Enter 'quit' to end the program. Hello again.  
  7. Hello again.  
  8.   
  9. Tell me something, and I will repeat it back to you:  
  10. Enter 'quit' to end the program. quit  
  11. quit  

3.使用标志

在前一个示例中,我们让程序在满足指定条件时就执行特定的任务。但在更复杂的程序中,很多不同的事件都会导致程序停止运行;下面来在前一节的程序中添加一个标志。我们把这个标志命名为active (可给它指定任何名称),它将用于判断程序是否应继续运行:

[python] view plain copy
  1. prompt = "\nTell me something, and I will repeat it back to you:"  
  2. prompt += "\nEnter 'quit' to end the program. "  
  3.   
  4. active = True  
  5. while active:  
  6.     message = input(prompt)  
  7.   
  8.     if message == 'quit':  
  9.         active = False  
  10.     else:  
  11.         print(message)  

我们将变量active设置成了True ,让程序最初处于活动状态。这样做简化了while语句,因为不需要在其中做任何比较—— 相关的逻辑由程序的其他部分处理。只要变量activeTrue,循环就将继续运行。


4.使用 break 退出循环

要立即退出while 循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用break 语句。break语句用于控制程序流程,可使用它来控制哪些代码行将执行,哪些代码行不执行,从而让程序按你的要求执行你要执行的代码。

例如,来看一个让用户指出他到过哪些地方的程序。在这个程序中,我们可以在用户输入'quit' 后使用break 语句立即退出while 循环:

[python] view plain copy
  1. prompt = "\nPlease enter the name of a city you have visited:"  
  2. prompt += "\n(Enter 'quit' when you are finished.) "  
  3.   
  4. while True:  
  5.     city = input(prompt)  
  6.   
  7.     if city == 'quit':  
  8.         break  
  9.   
  10.     else:  
  11.         print("I'd love to go to " + city.title() + "!")  

while True打头的循环将不断运行,直到遇到break语句。这个程序中的循环不断输入用户到过的城市的名字,直到他输入'quit' 为止。用户输入'quit' 后,将执行break语句,导致Python退出循环:

[python] view plain copy
  1. Please enter the name of a city you have visited:  
  2. (Enter 'quit' when you are finished.) New York  
  3. I'd love to go to New York!  
  4.   
  5. Please enter the name of a city you have visited:  
  6. (Enter 'quit' when you are finished.) San Francisco  
  7. I'd love to go to San Francisco!  
  8.   
  9. Please enter the name of a city you have visited:  
  10. (Enter 'quit' when you are finished.) quit  

5.在循环中使用continue

要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句,它不像break语句那样不再执行余下的代码并退出整个循环。例如,来看一个从1 数到10 ,但只打印其中偶数的循环:我们首先将a设置成了0 ,由于它小于10 ,Python进入while循环。进入循环后,我们以步长1的方式往上数,因此a1 。接下来,if 语句检查a2 的求模运算结果。如果结果为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.避免无限循环

[python] view plain copy
  1. # 这个循环将没完没了地运行!  
  2. x = 1  
  3. while x <= 5:  
  4.     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' ,如下所示:

[python] view plain copy
  1. pets = ['dog''cat''dog''goldfish''cat''rabbit''cat']  
  2. print(pets)    
  3. while 'cat' in pets:  
  4.     pets.remove('cat')    
  5. print(pets)  
结果:
[python] view plain copy
  1. ['dog''cat''dog''goldfish''cat''rabbit''cat']  
  2. ['dog''dog''goldfish''rabbit']  

3.使用用户输入来填充字典

可使用while 循环提示用户输入任意数量的信息。下面来创建一个调查程序,其中的循环每次执行时都提示输入被调查者的名字和回答。我们将收集的数据存储在一个字典中,以便将回答同被调查者关联起来:

[python] view plain copy
  1. responses = {}    
  2. # 设置一个标志,指出调查是否继续  
  3. polling_active = True    
  4. while polling_active:  
  5.     # 提示输入被调查者的名字和回答  
  6.     name = input("\nWhat is your name? ")  
  7.     response = input("Which mountain would you like to climb someday? ")    

  8.     # 将答卷存储在字典中  
  9.     responses[name] = response  
  10.   
  11.     # 看看是否还有人要参与调查  
  12.     repeat = input("Would you like to let another person respond? (yes/ no) ")  
  13.     if repeat == 'no':  
  14.         polling_active = False  
  15.   
  16. # 调查结束,显示结果  
  17. print("\n--- Poll Results ---")  
  18. for name, response in responses.items():  
  19.     print(name + " would like to climb " + response + ".")  

如果你运行这个程序,并输入一些名字和回答,输出将类似于下面这样:

[python] view plain copy
  1. What is your name? Eric  
  2. Which mountain would you like to climb someday? Denali  
  3. Would you like to let another person respond? (yes/ no) yes  
  4.   
  5. What is your name? Lynn  
  6. Which mountain would you like to climb someday? Devil's Thumb  
  7. Would you like to let another person respond? (yes/ no) no  
  8.   
  9. --- Poll Results ---  
  10. Lynn would like to climb Devil's Thumb.  
  11. Eric would like to climb Denali.  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Taylor_29511

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值