与基本的python代码混淆

时间:2013-04-12 12:58:16

标签: python while-loop

我不明白这段代码。我在想,虽然iterLeft不等于0,但它将ans添加到x。 答案是0 x是3,等于3。 Iterleft - 1 = 2

print str(x)应该打印2,因为x是2,然后是2,然后是ans,这是3

我的解释有什么问题

x = 3
ans = 0
itersLeft = x
while (itersLeft != 0):
     ans = ans + x
     itersLeft = itersLeft - 1
print str(x) + '*' + str(x) + ' = ' + str(ans)

2 个答案:

答案 0 :(得分:5)

  

我的解释有什么问题

x设置为3,然后永远不会更改。我看不出您希望print str(x)如何打印2

  

它将ans添加到x

不,反过来说:ans = ans + xx添加到ans

答案 1 :(得分:0)

x始终为3,因为您不会在while循环中更改它。

你必须提供indentation after while loop