Python3与2区别(学习笔记)

一、输出语句

在2中
>>> print'hello,world'
hello,world
在3中
>>> print'hello,world'
SyntaxError: invalid syntax
>>> print('hello,world')
hello,world

二、不等于

在2中: 不等于可以用!=或<>
在3中:不等于只能用!=

三、整除

在2中:
>>>1/2            #整除
0
>>> 1//2          #"//"表示整除,就算是浮点数也表示整除
0
如果需要普通的除法,有两种方式:
1、将一个及以上的数变成浮点数
>>>1.0/2.0
0.5
>>>1.0/2
0.5
>>>1/2.0
0.5
2、在程序前输入以下语句:from__future__import division ("__"是两个下划线)
在3中:
>>> 1//2
0
>>> 1/2
0.5

四、长整型数

在2中:
>>> 10000000000000000000000000000000    #普通整数在-2147483648~2147483647之间。如果需要大数就会用到长整型数,书写方法与普通整数一样,但结尾有个L
10000000000000000000000000000000L
在3中:
>>> 10000000000000000000000000000000
10000000000000000000000000000000

五、输入语句(获取用户输入)

在2中:
>>> price=raw_input('input the stock price of Apple:')
input the stock price of Apple:109
>>> price
'109'
>>> price=input('input the stock price of Apple:')
input the stock price of Apple:109
>>> price
109


在3中:

>>> price=raw_input('input the stock price of Apple:')             #3中raw_input()和input()整合成了input(),返回类型为str
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    price=raw_input('input the stock price of Apple:')
NameError: name 'raw_input' is not defined
>>> price=input('input the stock price of Apple:')
input the stock price of Apple:109
>>> price
'109'


六、重新加载

在3中:

>>>from imp import reload
>>> reload(kNN)
<module 'kNN' from 'D:\\Python\\kNN.py'></span>

>>> reload(kNN)
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    reload(kNN)
NameError: name 'reload' is not defined</span>

七、range()和xrange()

在2中:

range()和xrange()的语法一样,前者返回的是列表,后者返回的是生成器,但后者在内存上更有效。

>>>range(3,11,2)
[3, 5, 7, 9]
>>> xrange(3,11,2)
xrange(3, 11, 2)
>>>for i in xrange(3,11,2):
...     print i
... 
3
5
7
9

在3中:

没有xrange()。range()的功能就是2.x中xrange()的功能。

>>>for i in range(3,11,2):
	print(i)

	
3
5
7
9

如果要获得真实列表,需要显示调用:

>>> list(range(3,11,2))
[3, 5, 7, 9]

八、urllib.urlopen()

在2中:
>>> import urllib
>>> r = urllib.urlopen('http://z.cn/')
>>> htlm = r.read()

在3中:
>>> import urllib.request
>>> r = urllib.request.urlopen('http://z.cn/')
>>> htlm = r.read()










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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值