Python · 3 分钟阅读
`input()` 函数
目录
- 1. 语法
- 2. 基础示例
- 3. 类型转换
- 4. 一行多个值
- 5. 输入校验(重试到对为止)
- 6. 提前结束输入
- 7. 与
print的搭配技巧 - 8. 不只是终端:
input()也被其它流替换 - 9. 常见问题
- 10. 小结
input() 是 Python 内置的 阻塞式 命令行输入:暂停程序,等待用户在
终端输入一行,按下回车后把这一行 作为字符串 返回。
1. 语法
input(prompt=None) # prompt 可选,提示语会原样打印
- 始终返回
str——要其它类型必须手动int()/float()。 - 用户在终端按
Ctrl-D(Unix)/Ctrl-Z(Windows)结束输入时抛EOFError。 - 按
Ctrl-C抛KeyboardInterrupt。
2. 基础示例
name = input("请输入您的姓名: ")
print(f"您好, {name}!")
提示语末尾要不要换行?
input会自己加一个换行,不必再写"\n"。
3. 类型转换
age = input("请输入您的年龄: ")
age = int(age)
print(f"您明年将会是 {age + 1} 岁。")
更现代的写法:
age = int(input("请输入您的年龄: ")) # 一行搞定
⚠️ 输入非数字会抛
ValueError,生产代码务必捕获。
4. 一行多个值
# 一次读 a b 两个整数,用空格分隔
a, b = map(int, input("输入 a b: ").split())
print(a + b)
split()默认按任意空白切分;指定分隔符用split(",")/split(";")等。
5. 输入校验(重试到对为止)
def ask_int(prompt: str, lo: int, hi: int) -> int:
while True:
try:
n = int(input(prompt))
except ValueError:
print("请输入整数。")
continue
if not (lo <= n <= hi):
print(f"范围 {lo} ~ {hi}。")
continue
return n
age = ask_int("请输入您的年龄(0-150): ", 0, 150)
更优雅的写法可以用 prompt_toolkit / click / typer,它们带自动提示、
校验、历史记录、Vim 模式等高级功能。
6. 提前结束输入
try:
while True:
line = input("> ")
print("got:", line)
except EOFError:
print("输入结束。")
echo "hello" | python script.py之类的管道场景特别常见——input()会
一行行读直到收到EOF。
7. 与 print 的搭配技巧
| 写法 | 效果 |
|---|---|
print("a", "b", sep="-") |
输出 a-b |
print("hi", end="") |
不换行 |
print(f"x = {x:>5}") |
右对齐 5 字符 |
input("> ") |
输出 > 然后等用户输入 |
8. 不只是终端:input() 也被其它流替换
input(prompt) 默认从 sys.stdin 读。sys.stdin 本身是个文件对象,
因此可以替换成任何可读对象(很少用到,但能做单元测试):
import sys, io
sys.stdin = io.StringIO("alice\n30\n")
name = input() # 'alice'
age = int(input()) # 30
sys.stdin = sys.__stdin__ # 恢复
9. 常见问题
- 中文输入乱码? 终端
LANG=zh_CN.UTF-8;多数情况 Python 3 默认 utf-8
没问题。 - 脚本需要密码怎么办? 用
getpass.getpass("password: "),输入不回显。 - 想读一整段(多行)? 多次
input(),或用sys.stdin.read()。 - CLI 工具想做得专业? 用
argparse/click/typer而不是input。
10. 小结
input(prompt)始终返回字符串,按需int/float。- 用
try / except ValueError配合while True做重试。 Ctrl-D→EOFError,Ctrl-C→KeyboardInterrupt,按需捕获。- 写正式 CLI 时考虑
argparse/click/typer/prompt_toolkit。