Python2和3的主要區別,Python2區別
一、print
在 python2 中 print 是一條語句,而在 python3 中 print 作為函數存在。
# python2>>> print ("hello")hello# python3 >>> print ("hello")hello
這樣看好像沒有什麼區別,python2 好像也可以把 print 當做函數使用,但是僅僅是表象而已,前者是把 ("hello")當作一個整體,而後者 print()是個函數,接收字串作為參數。
#python2>>> print ("hello","world")('hello', 'world')#python3>>> print ("hello","world")hello world
這樣看就非常明顯了,python2 中,print 語句後接的是元組對象 ("hello","world")。
而 python3 中,print() 函數是得到了兩個位置參數 hello 和 world 。
如果想在 python2 中把 print 當做函數使用,可以匯入 __future__ 模組中的 print_function
>>> print ("Hello","world")('Hello', 'world')>>> >>> from __future__ import print_function>>> print ("Hello","world")Hello world
二、編碼
python2 預設編碼是 asscii,所以不能直接列印中文,如果要在指令碼中使用中文,需要在指令碼中聲明使用utf-8,# -*- coding: utf-8 -*-,
#!/usr/bin/env python# -*- coding: utf-8 -*-print "您好"
而在 python3 中,預設編碼已經是 utf-8 了,所以已經不需要單獨聲明了,可以直接列印中文內容。
#!/usr/bin/env pythonprint ("您好")
三、使用者輸入
python 2 使用者輸入使用 raw_input(),python 3 使用 input(),python2 中也可以使用 input(),但是參數只能是變數,不推薦在python 2 中使用 input()。
#!/usr/bin/env python#user_input = raw_input("Please input something: ") #only on python 2.xuser_input = input("Please input something: ")print(user_input)