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
'''
相关推荐
理想三旬几秒前
网络爬虫(上)
python
zzywxc78714 分钟前
大模型落地实践指南:从技术路径到企业级解决方案
java·人工智能·python·microsoft·golang·prompt
小小测试开发1 小时前
给贾维斯加“手势控制”:从原理到落地,打造多模态交互的本地智能助
人工智能·python·交互
Python×CATIA工业智造1 小时前
Python数据汇总与统计完全指南:从基础到高阶实战
python·pycharm
MoRanzhi12034 小时前
2. Pandas 核心数据结构:Series 与 DataFrame
大数据·数据结构·人工智能·python·数据挖掘·数据分析·pandas
小钱c75 小时前
Python利用ffmpeg实现rtmp视频拉流和推流
python·ffmpeg·音视频
合作小小程序员小小店6 小时前
桌面预测类开发,桌面%性别,姓名预测%系统开发,基于python,scikit-learn机器学习算法(sklearn)实现,分类算法,CSV无数据库
python·算法·机器学习·scikit-learn·sklearn
Q26433650236 小时前
【有源码】基于Hadoop+Spark的豆瓣电影数据分析与可视化系统-基于大数据的电影评分趋势分析与可视化系统
大数据·hadoop·python·数据分析·spark·毕业设计·课程设计
天特肿瘤电场研究所7 小时前
靠谱的肿瘤电场疗法公司
人工智能·python
闲人编程7 小时前
2025年,如何选择Python Web框架:Django, Flask还是FastAPI?
前端·后端·python·django·flask·fastapi·web