Python2中input()、raw_input()和Python3中input(),python2python3

來源:互聯網
上載者:User

Python2中input()、raw_input()和Python3中input(),python2python3

    聽了ALEX的某節課,說input()和raw_input()函數在Python2中沒有區別,現在來探討一下Python2中的input()、raw_input()函數和Pyhont3中的input()函數:

    Python2中的raw_input()函數,我們知道input()、raw_input()都是讓使用者輸入的函數:

    input()函數:

    首先,我們先輸入數字:

>>> a = input("Please input your favorite number: ")
Please input your favorite number: 5
>>> a
5

    從中可以看出,當我們輸入數位時候,input()函數直接接受了5,並把這個使用者輸入的數字賦給了a,是以數字形式的。

    接下來,我們以字元形式輸入:
>>> a = input("Please input your name: ")
Please input your name: virgin
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'virgin' is not defined

    從結果可以看出,提示我們輸入的名字沒有定義,報錯了,說明不能以字元形式直接沒有引號的情況下進行輸入;

    我們驗證當我們以引號的方式輸入字串的時候,這個時候沒有提示我們錯誤,由此可以看出,是沒有問題的
>>> a = input("Please input your name: ")
Please input your name: "Virgin"
>>> a
'Virgin'

    從中可以看出,其實Python2.x中,input()函數讓我們明確我們輸入的是數字格式還是字元格式設定,就是我們自己要知道我們想要的是什麼,數字格式直接輸入,字元格式設定必須加上單引號或者雙引號,以確定我們輸入的是字串。

    raw_input()函數:

>>> a = raw_input("Please input your name: ")
Please input your name: Virgin
>>> a
'Virgin'
>>> a = raw_input("Please input your favorite number: ")
Please input your favorite number: 10
>>> a
'10'
    第一次我們輸入的是字串,而且沒有加引號,正常把Virgin賦給了變數a;第二次輸入的是數字10,但是輸出的時候,a是字元格式設定的'10',這個時候系統將我們輸入的數字預設為了文本,所以可以看出,raw_input()函數無論使用者輸入什麼,都預設為字元格式設定;而input()函數在Python2.x中,是要使用者確定自己輸入的是什麼,使用者要自己清楚明白自己操控的是什麼。

    Python3中的input()函數:

    我們知道,在Python3中是沒有raw_input()函數的,只有input()函數,因為Python3是就行了最佳化整合:

    input()函數

>>> a = input("Please input your favoriete number: ")
Please input your favoriete number: 10
>>> a
'10'
>>> b = input("Please input your name: ")
Please input your name: Virgin
>>> b
'Virgin'
    第一次我們輸入的是數字,此時,input()是將數字10當作文本賦給了變數a,第二次,我們把文本賦給了變數b,輸出結果還是文本,這與Python2中的raw_input()是一樣的,所以,在Python3中是將Python2中的input()刪除了,把raw_input()的名稱改成了input()函數,這樣在我們使用數位時候就需要自己來進行轉換了,所以我們在讓使用者輸入數位時候一定切忌要進行轉換,如果我們要使用數位化。

   

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.