python2 和 pyhton3 輸入語句寫法


Python的輸入語句類型

1 python2的輸入語句

在python2中有兩種常見的輸入語句,input()和raw_input()。

(1)input()函數

可以接收不同類型的參數,而且返回的是輸入的類型。如,當你輸入int類型數值,那么返回就是int型;其中字符型需要用單引號或雙引號,否則,報錯。

a.數值型輸入

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

b.字符類型

如果輸入的字符不加引號,就會報錯

>>> 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'

當然,可以對輸入的字符加以說明

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

(2)raw_input()

函數raw_input()是把輸入的數據全部看做字符類型。輸入字符類型時,不需要加引號,否則,加的引號也會被看做字符。

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

如果想要int類型數值時,可以通過調用相關函數轉化。

>>> 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的用法

>>> 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'

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM