当前位置: 首页 > news >正文

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

一、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
'''

http://www.lryc.cn/news/605064.html

相关文章:

  • 【机器学习】pycharm使用SSH SFTP 远程连接 ubuntu服务器 进行开发+调试+数据训练
  • IBus vs. Fcitx5:一场 Linux 输入法框架的正面交锋
  • 在 Kubernetes 上部署 Label Studio
  • Apache Kafka核心组件详解
  • 当人生低谷无人帮助时,如何独自奏响人生乐章
  • 借助 Wisdom SSH AI 助手构建 Linux 容器化开发流水线
  • 虚实共生的智能革命:元宇宙、物联网与 AI 融合生态全景图谱
  • Vue 3 入门教程 2- Vue 组件基础与模板语法
  • 推客系统开发全流程解析:从概念到落地的完整指南
  • 论文Review LSLAM BALM | 经典激光SLAM方案!港大MARS出品!RAL2021 | 激光BA优化
  • RocketMQ 核心特性解析及与 Kafka区别
  • Spring AI 海运管理应用第2部分
  • Centos 7.9安装部署cobbler-自动化部署服务器完整教程
  • 数据结构第3问:什么是线性表?
  • 从0开始学linux韦东山教程Linux驱动入门实验班(7)
  • 不止 “听懂”,更能 “感知”!移远通信全新AI 音频模组 重新定义智能家居“听觉”逻辑
  • 【Datawhale AI夏令营】科大讯飞AI大赛(大模型技术)/夏令营:让AI理解列车排期表(Task3)
  • 如何将DICOM文件制作成在线云胶片
  • 一句话指令实现“2D转3D”、“图片提取线稿”
  • Kong API Gateway深度解析:插件系统与微服务架构的技术基石
  • Python爬虫05_Requests肯德基餐厅位置爬取
  • 企业微信API接口发消息实战:从0到1的技术突破之旅
  • 新注册企业信息查询“数据大集网”:驱动企业增长的源头活水
  • 笔试——Day23
  • C++ 项目 QML QtQuick.Controls“ is not installed
  • 【C语言】深度剖析指针(二):指针与数组,字符,函数的深度关联
  • 基于 Amazon Bedrock 与 Anthropic Claude 3 智能文档处理方案:从扫描件提取到数据入库全流程实践
  • C++入门基础 1
  • 【MySQL 数据库】MySQL索引特性(二)页目录(B和B+树)(非)聚簇索引 索引操作
  • 293F细胞是什么?