python 的输入与输出
一、python 输入
1.1 使用内建函数 input()
>>> input()
"hello world"
'hello world'
>>>
----这里输入字符串需要带 引号,输入数字则不用
>>> input()
1
1
>>>
----错误例子,会报错
>>> input()
hello world
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
input()
File "<string>", line 1
hello world
^
SyntaxError: unexpected EOF while parsing
>>>
----在 input() 时,可以提示
一下,需要输入什么,例:
>>> input("input string:")
input string:"hello world"
'hello world'
>>>
1.2 使用内建函数 raw_input()
>>> raw_input("input string: ")
input string: hello world
'hello world'
----raw_input() 会把所有 的输入当作字符串,故不用引号
>>> raw_input()
1
'1'
>>>
二、python 输出
print 打印,在python中,它打印在 命令行、控制台。它操作的对象是一个 字符串
这里举了几个例来说明
1. print 后面跟字符串需要加引号,可以看一下有引号和没有引号的区别
>>> print "string"
string
# 错误的使用,没有用引号
>>> print string
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
print string
NameError: name 'string' is not defined
>>> print 1
1
>>> print 3.13
3.13
>>> print 1+1
2
>>> print "1+1"
1+1
>>> print 2 > 5
False
>>>
2. 在python 命令行(python shell)中,print 可以省略
>>> "string"
'string'
>>> 1
1
>>> 3.13
3.13
>>> 1+1
2
>>> "1+1"
'1+1'
>>> 2 > 5
False
>>>
3. 格式化输出<这里不作详解,字符串章节再细说>()
>>> string = "hello world"
>>> print "%s" % string
hello world
# 这里 hello world 会占15个字符,不足会左边补空格
>>> print "%15s" % string
hello world
>>>