歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python raw_input()和input() 函數 讀取交互輸入

Python raw_input()和input() 函數 讀取交互輸入

日期:2017/3/1 9:33:33   编辑:Linux編程

函數:raw_input()和input()

注意:在python3.x中,已經刪除raw_input(),取而代之的是input(),當然這僅僅是重命名,用法還是一樣。因此在這裡介紹的是python2.x中的raw_input()和input(),在python3.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 http://www.linuxidc.com/Linux/2015-01/111870.htm

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

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

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

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

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

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

Copyright © Linux教程網 All Rights Reserved