input()

函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其赋给一个变量,以方便让你使用。

例如,下面的程序让用户输入一些文本,再将这些文本呈现给用户:

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

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

通过在提示末尾(这里是冒号后面)包含一个空格,可将提示语用户输入分开,让用户情书的知道输入始于何处

有时候,提示可能超过一行,例如,你可能需要指出获取特定输入的原因。在这种情况下,可将提示赋值给一个变量,再将该变量传递给函数input()。这样,即便提示超过一行,input函数也会非常清晰:

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

image.png

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

使用函数input()时,Python将用户输入解读为字符串。因此如果将输入作为数来使用,就会引发错误:
image.png
为了解决这个问题,可使用函数int(),它让Python将输入视为数值。函数int()将数的字符串表示转换为数值表示
image.png

While循环

可使用while循环来数数,例如下面的循环从1数到5:

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

让用户选择何时退出

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

  1. prompt = "\nTell me some thing, and I will repeat it back to you,"
  2. prompt += "\n Enter 'quit' to end the program. "
  3. message = ""
  4. while message != 'quit':
  5. message = input(prompt)
  6. # 程序将在显示消息前做简单的检查,仅在消息不是退出值时才打印它。
  7. if message != 'quit':
  8. print(message)

使用标志

在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量称为标志(flag),充当程序的交通信号灯。可以让程序在标志为True时继续运行,并在任何时间导致标志值为False时让程序停止运行。这样,在While语句中就只需要检查一个条件:标志的当前值是否为True。然后将所有其他测试(是否发生了应将标志设置为False的事件)都放在其他地方,从而让程序更整洁:

  1. prompt = "\nTell me some thing, and I will repeat it back to you,"
  2. prompt += "\n Enter '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)

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

使用break退出循环

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

:::tips 在任何Python循环中都可以使用break语句。例如,可使用break语句来退出遍历列表或字典的for循环 :::

在循环中使用continue

要返回循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句,它不像break语句那样不在执行余下的代码并退出整个循环,当执行continue语句时,Python会忽略余下的代码,并返回循环的开头。

  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整除,就执行循环中余下的代码,将这个数打印出来

避免无线循环

每个程序员都会偶尔因不小心而编写出无限循环,在循环的退出条件比较微妙时尤其如此,如果程序陷入无线循环,可按Ctrl+C,也可关闭显示程序输出的终端窗口。
要避免编写无限循环,务必对每个while循环进行测试,确保其按预期那样结束。如果你希望程序在用户输入特定值时结束,可运行程序并输入这样的值。如果在这种情况下程序没有结束,请检查程序处理这个值的方式,确认程序至少有一个这样的地方能让循环条件为False,或者让break语句得以执行。

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

for循环时一种遍历列表的有效方式,但不应在for循环中修改列表,否则将导致Python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用while循环。通过将while循环同列表和字典结合起来使用,可收集、存储并组织大量输入,供以后查看和显示。

在列表之间移动元素

  1. # 首先,创建一个待验证用户列表和一个用于存储已验证用户的空列表
  2. unconfirmed_users = ['alice','brain','candace']
  3. confirmed_users = []
  4. # 验证每个用户,直到没有未验证用户为止,将每个经过验证的用户都移到已验证用户列表中
  5. # while循环将不断运行,直到列表 unconfirmed_users 变成空的
  6. while unconfirmed_users:
  7. current_user = unconfirmed_users.pop()
  8. print(f"Verifying user:{current_user.title()}")
  9. confirmed_users.append(current_user)
  10. # 显示所有已验证的用户
  11. print("\nThe following users have been confirmed:")
  12. for confirmed_user in confirmed_users:
  13. print(confirmed_user.title())

image.png

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

  1. pets = ['dog', 'cat', 'dog', 'godfish', 'cat', 'rabbit', 'cat']
  2. print(pets)
  3. while 'cat' in pets:
  4. pets.remove('cat')
  5. print(pets)
  6. '''
  7. PS C:\Users\13581\pytest> python .\C07-02.py
  8. ['dog', 'cat', 'dog', 'godfish', 'cat', 'rabbit', 'cat']
  9. ['dog', 'dog', 'godfish', 'rabbit']
  10. '''

使用用户输入来填充字典

  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 somedat? ")
  8. # 将回答存储在字典中
  9. responses[name] = response
  10. # 看看是否还有人要参与调查
  11. repeat = input("Would you like to let another person resond? (yes/no) ")
  12. if repeat == 'no':
  13. polling_active = False
  14. # 调查结束,显示结果。
  15. print("\n--- Poll Result ---")
  16. for name, response in responses.items():
  17. print(f"{name} would like to climb {response}.")