1. 程式人生 > >Python 2.x 中的 raw_input() 和 input()

Python 2.x 中的 raw_input() 和 input()

Python 2.x 和 Python 3.x 還是有一點小差別的。比如 input 在 Python 2.x 中有兩個函式 raw_input()input()。在 Python 3.x 中,只有一個函式來獲取使用者輸入,這被稱為 input(),這相當於 Python 2.7 的 raw_input()

例 1:input()

name = input('Please enter your number: ')
print name

命令列 1.1

Please enter your number: 'qq'
qq

命令列 1.2

Please enter your number
: "qq" qq

命令列 1.3

Please enter your number: qq
Traceback (most recent call last):
    File "onr.py", line 1, in < module> #onr.py是我的檔名
    name = input('Please enter your number: ')
  File "< string>", line 1, in < module >
NameError: name 'qq' is not defined

命令列 1.4

Please enter your number
: 11 11

命令列 1.5

Please enter your number: '1+1'
1+1

命令列 1.6

Please enter your number: 1+1
2

例 2:raw_input()

name = raw_input('Please enter your number: ')
print name

命令列 2.1

Please enter your number: qq
qq

命令列2.2

Please enter your number: '1+1'
'1+1'

命令列2.3

Please enter your number
: 1+1 1+1

Python 2.x

  • raw_print() 可以直接讀取控制檯的任何型別輸入,並且只會讀入您輸入的任何內容,返回字串型別。即可用把控制檯所有輸入作為字串看待,並返回字串型別。
  • input() 能夠讀取一個合法的 python 表示式,返回數值型別,如int,float。即如果你在控制檯輸入的字串必須用單引號或雙引號將它括起來,否則會引發 SyntaxError 。

這裡寫圖片描述

Python 3.x

Python 2.x 中的 raw_input() 被重新命名為 Python 3.x 中的 input(),所以 Python 3.x 中的 input() 返回型別為字串型別。同時 Python 2.x 中的 input() 在 Python 3.x 中不再保留。

Python input 說明文件 可以看到 input() 其實是通過 raw_input() 來實現的,原理很簡單,就下面一行程式碼:

def input(prompt):
    return (eval(raw_input(prompt)))

如果要使用 Python 2.x 中的 input(),即需要將使用者輸入看作 Python 語句,則必須手動操作 eval(input())