Python基础:input()获取用户输入与类型转换

一、开篇:程序与用户交互的第一道门
一个程序如果不接受任何输入,那它每次运行的结果都是一样的——就像一个永远只说同一句话的机器人。input()函数是Python程序与用户交互的最基本方式,它让程序能够"倾听"用户的输入并做出不同的响应。
⌨️ 看起来简单的input(),其实有很多细节值得注意:
# 最基本的用法
name = input("请输入你的名字: ")
print(f"你好,{name}!")
# 但是…
age = input("请输入你的年龄: ")
# print(f"明年你就{age + 1}岁了") # TypeError!age是字符串,不是数字!
💡 Python的input()总是返回字符串,理解这一点是避免绝大多数输入相关bug的关键。今天我们就来全面掌握input()的用法、类型转换技巧、输入验证和异常处理。
二、input()的基本用法
2.1 语法与返回值
# input() 的基本语法
# input(prompt) → str
# prompt: 可选的提示字符串(显示给用户看)
# 返回值: 用户输入的字符串(不包括末尾的换行符)
# 基本使用
name = input("请输入姓名: ")
print(f"你好,{name}")
print(f"输入的类型: {type(name)}") # <class 'str'>
# 不提供提示信息
print("请输入一些内容: ", end='')
content = input()
print(f"你输入了: {content}")
# ⚠️ input()总是返回字符串,即使是数字!
number = input("请输入一个数字: ")
print(f"类型: {type(number)}, 值: {number!r}")
# 输入: 42
# 类型: <class 'str'>, 值: '42' ← 注意是字符串!
2.2 input()的执行过程
# input() 的执行流程:
# 1. 将prompt输出到标准输出(不换行)
# 2. 等待用户输入
# 3. 用户按下Enter键
# 4. 读取用户输入的内容(去掉末尾的\\n)
# 5. 返回字符串
# 用代码演示
def simulate_input():
print("模拟 input() 的行为:")
import sys
# 1. 输出提示
sys.stdout.write("请输入: ")
sys.stdout.flush()
# 2-4. 读取一行
user_input = sys.stdin.readline()
# 5. 去掉末尾换行符
result = user_input.rstrip('\\n')
print(f"返回: {result!r}")
return result
# 注意:input()在读取EOF时抛出EOFError
# 在读取时被Ctrl+C中断抛出KeyboardInterrupt
2.3 处理多行输入
# input()一次只能读取一行
# 读取多行需要使用循环
print("请输入多行文本(空行结束):")
lines = []
while True:
line = input()
if line == "": # 空行 = 结束
break
lines.append(line)
print(f"\\n共输入 {len(lines)} 行:")
for i, line in enumerate(lines, 1):
print(f" {i}: {line}")
# 按特定标记结束
print("\\n请输入文本(输入 END 结束):")
lines = []
while True:
line = input()
if line.strip().upper() == "END":
break
lines.append(line)
print(f"\\n共输入 {len(lines)} 行(不包括END)")
三、类型转换:从字符串到你需要的数据类型
3.1 转换为整数
# int() 将字符串转换为整数
# 基本转换
age_str = input("请输入年龄: ")
try:
age = int(age_str)
print(f"年龄: {age}, 明年: {age + 1}")
except ValueError:
print("请输入有效的整数!")
# int() 支持的格式
print(int("42")) # 42 —— 十进制
print(int("-10")) # -10 —— 负数
print(int("+5")) # 5 —— 带正号
print(int("0b1010", 2)) # 10 —— 二进制
print(int("0o12", 8)) # 10 —— 八进制
print(int("0xa", 16)) # 10 —— 十六进制
# int() 不支持的格式
# int("3.14") # ValueError —— 不能直接转浮点格式
# int("1,000") # ValueError —— 不能有千位分隔符
# int(" 42 ") # ✅ 可以!会自动strip空格
3.2 转换为浮点数
# float() 将字符串转换为浮点数
price_str = input("请输入价格: ")
try:
price = float(price_str)
print(f"价格: ¥{price:.2f}")
except ValueError:
print("请输入有效的数字!")
# float() 支持的格式
print(float("3.14")) # 3.14 —— 标准浮点
print(float("10")) # 10.0 —— 整数
print(float("-2.5")) # -2.5 —— 负数
print(float("1e-3")) # 0.001 —— 科学计数法
print(float("inf")) # inf —— 无穷大
print(float("-inf")) # -inf —— 负无穷
print(float("nan")) # nan —— 非数字
3.3 转换为布尔值
# bool() 的转换规则:
# 空字符串 → False
# 非空字符串 → True
# 注意:字符串 "False" 也是 True!
print(bool("")) # False
print(bool("False")) # True!—— 非空字符串
print(bool("0")) # True!—— 非空字符串
print(bool("True")) # True
# ✅ 正确的布尔转换方式
def str_to_bool(s):
"""将字符串转换为布尔值"""
s = s.strip().lower()
if s in ('true', 'yes', 'y', '1', 'on'):
return True
elif s in ('false', 'no', 'n', '0', 'off'):
return False
else:
raise ValueError(f"无法转换为布尔值: {s}")
# 使用
while True:
answer = input("是否继续?(yes/no): ").strip().lower()
if answer in ('yes', 'no'):
break
print("请输入 yes 或 no")
should_continue = answer == 'yes'
print(f"继续: {should_continue}")
3.4 转换为列表等其他类型
# 将逗号分隔的字符串转换为列表
items_str = input("请输入多个值(用逗号分隔): ")
items = [item.strip() for item in items_str.split(',')]
print(f"列表: {items}")
# 转换为集合(去重)
unique_items = set(item.strip() for item in items_str.split(','))
print(f"集合(去重): {unique_items}")
# 将JSON字符串转换为Python对象
import json
json_str = input("请输入JSON数据: ")
try:
data = json.loads(json_str)
print(f"解析结果: {data}")
print(f"类型: {type(data).__name__}")
except json.JSONDecodeError as e:
print(f"JSON解析错误: {e}")
# 将input解析为多个值
def input_multi(prompt="", separator=" "):
"""一次输入多个值"""
raw = input(prompt)
return raw.split(separator)
# 使用
# x, y, z = input_multi("请输入三个坐标(空格分隔): ")
# print(f"坐标: ({x}, {y}, {z})")
四、输入验证的最佳实践
4.1 验证数字输入
def get_int(prompt, min_val=None, max_val=None):
"""获取一个整数输入,带范围验证"""
while True:
try:
value = int(input(prompt))
if min_val is not None and value < min_val:
print(f"❌ 值不能小于 {min_val},请重新输入")
continue
if max_val is not None and value > max_val:
print(f"❌ 值不能大于 {max_val},请重新输入")
continue
return value
except ValueError:
print("❌ 请输入一个有效的整数")
def get_float(prompt, min_val=None, max_val=None):
"""获取一个浮点数输入,带范围验证"""
while True:
try:
value = float(input(prompt))
if min_val is not None and value < min_val:
print(f"❌ 值不能小于 {min_val},请重新输入")
continue
if max_val is not None and value > max_val:
print(f"❌ 值不能大于 {max_val},请重新输入")
continue
return value
except ValueError:
print("❌ 请输入一个有效的数字")
# 使用
# age = get_int("请输入年龄(0-150): ", 0, 150)
# score = get_float("请输入分数(0-100): ", 0, 100)
4.2 验证选择输入
def get_choice(prompt, choices, case_sensitive=False):
"""获取用户选择,必须从给定选项中选择"""
if not case_sensitive:
choices_lower = [c.lower() for c in choices]
while True:
choice = input(prompt).strip()
if not case_sensitive:
if choice.lower() in choices_lower:
# 返回原始大小写的选项
idx = choices_lower.index(choice.lower())
return choices[idx]
else:
if choice in choices:
return choice
print(f"❌ 无效选择,请从 {choices} 中选择")
# 使用
# color = get_choice("请选择颜色 (red/green/blue): ", ["red", "green", "blue"])
# print(f"你选择了: {color}")
4.3 通用输入框架
class InputValidator:
"""通用输入验证框架"""
@staticmethod
def get(prompt, converter=str, validator=None, error_msg="输入无效"):
"""获取并验证用户输入"""
while True:
raw = input(prompt).strip()
# 转换
try:
value = converter(raw)
except (ValueError, TypeError) as e:
print(f"❌ 转换错误: {e}")
continue
# 验证
if validator is not None:
try:
is_valid = validator(value)
if is_valid is False:
print(f"❌ {error_msg}")
continue
if isinstance(is_valid, str):
print(f"❌ {is_valid}")
continue
except Exception as e:
print(f"❌ 验证错误: {e}")
continue
return value
# 使用示例
def validate_email(email):
if "@" not in email:
return "邮箱必须包含@符号"
if "." not in email.split("@")[–1]:
return "邮箱域名不完整"
return True
def validate_age(age):
if age < 0 or age > 150:
return f"年龄 {age} 不在有效范围(0-150)"
return True
# email = InputValidator.get(
# "请输入邮箱: ",
# converter=str,
# validator=validate_email,
# )
# age = InputValidator.get(
# "请输入年龄: ",
# converter=int,
# validator=validate_age,
# error_msg="年龄无效"
# )
五、实战案例
5.1 简易问卷调查
class Survey:
"""简易问卷调查 —— input()的综合应用"""
def __init__(self, title):
self.title = title
self.questions = []
self.responses = []
def add_question(self, q_type, prompt, **kwargs):
"""添加问题
q_type: 'text', 'number', 'choice', 'rating'
"""
self.questions.append({
"type": q_type,
"prompt": prompt,
**kwargs,
})
def run(self):
"""运行调查"""
print("=" * 50)
print(f"📋 {self.title}")
print("=" * 50)
participant = input("请输入你的名字: ").strip()
response = {"name": participant}
for i, q in enumerate(self.questions, 1):
print(f"\\n问题 {i}/{len(self.questions)}")
response[f"q{i}"] = self._ask_question(q)
self.responses.append(response)
print(f"\\n✅ 感谢参与,{participant}!")
return response
def _ask_question(self, q):
"""根据问题类型获取答案"""
q_type = q["type"]
prompt = q["prompt"]
if q_type == "text":
return input(prompt + " ").strip()
elif q_type == "number":
while True:
try:
return float(input(prompt + " "))
except ValueError:
print(" 请输入有效数字")
elif q_type == "choice":
choices = q.get("choices", [])
print(prompt)
for j, c in enumerate(choices, 1):
print(f" {j}. {c}")
while True:
try:
choice = int(input("请选择(输入编号): "))
if 1 <= choice <= len(choices):
return choices[choice – 1]
print(f" 请输入1-{len(choices)}之间的数字")
except ValueError:
print(" 请输入数字")
elif q_type == "rating":
min_r, max_r = q.get("min", 1), q.get("max", 5)
while True:
try:
rating = int(input(f"{prompt} ({min_r}–{max_r}分): "))
if min_r <= rating <= max_r:
return rating
print(f" 请输入{min_r}–{max_r}之间的整数")
except ValueError:
print(" 请输入有效整数")
def show_summary(self):
"""显示调查结果摘要"""
if not self.responses:
print("暂无数据")
return
print(f"\\n📊 调查结果 (共{len(self.responses)}份)")
print("=" * 50)
for i, r in enumerate(self.responses, 1):
print(f"\\n参与人{i}: {r['name']}")
for j, q in enumerate(self.questions, 1):
print(f" Q{j}: {q['prompt'][:30]}… → {r[f'q{j}']}")
# 使用
survey = Survey("用户满意度调查")
survey.add_question("text", "你的名字是?")
survey.add_question("number", "你使用本产品多久了?(月)")
survey.add_question("choice", "你最喜欢的功能是?",
choices=["功能A", "功能B", "功能C"])
survey.add_question("rating", "总体满意度", min=1, max=5)
# survey.run()
5.2 命令行待办事项
class TodoApp:
"""命令行待办事项 —— input()驱动交互"""
def __init__(self):
self.tasks = []
self.next_id = 1
def run(self):
while True:
self._show_menu()
choice = input("\\n请选择操作: ").strip()
if choice == "1":
self._add_task()
elif choice == "2":
self._list_tasks()
elif choice == "3":
self._complete_task()
elif choice == "4":
self._delete_task()
elif choice == "5":
print("👋 再见!")
break
else:
print("无效选择,请重新输入")
def _show_menu(self):
print(f"\\n{'='*40}")
print(f"📝 待办事项 ({len([t for t in self.tasks if not t['done']])}个未完成)")
print(f"{'='*40}")
print("1. 添加任务")
print("2. 查看任务")
print("3. 完成任务")
print("4. 删除任务")
print("5. 退出")
def _add_task(self):
title = input("任务内容: ").strip()
if not title:
print("任务内容不能为空")
return
self.tasks.append({
"id": self.next_id,
"title": title,
"done": False,
})
self.next_id += 1
print(f"✅ 任务已添加")
def _list_tasks(self):
if not self.tasks:
print("暂无任务")
return
for task in self.tasks:
status = "✅" if task["done"] else "⬜"
print(f" [{task['id']}] {status} {task['title']}")
def _complete_task(self):
task_id = input("输入要完成的任务ID: ").strip()
try:
task_id = int(task_id)
for task in self.tasks:
if task["id"] == task_id:
task["done"] = True
print(f"✅ '{task['title']}' 已完成")
return
print("未找到该任务")
except ValueError:
print("请输入有效的任务ID")
def _delete_task(self):
task_id = input("输入要删除的任务ID: ").strip()
try:
task_id = int(task_id)
for i, task in enumerate(self.tasks):
if task["id"] == task_id:
removed = self.tasks.pop(i)
print(f"🗑️ '{removed['title']}' 已删除")
return
print("未找到该任务")
except ValueError:
print("请输入有效的任务ID")
# 运行
# app = TodoApp()
# app.run()
六、本章小结
✅ 本文我们全面掌握了input()函数:
基本特性:input(prompt)总是返回字符串,读取用户输入直到Enter,自动去掉末尾换行符。
类型转换:int()、float()、bool()等将字符串转换为需要的数据类型。关键:input返回的是字符串,必须显式转换。
输入验证:永远不要信任用户输入!使用try-except捕获ValueError,在循环中反复询问直到得到合法输入。
设计模式:验证循环(while True + try-except)、选择验证(检查是否在允许集合中)、通用输入框架。
实战案例:问卷调查系统、命令行待办事项管理——input()在这些场景中作为用户与程序的交互桥梁。
input()虽然简单,但它是构建交互式Python程序的基础。掌握好输入验证和类型转换,你就能写出健壮的、对用户友好的命令行程序。⌨️ 下一篇文章,我们将深入学习类型转换int、float、str互转的所有细节。





