一、input() 函数的工作原理
input() 函数让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python 将其赋给一个变量,以便使用。
message = input("Tell me something, and I will repeat it back to you: ")
print(message)'''
结果:
Tell me something, and I will repeat it back to you: Hi, xiaolouo
Hi, xiaolouo
'''
1. int() 来获取数值输入
在使用 input() 函数时,Python 会将用户输入解读为字符串。
>>> age = input('How old are you?') How old are you?21
>>> age
'21'
当试图将该输入用于数值比较时,Python 会报错,因为它无法将字符串和整数进行比较
>>> age >= 18
Traceback (most recent call last): File "<python-input-2>", line 1, in <module>
age >= 18 TypeError: '>=' not supported between instances of 'str' and 'int'
为了解决这个问题,可使用函数 int() 将输入的字符串转换为数值,确保能够成功地执行比较操作:
>>> age = int(age)
>>> age >= 18
True
2. 求模运算符
求模运算符(%)是个很有用的工具,它将两个数相除并返回余数:
>>> 4 % 3
1
>>> 5 % 3
2
二、while 循环简介
for 循环用于针对集合中的每个元素执行一个代码块,而 while 循环则不断地运行,直到指定的条件不再满足为止
1. 使用 while 循环
可以使用 while 循环来数数。例如,下面的 while 循环从 1 数到 5:
current_number = 1
while current_number <= 5:print(current_number)current_number += 1'''
结果:
1
2
3
4
5
'''
2. 让用户选择何时退出
我们在其中定义了一个退出值,只要用户输入的不是这个值,程序就将一直运行:
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'q' to end the program."
message = ''
while message != 'q':message = input(prompt)print(message)
'''
结果:
Tell me something, and I will repeat it back to you:
Enter 'q' to end the program.w
wTell me something, and I will repeat it back to you:
Enter 'q' to end the program.r
rTell me something, and I will repeat it back to you:
Enter 'q' to end the program.q
q'''
3. 使用标志
在要求满足很多条件才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量称为标志(flag),充当程序的交通信号灯。可以让程序在标志为 True 时继续运行,并在任何事件导致标志的值为False 时让程序停止运行。这样,在 while 语句中就只需检查一个条件:标志的当前值是否为 True。
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'q' to end the program."
message = ''
active = True
while active:message = input(prompt)if message == 'q':active = Falseelse:print(message)'''
结果:
Tell me something, and I will repeat it back to you:
Enter 'q' to end the program.1
1Tell me something, and I will repeat it back to you:
Enter 'q' to end the program.2
2Tell me something, and I will repeat it back to you:
Enter 'q' to end the program.q
'''
4. 使用 break 退出循环
如果不管条件测试的结果如何,想立即退出 while 循环,不再运行循环中余下的代码,可使用 break 语句。break 语句用于控制程序流程,可用来控制哪些代码行将执行、哪些代码行不执行,从而让程序按你的要求执行你要执行的代码。
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'q' to end the program."
message = ''
while True:city = input(prompt)if city == 'q':breakelse:print(f"I'd love {city}.")'''
结果:
Tell me something, and I will repeat it back to you:
Enter 'q' to end the program.sh
I'd love sh.Tell me something, and I will repeat it back to you:
Enter 'q' to end the program.yn
I'd love yn.Tell me something, and I will repeat it back to you:
Enter 'q' to end the program.q'''
5. 在循环中使用 continue
要返回循环开头,并根据条件测试的结果决定是否继续执行循环,可使用continue 语句,它不像 break 语句那样不再执行余下的代码并退出整个循环。例如,来看一个从 1 数到 10,只打印其中奇数的循环:
current_number = 0
while current_number < 10:current_number += 1if current_number % 2 == 0:continueprint(current_number)'''
结果:
1
3
5
7
9
'''
三、使用 while 循环处理列表和字典
通过将 while 循环与列表和字典结合起来使用,可收集、存储并组织大量的输入,供以后查看和使用。
1. 在列表之间移动元素
# 首先,创建一个待验证用户列表
# 和一个用于存储已验证用户的空列表
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
# 验证每个用户,直到没有未验证用户为止
# 将每个经过验证的用户都移到已验证用户列表中
while unconfirmed_users:current_user = unconfirmed_users.pop()print(f"Verifying user: {current_user}")confirmed_users.append(current_user)
# 显示所有的已验证用户
print("\nThe following users are confirmed:")
for confirmed_user in confirmed_users:print(confirmed_user.title())'''
结果:
Verifying user: candace
Verifying user: brian
Verifying user: aliceThe following users are confirmed:
Candace
Brian
Alice'''
2. 删除为特定值的所有列表元素
pets = ['dog', 'cat', 'goldfish', 'cat', 'rabbit']
print(pets)
while 'cat' in pets:pets.remove('cat')
print(pets)'''
结果:
['dog', 'cat', 'goldfish', 'cat', 'rabbit']
['dog', 'goldfish', 'rabbit']'''
3. 使用用户输入填充字典
可以使用 while 循环提示用户输入任意多的信息
responses = {}
# 设置一个标准,指出调查是否继续
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? [Y/N]")if repeat == 'no':polling_active = False
print("\n--- Poll Results ---")
for name, responses in responses.items():print(f"{name}: {responses}")'''
结果:
What is your name? zhnagsan
Which mountain would you like to climb someday?taishan
Would you like to let another person respond? [Y/N]YWhat is your name? lisi
Which mountain would you like to climb someday?yueshan
Would you like to let another person respond? [Y/N]NWhat is your name? wangwu
Which mountain would you like to climb someday?qianlishan
Would you like to let another person respond? [Y/N]no--- Poll Results ---
zhnagsan: taishan
lisi: yueshan
wangwu: qianlishan
'''