• 7-用户输入和while循环


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

    7.1 函数input()的工作原理

    函数input()接受一个参数——要向用户显示的提示(prompt)或说明,让用户知道该如何做。

    1. prompt = "\nTell me something, and I will repeat it back to you:"
    2. message=input(prompt)

    注意 Sublime Text等众多编辑器不能运行提示用户输入的程序。你可以使用SublimeText来编写提示用户输入的程序,但必须从终端运行它们。详情请参阅1.5节。或者如下:

     

     最后在cmd窗口中输入python parrot.py

    7.1.1 编写清晰的程序

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

    name = input("请输入你的名字: ")

     提示可能超过一行时,可将提示赋给一个变量,再将该变量传递给函数input():

    1. prompt = "If you tell us who you are, we can personalize the messages you see."
    2. prompt += "\nWhat is your first name? "
    3. name = input(prompt)
    4. print(f"\nHello, {name}!")

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

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

    1. height = input("How tall are you, in inches? ")
    2. height = int(height)
    3. if height >= 48:
    4. print("\nYou're tall enough to ride!")
    5. else:
    6. print("\nYou'll be able to ride when you're a little older.")

    7.1.3 求模运算符

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

    1. number = input("Enter a number, and I'll tell you if it's even or odd: ")
    2. number = int(number)
    3. if number % 2 == 0:
    4. print(f"\nThe number {number} is even.")
    5. else:
    6. 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:

    1. current_number = 0
    2. while current_number < 10:
    3. current_number += 1
    4. print(current_number)

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

    7.2.2 让用户选择何时退出

    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. if message != 'quit':
    7. print(message)

    7.2.3 使用标志

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

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

    7.2.4 使用break退出循环

    break语句用于控制程序流程,可用来控制哪些代码行将执行、哪些代码行不执行,从而让程序按你的要求执行你要执行的代码。

    例如,来看一个让用户指出他到过哪些地方的程序。

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

    注意 在任何Python循环中都可使用break语句。

    7.2.5 在循环中使用continue

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

    1. current_number = 0
    2. while current_number < 10:
    3. current_number += 1
    4. if current_number % 2 == 0:
    5. continue
    6. print(current_number)

    7.2.6 避免无限循环

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

    1. current_number = 0
    2. while current_number < 10:
    3. 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 在列表之间移动元素

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

    1. # Start with users that need to be verified,
    2. # and an empty list to hold confirmed users.
    3. unconfirmed_users = ['alice', 'brian', 'candace']
    4. confirmed_users = []
    5. # Verify each user until there are no more unconfirmed users.
    6. # Move each verified user into the list of confirmed users.
    7. while unconfirmed_users:
    8. current_user = unconfirmed_users.pop()
    9. print(f"Verifying user: {current_user.title()}")
    10. confirmed_users.append(current_user)
    11. # Display all confirmed users.
    12. print("\nThe following users have been confirmed:")
    13. for confirmed_user in confirmed_users:
    14. print(confirmed_user.title())

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

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

    1. pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
    2. print(pets)
    3. while 'cat' in pets:
    4. pets.remove('cat')
    5. print(pets)

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

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

    1. responses = {}
    2. # Set a flag to indicate that polling is active.
    3. polling_active = True
    4. while polling_active:
    5. # Prompt for the person's name and response.
    6. name = input("\nWhat is your name? ")
    7. response = input("Which mountain would you like to climb someday? ")
    8. # Store the response in the dictionary.
    9. responses[name] = response
    10. # Find out if anyone else is going to take the poll.
    11. repeat = input("Would you like to let another person respond? (yes/ no) ")
    12. if repeat == 'no':
    13. polling_active = False
    14. # Polling is complete. Show the results.
    15. print("\n--- Poll Results ---")
    16. for name, response in responses.items():
    17. 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循环和字典。

  • 相关阅读:
    【youcans 的 OpenCV 例程200篇】180.基于距离变换的分水岭算法
    MySQL - Heap 表是什么?
    以太坊“共识层”客户端prysm和teku对比选型
    MySQL 性能监控
    04.9. 环境和分布偏移
    (数据科学学习手札145)在Python中利用yarl轻松操作url
    C# EF框架增加和查询
    IDEA spring-boot项目启动,无法加载或找到启动类问题解决
    Python常见面试题
    琐碎的容易忽视的知识
  • 原文地址:https://blog.csdn.net/daqi1983/article/details/125484982