Python3与2区别(学习笔记)

来源:互联网 发布:dnf本地安全策略优化 编辑:程序博客网 时间:2024/05/21 06:48

一、输出语句

在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.00.5>>>1.0/20.5>>>1/2.00.5
2、在程序前输入以下语句:from__future__import division ("__"是两个下划线)
在3中:
>>> 1//20
>>> 1/20.5

四、长整型数

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

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

在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>>> price109


在3中:

>>> price=raw_input('input the stock price of Apple:')             #3中raw_input()和input()整合成了input(),返回类型为strTraceback (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... 3579

在3中:

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

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

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

>>> 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
原创粉丝点击