python中input()與raw_input()的區別

天飛.h發表於2016-04-21

先看一段操作:
[13:51 t /tmp]$ python
Python 2.7.11 (default, Mar 31 2016, 20:46:51)
[GCC 5.3.1 20151207 (Red Hat 5.3.1-2)] on linux2
Type “help”, “copyright”, “credits” or “license” for more information.
>>> name=input(“Your name:”)
Your name:talen    #使用input()輸入內容不加引號
Traceback (most recent call last):
  File “”, line 1, in
  File “”, line 1, in
NameError: name `talen` is not defined
>>> name=input(“Your name:”)
Your name:”talen”    #使用input()輸入內容新增引號
>>> print name
talen
>>> name=raw_input(“Your name:”)
Your name:talen        #使用raw_input()輸入內容不加引號
>>> print name
talen
>>>
從上面的例子可以看出,如果想輸入字串,input()的輸入內容必須使用“號,否則會被認為是變數名。
>>> num=input(“Your num:”)
Your num:897
>>> type(num)

>>> num2=raw_input(“Your num:”)
Your num:897
>>> type(num2)

>>>
從這個操作來看,input()接受了輸入的資料型別,raw_input()把輸入當作字串來看。所以input()輸入必須進行資料型別的轉換才能正確表達第一個例子中的輸入。
input([prompt])

Equivalent to eval(raw_input(prompt)).

This function does not catch user errors. If the input is not syntactically
valid, a SyntaxError will be raised. Other exceptions may be raised if
there is an error during evaluation.

If the readline module was loaded, then input() will use it to
provide elaborate line editing and history features.

Consider using the raw_input() function for general input from users.


相關文章