7-用户输入和while循环

通过获取用户输入并学会控制程序的运行时间,你就能编写出交互式程序。

7.1 函数input()的工作原理

函数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

7.1.1 编写清晰的程序

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

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}!")

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

将数值输入用于计算和比较前,务必将其转换为数值表示。

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.")

7.1.3 求模运算符

求模运算符(%),将两个数相除并返回余数:

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的整数倍。

7.2 while循环简介

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

7.2.1 使用while循环

输出1到9:

current_number = 0
while current_number < 10:
    current_number += 1
    print(current_number)

你每天使用的程序很可能就包含while循环。例如,游戏使用while循环,确保在玩家想玩时不断运行,并在玩家想退出时停止运行。 

7.2.2 让用户选择何时退出

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)

7.2.3 使用标志

在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态,这个变量称为标志(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)

7.2.4 使用break退出循环

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语句。

7.2.5 在循环中使用continue

要返回循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句:

current_number = 0
while current_number < 10:
    current_number += 1
    if current_number % 2 == 0:
        continue
    
    print(current_number)

7.2.6 避免无限循环

下面这段代码就会陷入无限循环:

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,也可关闭显示输出的窗口)。

7.3 使用while循环处理列表和字典

for循环是一种遍历列表的有效方式,但不应在for循环中修改列表,否则将导致Python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用while循环。

7.3.1 在列表之间移动元素

例如在验证用户的同时将其从未验证用户列表中提取出来,再将其加入另一个已验证用户列表中:

# 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())

7.3.2 删除为特定值的所有列表元素

假设你有一个宠物列表,其中包含多个值为'cat'的元素。要删除所有这些元素,可不断运行一个while循环,直到列表中不再包含值'cat',如下所示:

pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)

while 'cat' in pets:
    pets.remove('cat')
    
print(pets)

7.3.3 使用用户输入来填充字典

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

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?

7.4 小结

在本章中,你学习了:如何在程序中使用input()来让用户提供信息;如何处理文本和数的输入,以及如何使用while循环让程序按用户的要求不断运行;多种控制while循环流程的方式:设置活动标志、使用break语句以及使用continue语句;如何使用while循环在列表之间移动元素,以及如何从列表中删除所有包含特定值的元素;如何结合使用while循环和字典。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值