python中while循环并列_Python中while循环的一个问题

匿名用户

1级

2013-08-27 回答

是因为你使用的编译器是python3.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.

>>> a = 1

>>> b = 1

>>> while a > 0:

...     b += 1

...     a /= b

...

>>> print(a, b)

0.0 178如果使用python2.x的话,打印出来将是(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)

可以比较明显的看到,使用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 终于 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值