Python2和Python3主要的区别

  1. print

Python 2:print为class
Python 3:print为一个函数,必须用括号括起来;

>>> print 'Hello,Python2 !'
>>> print('Hello,Python3 ! ')
  1. input

Python 2:input得到的为int型,如果想要输入str类型使用raw_input
Python 3:input得到的为str;

>>>p3_input = input('enter a number: ') 	#enter a number: 123
>>>type(p3_input) 	#<type 'str'>

>>>p2_input = input('enter a number: ') 	#enter a number: 123
>>>type(p2_input) 	#<type 'int'>

>>> p2_input = raw_input('enter a number: ')  #enter a number: 123
>>> type(my_input)  #<type 'str'>
  1. 不等运算符

Python 2:不等于有两种写法 != 和 <>
Python 3:去掉了<>, 只有!=一种写法;

  1. 比较操作符区别

Python 2:任意两个对象都可以比较;
Python 3:只有同一数据类型的对象可以比较

#Python 2
>>> 11 < 'test'    #True
#Python 3
>>> 11 < 'test'   # TypeError: not supported between instances of 'str' and 'int'
  1. round

Python 2:round 函数返回 float 类型值;
Python 3:round 函数返回 int 类型值

#Python 2
>>>isinstance(round(15.5),float)  #True
#Python 3
>>>isinstance(round(15.5),int)    #True
  1. for 循环中变量值

Python 2:for 循环会修改外部相同名称变量的值;
Python 3:for 循环不会修改外部相同名称变量的值

  1. 异常抛出和捕捉机制

Python 2:

>>>raise IOError, "file error"  #抛出异常
>>>except NameError, err:       #捕捉异常

Python 3:

>>>raise IOError("file error")   #抛出异常
>>>except NameError as err:      #捕捉异常
  1. import

Python 2 :相对路径的 import ;
Python 3 :采用的是绝对路径的方式进行 import

  1. 字符

Python 2 :使用 ASCII 码作为默认编码方式导致 string 有两种类型 str 和 unicode;
Python 3: 只支持Unicode 字符的 string

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值