python2 和 pyhton3 輸入語句寫法

來源:互聯網
上載者:User

標籤:compile   com   類型   調用   log   put   title   通過   協助   

Python的輸入語句類型1 python2的輸入語句

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

(1)input()函數

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

a.數值型輸入

>>> a = input()10>>> type(a)<type ‘int‘>>>> a10>>> a = input()1.23>>> type(a)<type ‘float‘>>>> a1.23

b.字元類型

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

>>> r = input()helloTraceback (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 : ‘,nameYour 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‘>>>> a1>>> a = float(raw_input())1.23>>> type(a)<type ‘float‘>>>> a1.23

在同一行中輸入多個數值,可以有多種方式,這裡給出調用map() 函數的轉換方法。map使用方法請參考python-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使用方法參考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‘

 

python2 和 pyhton3 輸入語句寫法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.