raw_input和input的区别

来源:互联网 发布:大月薰 知乎 编辑:程序博客网 时间:2024/05/29 07:26

raw_input和input的区别
分类:Python学习总结
这两个均是 python 的内置函数,通过读取控制台的输入与用户实现交互。但他们的功能不尽相同。下面对它们逐一介绍:
1、raw_input函数
语法:raw_input([prompt])
如果prompt不存在,也就是raw_input(),它会标准输出(没有后面的换行符)。然后这个函数从输入读取一行,把它转化为字符串(移除尾部的换行符),并输出它。在这里移除尾部的换行符,也就是说,你输入一行时,会回车换行,这个换行不会作为字符串中的字符输出。
如果prompt存在,prompt经常是字符串(用来提示输入),用法和prompt不存在一样。
当读取到文件的结束符时会抛出异常。
总的来说,raw_input将所有输入作为字符串看待,不管用户输入什么类型的都会转变成字符串。

x=raw_input() # prompt不存在
abc
x
‘abc’

y=raw_input(“please input:”)
please input:abc
y
‘abc’

z=raw_input(“please input:”)
please input:34
z
‘34’

m=raw_input(“please input:”)
please input:[2,3,1,4]
m
‘[2,3,1,4]’

n=raw_input(“please input:”)
please input:3+2
n
‘3+2’

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2、input函数

语法:input([prompt])
等价于:eval(raw_input(prompt))
我们知道eval函数是将字符串str当成有效Python表达式来求值,并返回计算结果。
input函数期望用户输入的是一个有效的表达式,也就是说,如果要输入字符串就必须要用引号括起来,否则它会引发一个 SyntaxError。它会根据输入内容的形式确定返回的形式。

x=input()
“abc”
x
‘abc’

y=input(“please input:”)
please input:abc

Traceback (most recent call last):
File “

0 0