浅谈Python2和Python3的区别
声明:由于博主主要用的是Python3.5,所以文中可能出现一些纰漏,敬请谅解,也可以向我提出来。
十点区别
一、print
print几乎是每种编程语言必须有的,Python也不例外,而且Python2和Python3最大的区别之一就是print。在Python2中,print是一个关键字,如下:
>>> import keyword
>>> keyword.kwlist
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']
>>>
而在Python3中,print是一个函数,因此Python3中print都需要加上括号表示函数,如下:
>>> help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
其中value就是要打印的字符串,sep=’ ‘表示默认用空格隔开,end=’\n’表示默认换行。
例子:
end:
>>> print('hello', end='')
hello>>> print('world')
注:Python2不换行只需要用一个逗号,
隔开。
sep:
>>> print('hello', 'world')
hello world
>>> print('hello', 'world', sep=',')
hello,world
二、输入函数
在Python2中,输入函数有两种:input()
和raw_input()
>>> something = input('input what you want to do:')
input what you want to do:'play basketball'
>>> print something
play basketball
>>> something = raw_input('input what you want to do:')
input what you want to do:'do sports'
>>> print something
'do sports'
而在Python3中,只保留了input()
函数。
三、异常处理
相比较Python2,Python3在异常处理方面改动得比较多,比如:
1.异常的继承&#x