计算机编程中,会经常涉及输入输出(IO,输入/输出)。提供IO功能的设备就是输入输出设备,比如,键盘,鼠标就是典型的输入设备,显示器就是典型的输出设备。程序在运行过程中,数据存储在内存中,但有时候它需要用户通过输入设备把数据(比如,密码)传递给程序;也有时候,程序需要把运行的结果数据输出给用户,这可能是打印到显示器,也可能是写到磁盘文件中。

python标准输入输出sys python的标准输入输出_数据

编程时,关于IO有两个基本概念:标准输入(STDIN)和标准输出(STDOUT)标准输入和输出都是对于命令行编程(非图形化界面)的,简单来说,标准输入就是在命令行通过敲打键盘输入,标准输出就是打印到显示器。

的Python语言提供了方便的输入(输入())和输出(印刷())函数。

输入函数input()

?程序在运行过程中,如何接收用户的键盘输入呢那就是通过输入()函数,我们先来看一个例子:

In [6]: a = input('请输入你的年龄:')

请输入你的年龄:18

In [7]: print(type(a))

这个例子中,请输入你的年龄:就是让用户输入前给的提示,input()函数返回接收到的键盘输入,并且是一个字符串,这一点非常重要,虽然我们知道,年龄应该是一个数字,但是输入返回的是字符串,你要根据需要转变为整数:a = int(a)。

关于input()函数,我们可以详细了解它的说明:

In [5]: input?
Signature: input(prompt=None, /)
Docstring:
Read a string from standard input. The trailing newline is stripped.
The prompt string, if given, is printed to standard output without a
trailing newline before reading input.
If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
On *nix systems, readline is used if available.
Type: builtin_function_or_method

输出函数print()

这个打印函数,我们已经接触过很多了,在程序运行过程中,使用我们print把必要的数据打印到显示器(标准输出),以便我们查看程序状态,数据结果等等,这在Python的程序的调试过程中很有用。

我们先类看看打印函数的说明:

In [8]: print?
Docstring:
print(value, ..., sep=' ', end=' ', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
Type: builtin_function_or_method
打印函数是一个可变参数函数,也就是说,它可以打印若干个变量,比如print(1), print(1, 2, 3)它的定义有四个默认参数:
sep=' '?表示被打印的若干个变量之间用空格隔开;
end=' '?表示打印完毕会自动多打印一个换行符;
file=sys.stdout?表示默认输出到标注输出设备(显示器),利用该参数我们也可以打印到文件中;
flush=False?默认不强制刷新到输出设备。
我们下面看看print()函数的使用例子:
In [23]: print(1, 2, 3)
1 2 3
In [24]: print(1, 2, 3, sep=';')
1;2;3
In [25]: print(1, 2, 3, sep=';', end='|')
看看再如何把信息print到文件中:
In [30]: f = open('z.log', 'w')
In [31]: print('认真学Python', file=f)
In [32]: f.close()
In [33]: cat z.log


总结

(1)标注输入函数input()让我们的程序从键盘获得输入数据;

(2)标注输出函数print()让我们的程序把数据打印到显示器;