您的位置:首页 > 编程语言 > Python开发

Python 读取键盘输入 :raw_input()和input() 函数 读取交互输入

2015-11-20 20:44 1176 查看
函数:raw_input()和input()

注意:在python3.x中,已经删除raw_input(),取而代之的是input(),当然这仅仅是重命名,用法还是一样。因此在这里介绍的是python2.x中的raw_input()和input(),在python3.x中只要按raw_input()的使用方式就行

1:作用:读取控制台的输入与用户实现交互

2:语法

raw_input([prompt])

input([prompt])

3:参数

prompt:如果存在此参数,则会直接输出到屏幕上,不会再往下另起一行

4:两者关系:

input()本质上是使用raw_input()来实现的,即调用完raw_input()之后再调用eval()函数,调用如下:

def input(prompt):

return (eval(raw_input(prompt)))

5:两者相同点:

都能接受字符串、数字以及表达式作为输入。

6:两者差别:

6.1、当输入为字符串时:

raw_input(): 读取控制台的输入,同时返回字符串类型

input(): 读取控制台的输入,但输入时必须使用引号括起来,否则会报错

6.2、当输入为纯数字时:

raw_input(): 读取控制台的输入,同时返回字符串类型,当作字符串处理

input(): 读取控制台的输入,返回输入的数值类型(int, float)

6.3、当输入为字符串表达式时:

raw_input(): 读取控制台的输入,但不会对输入的数字进行运算,直接返回字符串类型,当作字符串处理

input(): 读取控制台的输入,对合法的 python 数字表达式进行运算,返回运算后的结果

6.4、输入的为特殊字符时

比如'\t','\n'等

raw_input(): 读取控制台的输入,返回字符串类型,和输入一样

input(): 读取控制台的输入,但输入时必须使用引号括起来,返回特殊符号所代表的内容

注:无特殊要求建议使用 raw_input() 来与用户交互

7:实例:

7.1、输入为字符串的时:

>>> a1 = raw_input("raw_input_str: ")

raw_input_str: hello

>>> print a1,type(a1)

hello <type 'str'>

>>> a2 = input("input_str: ")

input_str: hello

Traceback (most recent call last):

File "<pyshell#4>", line 1, in <module>

a2 = input("input: ")

File "<string>", line 1, in <module>

NameError: name 'hello' is not defined

>>> a2 = input("input_str: ")

input_str: 'hello'

>>> print a2,type(a2)

hello <type 'str'>

7.3、输入为字符串表达式时:

>>> c1 = raw_input("raw_input_exp: ")

raw_input_exp: 3 + 3

>>> print c1,type(c1)

3 + 3 <type 'str'>

>>> c2 = input("input_exp: ")

input_exp: 3 + 3

>>> print c2,type(c2)

6 <type 'int'>

7.4、输入的为特殊字符时:

>>> d1 = raw_input("raw_input_sp: ")

raw_input_sp: \t

>>> print d1,type(d1)

\t <type 'str'>

>>> d2 = input("input_sp: ")

input_sp: \t

Traceback (most recent call last):

File "<pyshell#57>", line 1, in <module>

d2 = input("input_sp: ")

File "<string>", line 1

\t

^

SyntaxError: unexpected character after line continuation character

>>> d2 = input("input_sp: ")

input_sp: '\t'

>>> print d2,type(d2)

<type 'str'>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: