python中3个while循环_Python中while循环的一个问题

本文详细对比了Python2.x和Python3.x中print语句的使用差异,以及浮点数处理的区别。在Python3.x中,print变为函数,而在2.x中是语句。此外,当执行特定数学运算时,3.x会得到浮点型结果,而2.x则可能得到整型。通过示例代码和循环迭代次数的分析,解释了这种差异的原因,并强调了在调试程序时使用print输出的重要性。
摘要由CSDN通过智能技术生成

展开全部

是因为2113你使用的编译器是python3.x的原5261因:Python 3.3.1 (default, Apr 17 2013, 22:32:14)

[GCC 4.7.3] on linux

Type "help", "copyright", "credits" or "license" for more information.

>>> a = 1

>>> b = 1

>>> while a > 0:

... b += 1

... a /= b

...

>>> print(a, b)

0.0 178

如果使用python2.x的话,打印出4102来将是(0,2)Python 2.7.4 (default, Apr 19 2013, 18:32:33)

[GCC 4.7.3] on linux2

Type "help", "copyright", "credits" or "license" for more information.

>>> a = 1

>>> b = 1

>>> while a > 0:

... b += 1

... a /= b

...

>>> print (a,b)

(0, 2)

>>> c = (a, b)

>>> print c

(0, 2)

>>> print type(c)

可以比较明显的看到,使1653用python3.x输出的结果是一个浮点型(float),一个整型(int);而使用python2.x输出的结果是元组(tuple, 直观看就是带括号)。

这就是python3.x和python2.x的比较明显的一个区别---print

在python2.x中,print是个语句(statement),而在3.x中,print是个函数(function),最直接的例子:

在2.x中:>>> print 'hello world'

hello world

在3.x中:Python 3.3.1 (default, Apr 17 2013, 22:32:14)

[GCC 4.7.3] on linux

Type "help", "copyright", "credits" or "license" for more information.

>>> print 'hello world'

File "", line 1

print 'hello world'

^

SyntaxError: invalid syntax

>>> print ('hello world')

hello world

>>>

-------

还有一个比较明显的区别是在3.x中,最后打印的a为0.0(浮点型);而在2.x中,a为0(没有小数点,整型)。这就说明了为什么在python3.x中迭代了178次,因为:第一次:b = 1 + 1 = 2; a = 1 / 1 + 1 = 0.5

第二次:b = 2 + 1 = 3; a = 0.5 / 2 + 1 = 0.167

....

需要迭代178次,才使得 a 终于 < 0.

如果你在循环中加入打印的话,例如:Python 3.3.1 (default, Apr 17 2013, 22:32:14)

[GCC 4.7.3] on linux

Type "help", "copyright", "credits" or "license" for more information.

>>> a = 1

>>> b = 1

>>> while a > 0:

... b = b + 1

... a = a / b

... print ('a: ', a)

... print ('b: ', b)

...

a: 0.5

b: 2

a: 0.16666666666666666

b: 3

a: 0.041666666666666664

b: 4

a: 0.008333333333333333

b: 5

a: 0.001388888888888889

...

...

b: 175

a: 5.054e-321

b: 176

a: 3e-323

b: 177

a: 0.0

b: 178

>>> print(1/2)

0.5

这样,你比较容易知道原因了。

同样,我打印出了python2.x的结果:Python 2.7.4 (default, Apr 19 2013, 18:32:33)

[GCC 4.7.3] on linux2

Type "help", "copyright", "credits" or "license" for more information.

>>> a = 1

>>> b = 1

>>> while a > 0:

... b = b + 1

... a = a / b

... print 'a: ', a

... print 'b: ', b

...

a: 0

b: 2

>>> print 1/2

0

最后,打印是程序调试很有用的方法,通过打印的结果,你会知道每一步的运行结果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值