Python Input & Output

Input

reads one line from stdin and returns a str

Get an integer : s=int(input())

The usage of Prompt:

image-20261008154706900

EOF

EOF = End of File

当读到EOF,input()会报出 EOFError,比如:

1
2
3
4
5
6
# 假设这段代码在等待输入
try:
s = input("请输入内容: ")
print("你输入了:", s)
except EOFError:
print("检测到输入结束(EOF),没有内容可读了。")

Auditing Event

Raises an auditing event builtins.input with argument prompt before reading input

Raises an auditing event builtins.input/result with the result after successfully reading input.

本质:触发了input事件或者用户输入完input事件时向系统监视提出报告

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import sys

# 定义一个“监控摄像头”(审计钩子函数)
def my_audit_hook(event, args):
# 如果发现有输入事件发生
if event == "builtins.input":
# (补充)这里也不一定是print,是可以任意事件。主要在触发输入的操作就可以去做。
print(f"\n[监控系统] 警告:程序准备要求输入了!提示语是:'{args[0]}'")
elif event == "builtins.input/result":
print(f"[监控系统] 记录:用户实际输入的内容是:'{args[0]}'")

# 开启监控摄像头
sys.addaudithook(my_audit_hook)

# 运行正常的 input
name = input("请输入你的名字: ")
print(f"你好, {name}!")

运行结果是:

1
2
3
4
[监控系统] 警告:程序准备要求输入了!提示语是:'请输入你的名字: '
请输入你的名字: 张三
[监控系统] 记录:用户实际输入的内容是:'张三'
你好, 张三!

Print

1
print(*objects, sep=' ', end='\n', file=None, flush=False)
  • object:可以多个, print("a", "b", 123) 这些都是object

  • sep:sep='-' 中间的间隔

  • end:结尾是什么

  • file:默认sys.stdout,但可以这样:

    1
    2
    f = open("test.txt", "w")
    print("Hello", file=f)
  • flush:是否启用缓冲流,可以用 flush=True 来取消

Sys

Basic Usage

  • sys.stdin.readline() reads one line from stdin

  • s.strip() : Remove a new line and extra space

  • sys.stdout.write(text) writes text without adding a newline

  • sys.stdin.readlines() reads all remaining lines from standard input

    Returns a list of strings

    Use .strip() for each line, then output what you need


Example:

一行读入多个整数

1
2
3
4
5
import sys

line = sys.stdin.readline().split()

for num in line:

读入多行,每行多个整数:

1
2
3
4
5
6
7
8
9
10
import sys

while True:
# Read a line.
line = sys.stdin.readline()
# When readline returns an empty string, the file is fully read.
if line == "":
break
for number in line.split():
# process the data

Buffering 缓冲机制

image-20261008160920885

取消缓冲:

1
python -u script.py

读入整数

提前知道有多少个整数的方法:

1
a, b, c = map(int, input().spilt())

如果更多,可以使用迭代器:

1
2
3
4
5
data = list(map(int, input().split()))
it = iter(data)
a = next(it)
b = next(it)
c = next(it)

如果读完了还在访问,会抛出 StopIteration 的异常。

如果读入顺序不重要,可以这样:

1
2
3
nums = list(map(int, input().split()))
for num in nums:
print(num)

这种做法只适用于读入的是int,如果读入的是很多东西,还是回到使用:

1
2
line = sys.stdin.readline().split()
for num in line:

f-string

对于输出的时候,不需要用恶心的+连接了,可以这样:

1
print(f"我叫{name},今年{age}岁")

而且有更高级的操作,比如运算:

1
print(f"a + b = {a + b}")  # 输出: a + b = 30

调用函数,比如大写:

1
2
name = "python"
print(f"大写: {name.upper()}") # 输出: 大写: PYTHON

定义格式,比如保留2位小数:

1
2
price = 3.14159
print(f"价格: {price:.2f}") # 输出: 价格: 3.14

甚至可以在里面写条件表达式:

1
2
score = 85
print(f"结果: {'及格' if score >= 60 else '不及格'}") # 输出: 结果: 及格