通过获取用户输入并学会控制程序的运行时间,你就能编写出交互式程序。
函数input()接受一个参数——要向用户显示的提示(prompt)或说明,让用户知道该如何做。
- prompt = "\nTell me something, and I will repeat it back to you:"
- message=input(prompt)
注意 Sublime Text等众多编辑器不能运行提示用户输入的程序。你可以使用SublimeText来编写提示用户输入的程序,但必须从终端运行它们。详情请参阅1.5节。或者如下:


最后在cmd窗口中输入python parrot.py
通过在提示末尾(这里是冒号后面)包含一个空格,可将提示与用户输入分开,让用户清楚地知道其输入始于何处,如下所示:
name = input("请输入你的名字: ")
提示可能超过一行时,可将提示赋给一个变量,再将该变量传递给函数input():
- prompt = "If you tell us who you are, we can personalize the messages you see."
- prompt += "\nWhat is your first name? "
-
- name = input(prompt)
- print(f"\nHello, {name}!")
将数值输入用于计算和比较前,务必将其转换为数值表示。
- height = input("How tall are you, in inches? ")
- height = int(height)
-
- if height >= 48:
- print("\nYou're tall enough to ride!")
- else:
- print("\nYou'll be able to ride when you're a little older.")
求模运算符(%),将两个数相除并返回余数:
- number = input("Enter a number, and I'll tell you if it's even or odd: ")
- number = int(number)
-
- if number % 2 == 0:
- print(f"\nThe number {number} is even.")
- else:
- print(f"\nThe number {number} is odd.")
练习7-1:汽车租赁
编写一个程序,询问用户要租赁什么样的汽车,并打印一条消息,下面是一个例子。Let me see if I can find you a Subaru.
练习7-2:餐馆订位
编写一个程序,询问用户有多少人用餐。如果超过8位,就打印一条消息,指出没有空桌;否则指出有空桌。
练习7-3:10的整数倍 让用户输入一个数,并指出该数是否是10的整数倍。
for循环用于针对集合中的每个元素都执行一个代码块,而while循环则不断运行,直到指定的条件不满足为止。
输出1到9:
- current_number = 0
- while current_number < 10:
- current_number += 1
- print(current_number)
你每天使用的程序很可能就包含while循环。例如,游戏使用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)
-
- if message != 'quit':
- print(message)
在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态,这个变量称为标志(flag)。
- 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)
break语句用于控制程序流程,可用来控制哪些代码行将执行、哪些代码行不执行,从而让程序按你的要求执行你要执行的代码。
例如,来看一个让用户指出他到过哪些地方的程序。
- 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(f"I'd love to go to {city.title()}!")
注意 在任何Python循环中都可使用break语句。
要返回循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句:
- current_number = 0
- while current_number < 10:
- current_number += 1
- if current_number % 2 == 0:
- continue
-
- print(current_number)
下面这段代码就会陷入无限循环:
- current_number = 0
- while current_number < 10:
- print(current_number)
如果程序陷入无限循环,可按Ctrl + C,也可关闭显示程序输出的终端窗口。
要避免编写无限循环,确认程序至少有一个地方能让循环条件为False,或者让break语句得以执行。
注意 Sublime Text等一些编辑器内嵌了输出窗口,可在输出窗口中单击鼠标,再按Ctrl + C,这样应该能够结束无限循环。
练习7-4:比萨配料
编写一个循环,提示用户输入一系列比萨配料,并在用户输入'quit'时结束循环。每当用户输入一种配料后,都打印一条消息,指出我们会在比萨中添加这种配料。
练习7-5:电影票
有家电影院根据观众的年龄收取不同的票价:不到3岁的观众免费;3~12岁的观众收费10美元;超过12岁的观众收费15美元。请编写一个循环,在其中询问用户的年龄,并指出其票价。
练习7-6:三种出路
以不同的方式完成练习7-4或练习7-5,在程序中采取如下做法。
▲ 在while循环中使用条件测试来结束循环。
▲ 使用变量active来控制循环结束的时机。
▲ 使用break语句在用户输入'quit'时退出循环。
练习7-7:无限循环
编写一个没完没了的循环,并运行它(要结束该循环,可按Ctrl +C,也可关闭显示输出的窗口)。
for循环是一种遍历列表的有效方式,但不应在for循环中修改列表,否则将导致Python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用while循环。
例如在验证用户的同时将其从未验证用户列表中提取出来,再将其加入另一个已验证用户列表中:
- # Start with 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(f"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())
假设你有一个宠物列表,其中包含多个值为'cat'的元素。要删除所有这些元素,可不断运行一个while循环,直到列表中不再包含值'cat',如下所示:
- pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
- print(pets)
-
- while 'cat' in pets:
- pets.remove('cat')
-
- print(pets)
下面创建一个调查程序,其中的循环每次执行时都提示输入被调查者的名字和回答。我们将收集的数据存储在一个字典中,以便将回答同被调查者关联起来:
- responses = {}
-
- # Set a flag to indicate that polling is active.
- 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(f"{name} would like to climb {response}.")
练习7-8:熟食店
创建一个名为sandwich_orders的列表,在其中包含各种三明治的名字,再创建一个名为finished_sandwiches的空列表。遍历列表sandwich_orders,对于其中的每种三明治,都打印一条消息,如I made your tuna sandwich,并将其移到列表finished_sandwiches中。所有三明治都制作好后,打印一条消息,将这些三明治列出来。
练习7-9:五香烟熏牛肉卖完了
使用为完成练习7-8而创建的列表sandwich_orders,并确保'pastrami'在其中至少出现了三次。在程序开头附近添加这样的代码:打印一条消息,指出熟食店的五香烟熏牛肉(pastrami)卖完了;再使用一个while循环将列表sandwich_orders中的'pastrami'都删除。确认最终的列表finished_sandwiches未包含'pastrami'。
练习7-10:梦想的度假胜地 编写一个程序,调查用户梦想的度假胜地。使用类似于下面的提示,并编写一个打印调查结果的代码块。
If you could visit one place in the world, where would you go?
在本章中,你学习了:如何在程序中使用input()来让用户提供信息;如何处理文本和数的输入,以及如何使用while循环让程序按用户的要求不断运行;多种控制while循环流程的方式:设置活动标志、使用break语句以及使用continue语句;如何使用while循环在列表之间移动元素,以及如何从列表中删除所有包含特定值的元素;如何结合使用while循环和字典。