Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Python raw_input() 與 input():讀取互動式輸入全解析

函數:raw_input() 和 input()

注意:在 Python 3.x 中已經移除 raw_input(),改由 input() 取代,其實只是換了個名字,用法完全一樣。因此本文介紹的是 Python 2.x 的 raw_input() 與 input(),在 3.x 中只要照 raw_input() 的方式去用即可。

1:作用:讀取控制台的輸入,與使用者互動。

2:語法
raw_input([prompt])
input([prompt])

3:參數
prompt:若存在,會直接輸出到螢幕,且不會換行。

4:兩者關係:
input() 本質上是用 raw_input() 實作的,也就是先呼叫 raw_input(),再套一層 eval(),如下:
def input(prompt):
    return (eval(raw_input(prompt)))

5:相同點:
都能接受字串、數字以及運算式作為輸入。

6:差別:

6.1、輸入為字串時:
raw_input():讀取輸入並回傳字串型別
input():讀取輸入,但輸入時必須用引號括起來,否則會報錯

6.2、輸入為純數字時:
raw_input():回傳字串型別,當作字串處理
input():回傳輸入的數值型別(int、float)

6.3、輸入為字串運算式時:
raw_input():不會對數字做運算,直接回傳字串
input():會對合法的 Python 數字運算式求值,回傳運算結果

6.4、輸入為特殊字元時(如 '\t'、'\n'):
raw_input():回傳字串型別,內容與輸入一致
input():必須用引號括起來,回傳特殊符號所代表的內容

註:無特殊需求時,建議用 raw_input() 與使用者互動。

7:實例

7.1、輸入為字串時:

>>> a1 = raw_input("raw_input_str: ")
raw_input_str: hello
>>> print a1,type(a1)
hello <type 'str'>

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

>>> a2 = input("input_str: ")
input_str: 'hello'
>>> print a2,type(a2)
hello <type 'str'>

7.3、輸入為字串運算式時:

>>> c1 = raw_input("raw_input_exp: ")
raw_input_exp: 3 + 3
>>> print c1,type(c1)
3 + 3 <type 'str'>

>>> c2 = input("input_exp: ")
input_exp: 3 + 3
>>> print c2,type(c2)
6 <type 'int'>

7.4、輸入為特殊字元時:

>>> d1 = raw_input("raw_input_sp: ")
raw_input_sp: \t
>>> print d1,type(d1)
\t <type 'str'>

>>> d2 = input("input_sp: ")
input_sp: \t
Traceback (most recent call last):
  File "<pyshell#57>", line 1, in <module>
    d2 = input("input_sp: ")
  File "<string>", line 1
    \t
    ^
SyntaxError: unexpected character after line continuation character

>>> d2 = input("input_sp: ")
input_sp: '\t'
>>> print d2,type(d2)
 <type 'str'>

--------------------------------------分割線 --------------------------------------

CentOS上源碼安裝Python3.4  https://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] https://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] https://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 https://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 https://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 https://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved