您的当前位置:首页python2和pyhton3输入语句写法

python2和pyhton3输入语句写法

2020-05-04 来源:小侦探旅游网
python2和pyhton3输⼊语句写法

Python的输⼊语句类型

1 python2的输⼊语句

在python2中有两种常见的输⼊语句,input()和raw_input()。

(1)input()函数

可以接收不同类型的参数,⽽且返回的是输⼊的类型。如,当你输⼊int类型数值,那么返回就是int型;其中字符型需要⽤单引号或双引号,否则,报错。a.数值型输⼊

>>> a = input()10

>>> type(a)>>> a10

>>> a = input()1.23

>>> type(a)>>> a1.23

b.字符类型

如果输⼊的字符不加引号,就会报错

>>> r = input()hello

Traceback (most recent call last):

File \"\", line 1, in r = input()

File \"\", line 1, in NameError: name 'hello' is not defined

正确的字符输⼊

>>> r = input()'hello'>>> r'hello'

>>> r = input()\"hello\">>> r'hello'

当然,可以对输⼊的字符加以说明

>>> name = input('please input name:')please input name:'Tom'>>> print 'Your name : ',nameYour name : Tom

(2)raw_input()

函数raw_input()是把输⼊的数据全部看做字符类型。输⼊字符类型时,不需要加引号,否则,加的引号也会被看做字符。

>>> a = raw_input()1

>>> type(a)>>> a'1'

>>> a = raw_input()'hello'

>>> type(a)>>> a\"'hello'\"

如果想要int类型数值时,可以通过调⽤相关函数转化。

>>> a = int(raw_input())1

>>> type(a)>>> a1

>>> a = float(raw_input())1.23

>>> type(a)>>> a1.23

在同⼀⾏中输⼊多个数值,可以有多种⽅式,这⾥给出调⽤map() 函数的转换⽅法。map使⽤⽅法请参考

>>> a, b = map(int, raw_input().split())10 20>>> a10>>> b20

>>> l = list(map(int, raw_input().split()))1 2 3 4>>> l

[1, 2, 3, 4]

(3)input() 和raw_input()的区别

通过查看input()帮助⽂档,知道input函数也是通过调⽤raw_input函数实现的,区别在于,input函数额外调⽤内联函数eval()。eval使⽤⽅法参考

>>> help(input)

Help on built-in function input in module __builtin__:input(...)

input([prompt]) -> value

Equivalent to eval(raw_input(prompt)).

>>> help(eval)

Help on built-in function eval in module __builtin__:

eval(...)

eval(source[, globals[, locals]]) -> value

Evaluate the source in the context of globals and locals.

The source may be a string representing a Python expression or a code object as returned by compile().

The globals must be a dictionary and locals can be any mapping, defaulting to the current globals and locals. If only globals is given, locals defaults to it.

2 Python3输⼊语句

python3中的输⼊语句只有input()函数,没有raw_input();⽽且python3中的input()函数与python2中的raw_input()的使⽤⽅法⼀样。

>>> a = input()10

>>> type(a)>>> a'10'

因篇幅问题不能全部显示,请点此查看更多更全内容