Python 输入、输出和导入
Python 输入、输出和导入
本教程重点介绍两个内置函数 print() 和 input() 在 Python 中执行 I/O 任务。此外,您将学习导入模块并在程序中使用它们。
视频:Python 接受用户输入
Python 提供了许多内置函数,我们可以在 Python 提示符下随时使用。
input()
等一些函数 和 print()
分别广泛用于标准输入和输出操作。让我们先看看输出部分。
Python 输出使用 print() 函数
我们使用 print()
将数据输出到标准输出设备(屏幕)的功能。我们也可以将数据输出到文件中,不过这个会在后面讨论。
下面给出一个使用示例。
print('This sentence is output to the screen')
输出
This sentence is output to the screen
下面再举一个例子:
a = 5
print('The value of a is', a)
输出
The value of a is 5
在第二个 print()
语句,我们可以注意到在字符串和变量 a 的值之间添加了空格 .这是默认设置,但我们可以更改它。
print()
的实际语法 功能是:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
这里,objects
是要打印的值。
sep
值之间使用分隔符。它默认为空格字符。
打印完所有值后,end
被打印。它默认为一个新行。
file
是打印值的对象,其默认值为 sys.stdout
(屏幕)。这里有一个例子来说明这一点。
print(1, 2, 3, 4)
print(1, 2, 3, 4, sep='*')
print(1, 2, 3, 4, sep='#', end='&')
输出
1 2 3 4 1*2*3*4 1#2#3#4&
输出格式
有时我们想格式化我们的输出以使其看起来更有吸引力。这可以通过使用 str.format()
来完成 方法。该方法对任何字符串对象都是可见的。
>>> x = 5; y = 10
>>> print('The value of x is {} and y is {}'.format(x,y))
The value of x is 5 and y is 10
在这里,花括号 {}
用作占位符。我们可以使用数字(元组索引)来指定它们的打印顺序。
print('I love {0} and {1}'.format('bread','butter'))
print('I love {1} and {0}'.format('bread','butter'))
输出
I love bread and butter I love butter and bread
我们甚至可以使用关键字参数来格式化字符串。
>>> print('Hello {name}, {greeting}'.format(greeting = 'Goodmorning', name = 'John'))
Hello John, Goodmorning
我们还可以像旧的 sprintf()
那样格式化字符串 C 编程语言中使用的样式。我们使用 %
操作员来完成这项工作。
>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
The value of x is 12.35
>>> print('The value of x is %3.4f' %x)
The value of x is 12.3457
Python 输入
到目前为止,我们的程序是静态的。变量的值已定义或硬编码到源代码中。
为了提供灵活性,我们可能希望从用户那里获取输入。在 Python 中,我们有 input()
允许这样做的功能。 input()
的语法 是:
input([prompt])
其中 prompt
是我们希望在屏幕上显示的字符串。它是可选的。
>>> num = input('Enter a number: ')
Enter a number: 10
>>> num
'10'
在这里,我们可以看到输入的值 10
是字符串,不是数字。要将其转换为数字,我们可以使用 int()
或 float()
功能。
>>> int('10')
10
>>> float('10')
10.0
可以使用 eval()
执行相同的操作 功能。但是eval
更进一步。如果输入是字符串,它甚至可以计算表达式
>>> int('2+3')
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '2+3'
>>> eval('2+3')
5
Python 导入
当我们的程序变大时,最好把它分成不同的模块。
模块是包含 Python 定义和语句的文件。 Python 模块有一个文件名并以扩展名 .py
结尾 .
模块内的定义可以导入到另一个模块或 Python 中的交互式解释器。我们使用 import
关键字来做到这一点。
例如,我们可以导入 math
输入以下行:
import math
我们可以通过以下方式使用该模块:
import math
print(math.pi)
输出
3.141592653589793
现在math
里面的所有定义 模块在我们的范围内可用。我们也可以只导入一些特定的属性和函数,使用 from
关键词。例如:
>>> from math import pi
>>> pi
3.141592653589793
在导入模块时,Python 会查看 sys.path
中定义的几个地方 .它是一个目录位置列表。
>>> import sys
>>> sys.path
['',
'C:\\Python33\\Lib\\idlelib',
'C:\\Windows\\system32\\python33.zip',
'C:\\Python33\\DLLs',
'C:\\Python33\\lib',
'C:\\Python33',
'C:\\Python33\\lib\\site-packages']
我们还可以将自己的位置添加到此列表中。
Python