python基础:用户输入和 while 循环

一、input() 函数的工作原理

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

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 会将用户输入解读为字符串。

python 复制代码
>>> age = input('How old are you?')                                                                                     How old are you?21                                                                                                      
>>> age                                                                                                                 
'21'

当试图将该输入用于数值比较时,Python 会报错,因为它无法将字符串和整数进行比较

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() 将输入的字符串转换为数值,确保能够成功地执行比较操作:

python 复制代码
>>> age = int(age)                                                                                                      
>>> age >= 18                                                                                                           
True

2. 求模运算符

求模运算符(%)是个很有用的工具,它将两个数相除并返回余数:

python 复制代码
>>> 4 % 3
1
>>> 5 % 3
2

二、while 循环简介

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

1. 使用 while 循环

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

python 复制代码
current_number = 1
while current_number <= 5:
    print(current_number)
    current_number += 1

'''
结果:
1
2
3
4
5
'''

2. 让用户选择何时退出

我们在其中定义了一个退出值,只要用户输入的不是这个值,程序就将一直运行:

python 复制代码
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
w

Tell me something, and I will repeat it back to you:
Enter 'q' to end the program.r
r

Tell me something, and I will repeat it back to you:
Enter 'q' to end the program.q
q

'''

3. 使用标志

在要求满足很多条件才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量称为标志(flag),充当程序的交通信号灯。可以让程序在标志为 True 时继续运行,并在任何事件导致标志的值为False 时让程序停止运行。这样,在 while 语句中就只需检查一个条件:标志的当前值是否为 True。

python 复制代码
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 = False
    else:
        print(message)

'''
结果:
Tell me something, and I will repeat it back to you:
Enter 'q' to end the program.1
1

Tell me something, and I will repeat it back to you:
Enter 'q' to end the program.2
2

Tell me something, and I will repeat it back to you:
Enter 'q' to end the program.q
'''

4. 使用 break 退出循环

如果不管条件测试的结果如何,想立即退出 while 循环,不再运行循环中余下的代码,可使用 break 语句。break 语句用于控制程序流程,可用来控制哪些代码行将执行、哪些代码行不执行,从而让程序按你的要求执行你要执行的代码。

python 复制代码
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':
        break
    else:
        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,只打印其中奇数的循环:

python 复制代码
current_number = 0
while current_number < 10:
    current_number += 1
    if current_number % 2 == 0:
        continue
    print(current_number)

'''
结果:
1
3
5
7
9
'''

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

通过将 while 循环与列表和字典结合起来使用,可收集、存储并组织大量的输入,供以后查看和使用。

1. 在列表之间移动元素

python 复制代码
# 首先,创建一个待验证用户列表
# 和一个用于存储已验证用户的空列表
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: alice

The following users are confirmed:
Candace
Brian
Alice

'''

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

python 复制代码
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 循环提示用户输入任意多的信息

python 复制代码
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]Y

What is your name? lisi
Which mountain would you like to climb someday?yueshan
Would you like to let another person respond? [Y/N]N

What 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
'''
相关推荐
天天进步201520 分钟前
Python游戏开发引擎设计与实现
开发语言·python·pygame
数据狐(DataFox)1 小时前
CTE公用表表达式的可读性与性能优化
经验分享·python·sql
蹦蹦跳跳真可爱5891 小时前
Python----MCP(MCP 简介、uv工具、创建MCP流程、MCP客户端接入Qwen、MCP客户端接入vLLM)
开发语言·人工智能·python·语言模型
No0d1es1 小时前
第13届蓝桥杯Python青少组中/高级组选拔赛(STEMA)2022年1月22日真题
python·青少年编程·蓝桥杯·选拔赛
MediaTea1 小时前
Python 库手册:getopt Unix 风格参数解析模块
服务器·开发语言·python·unix
王尼莫啊1 小时前
【立体标定】圆形标定板标定python实现
开发语言·python·opencv
cosX+sinY2 小时前
10 卷积神经网络
python·深度学习·cnn
非极限码农2 小时前
基于Deepseek的语言润色助手API实现与部署指南
python·微服务·自然语言处理
AndrewHZ3 小时前
【图像处理基石】如何对遥感图像进行实例分割?
图像处理·人工智能·python·大模型·实例分割·detectron2·遥感图像分割