iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 17
0
Data Technology

30天python雜談系列 第 17

版本差異雜談之七———今天先讓自己input()一下

python 版本差異雜談之七

囉唆一下:阿呀呀,本來想要在六就結束版本差異雜談的,但差異六要講清楚的東西實在太多了,只好多開一個七了,但這樣也好,少讓我發一天的文,今天我就休息一下,輕鬆寫寫吧~

差異七:input()與raw_input()

input和raw_input,都可以用來設立程式的停駐點讀取teminal的輸入,差別在於raw_input讀取了用戶的輸入後,如實的把用戶的輸入字串作為一個回傳值,input不太一樣,他會把用戶的輸入作為一個字串表達式並執行他,其功能和eval相似,而確實,在python2的官方文檔:https://docs.python.org/2.7/library/functions.html#input 有指明input(prompt)等同於eval(raw_input(prompt)),所以input的功能就相當讀取用戶輸入的eval():

In python2 shell:
>>> while True:
...     raw_input_return = raw_input("Using the raw_input(): ")
...     print "the return value of raw_input():",raw_input_return
... 
Using the raw_input(): example
the return value of raw_input(): example
Using the raw_input(): 1+1
the return value of raw_input(): 1+1
Using the raw_input(): 範例輸入
the return value of raw_input(): 範例輸入
Using the raw_input(): 拉拉拉
the return value of raw_input(): 拉拉拉

In python2 shell:
>>> while True:
...   try:
...     input_return = input("Using the input(): ")
...   except Exception, e:
...     print "Error occur:",str(e)
...     continue
...   print "the return value of input():",input_return
... 
Using the input(): example
Error occur: name 'example' is not defined
Using the input(): 1+1
the return value of input(): 2
Using the input(): 我是範例
Error occur: invalid syntax (<string>, line 1)
Using the input(): 'lalala'
the return value of input(): lalala
Using the input(): 'lalala'+'hahaha'
the return value of input(): lalalahahaha

python3和python3不同的地方是python3已經沒有所謂的raw_input了,而input也變得只回傳用戶輸入的字串,而不會將其視為一個表達式來執行:

In python3 shell:
>>> raw_input()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'raw_input' is not defined
>>> while True:
...     input_return = input("Using the input(): ")
...     print("the return value of input():",input_return)
... 
Using the input(): example
the return value of input(): example
Using the input(): 1+1
the return value of input(): 1+1
Using the input(): 範例輸入
the return value of input(): 範例輸入
Using the input(): 拉拉拉
the return value of input(): 拉拉拉

所以如果想要在程式中設置一個暫停點並讀取用戶輸入,python2要用raw_input(),python3要用input()。

yaya版本差異雜談到此結束,突然覺得過好久了阿,我在寫草稿的時候就一直在苦思要怎麼寫,查了非常多資料,今天終於把他解決掉了,以下我就附上一些網路上介紹版本差異的實用文章給大家:
http://sebastianraschka.com/Articles/2014_python_2_3_key_diff.html
https://docs.python.org/3.0/whatsnew/3.0.html
https://www.zhihu.com/question/19698598


上一篇
版本差異雜談之六———pos_args與kw_args之亂
下一篇
iterator和generator雜談之一———剖析for in內部機制
系列文
30天python雜談30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言