python入门系列8―——I/O

来源:互联网 发布:网络爸爸手机版下载 编辑:程序博客网 时间:2024/06/08 07:15

欢迎前往我的个人博客


io就是输入输出

输出我们已经使用了,就是print

print “hello python”

通过键盘输入有2个函数:

1.input

2.raw_input

我们来看下它们之前的区别:

str = input("请输入")print "hello",str
str = raw_input("请输入")print "hello",str
尝试输入一个字符串或者数字,你会发现都没问题。

如果输入:https://www.baidu.com/

input就会报错,提示:

请输入https://www.baidu.com/Traceback (most recent call last):  File "D:\Python27\Mytest\test.py", line 1, in <module>    str = input("请输入")  File "<string>", line 1    https://www.baidu.com/         ^SyntaxError: invalid syntax
所以input必须输入合法的表达式才可以。通常情况下使用raw_input最好。

不过也有特例就是,如果你希望的是输出表达式的结果,而不是表达式的字符串,则需要用input:

输入:[x for x in range(1,5)]

input结果:

>>> 请输入[x for x in range(1,5)]hello [1, 2, 3, 4]
raw_input结果:

>>> 请输入[x for x in range(1,5)]hello [x for x in range(1,5)]