python2 和 pyhton3 输入语句写法

Python的输入语句类型

1 python2的输入语句

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

(1)input()函数

能够接收不一样类型的参数,并且返回的是输入的类型。如,当你输入int类型数值,那么返回就是int型;其中字符型须要用单引号或双引号,不然,报错。python

a.数值型输入shell

>>> a = input()
10
>>> type(a)
<type 'int'>
>>> a
10
>>> a = input()
1.23
>>> type(a)
<type 'float'>
>>> a
1.23

b.字符类型express

若是输入的字符不加引号,就会报错app

>>> r = input()
hello

Traceback (most recent call last):
  File "<pyshell#50>", line 1, in <module>
    r = input()
  File "<string>", line 1, in <module>
NameError: name 'hello' is not defined

正确的字符输入函数

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

固然,能够对输入的字符加以说明post

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

(2)raw_input()

函数raw_input()是把输入的数据所有看作字符类型。输入字符类型时,不须要加引号,不然,加的引号也会被看作字符。ui

>>> a = raw_input()
1
>>> type(a)
<type 'str'>
>>> a
'1'
>>> a = raw_input()
'hello'
>>> type(a)
<type 'str'>
>>> a
"'hello'"

若是想要int类型数值时,能够经过调用相关函数转化。lua

>>> a = int(raw_input())
1
>>> type(a)
<type 'int'>
>>> a
1
>>> a = float(raw_input())
1.23
>>> type(a)
<type 'float'>
>>> a
1.23

在同一行中输入多个数值,能够有多种方式,这里给出调用map() 函数的转换方法。map使用方法请参考python-map的用法url

>>> a, b = map(int, raw_input().split())
10 20
>>> a
10
>>> b
20
>>> 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使用方法参考Python 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)
<class 'str'>
>>> a
'10'
相关文章
相关标签/搜索