1. 函数input()的工作原理
函数input()让程序暂停运行,等待用户输入一些文本
- 获取用户输入后,Python将其赋给一个变量,以供使用
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
编写清晰的程序
- 每当使用
函数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}!")
使用int()来获取数值输入
- 使用
函数input()时,Python将用户输入解读为字符串,无法进行数值操作
- 使用
函数int()时,Python将用户输入解读为数值
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.")
2. while循环简介
for循环用于针对集合中的每个元素都执行一个代码块,而while循环则不断运行,直到指定的条件不满足为止
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
让用户选择何时退出
prompt = "Tell 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 = "Tell 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退出整个循环
- 使用
continue退出本次循环
3. 使用while循环处理列表和字典
在列表之间移动元素
unconfirmed_users = ['alice', 'brain', 'candace']
confirmed_users = []
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print(f"Verifying user: {current_user.title()}")
confirmed_users.append(current_user)
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())

删除为特定值的所有列表元素
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)

使用用户输入来填充字典
polling_active = True
while polling_active:
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':
polling_active = False
print("\n--- Poll Results ---")
for name, response in responses.items():
print(f"{name} would like to climb {response}.")

文章中的所有代码经测试均可成功编译运行,可直接复制。具有显然结果或简单结论的代码不展示运行结果。如有问题欢迎随时交流~