浅谈Python2和Python3的区别

浅谈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

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值