Python3与2的故事一

print函数:(Python3中print为一个函数,必须用括号括起来;Python2中print为class)

Python 2 的 print 声明已经被 print() 函数取代了,这意味着我们必须包装我们想打印在小括号中的对象。

Python 2

print 'Python', python_version()
print 'Hello, World!'
print( 'Hello, World!')
print "text", ; 
print 'print more text on the same line'
 
run result:
Python 2.7.6
Hello, World!
Hello, World!
text print more text on the same line

Python 3

1
2
3
4
print( 'Python', python_version())
print( 'Hello, World!')
print( "some text,", end="")
print( ' print more text on the same line')

run result:
Python 3.4.1
Hello, World!
some text, print more text on the same line


通过input()解析用户的输入:(Python3中input得到的为str;Python2的input的到的为int型,Python2的raw_input得到的为str类型)统一一下:Python3中用input,Python2中用row_input,都输入为str

幸运的是,在 Python 3 中已经解决了把用户的输入存储为一个 str 对象的问题。为了避免在 Python 2 中的读取非字符串类型的危险行为,我们不得不使用 raw_input() 代替。

Python 2
Python 2.7.6
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type “help”, “copyright”, “credits” or “license” for more information.

>>> my_input = input('enter a number: ')
 enter a number: 123 >>> type(my_input) <type 'int'> >>> my_input = raw_input('enter a number: ')  enter a number: 123 >>> type(my_input) <type 'str'> 

Python 3
Python 3.4.1
[GCC 4.2.1 (Apple Inc. build 5577)] on darwin
Type “help”, “copyright”, “credits” or “license” for more information.

>>> my_input = input('enter a number: ')
 enter a number: 123 >>> type(my_input) <class 'str'>

 


 

整除:(没有太大影响)(Python3中/表示真除,%表示取余,//表示地板除(结果取整);Python2中/表示根据除数被除数小数点位得到结果,//同样表示地板除)统一一下:Python3中/表示真除,%表示取余,//结果取整;Python2中带上小数点/表示真除,%表示取余,//结果取整

Python 2

1
2
3
4
5
print 'Python', python_version()
print '3 / 2 =', 3 / 2
print '3 // 2 =', 3 // 2
print '3 / 2.0 =', 3 / 2.0
print '3 // 2.0 =', 3 // 2.0

run result:
Python 2.7.6
3 / 2 = 1
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0

Python 3

1
2
3
4
5
print( 'Python', python_version())
print( '3 / 2 =', 3 / 2)
print( '3 // 2 =', 3 // 2)
print( '3 / 2.0 =', 3 / 2.0)
print( '3 // 2.0 =', 3 // 2.0)

run result:
Python 3.4.1
3 / 2 = 1.5
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0

转载于:https://www.cnblogs.com/linux985/p/10208706.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值