[英]Python programs using Loops
Given this Python program: 鉴于此Python程序:
num = input("Enter a number: ")
result = 1024
for i in range(num):
result = result / 2
print result
If the number you enter is 4, why is the output of this program 64? 如果输入的数字为4,为什么该程序的输出为64?
Trace through the program to see what happens. 跟踪程序以查看发生了什么。
range(num)
here is range(4)
, which gives the values 0, 1, 2, and 3. range(num)
是range(4)
,其值为0、1、2和3。
When i = 0, we divide 1024 by 2 to get 512. 当i = 0时,我们将1024除以2得到512。
When i = 1, we divide 512 by 2 to get 256. 当i = 1时,我们将512除以2得到256。
When i = 2, we divide 256 by 2 to get 128. 当i = 2时,我们将256除以2得到128。
When i = 3, we divide 128 by 2 to get 64. 当i = 3时,我们将128除以2得到64。
And voila! 瞧! There's your 64.
有你的64。
More generally, each iteration of the loop will divide result
by 2, so after num iterations of the loop, result
will be 1024 / 2 num . 更一般而言,循环的每次迭代将
result
除以2,因此在循环的num次迭代之后, result
将为1024/2 num 。 Since 1024 = 2 10 , this means that the result is 2 10 / 2 num = 2 10 - num . 由于1024 = 2 10,这意味着,其结果是2 10/2 NUM = 2 10 - NUM。 That said, if
num > 10
, because result
is an integer, Python will round down to zero. 就是说,如果
num > 10
,因为result
是一个整数,Python将舍入为零。 In other words: 换一种说法:
range(num)
is the empty range and the program prints 1024. range(num)
为空范围,程序将输出1024。 Hope this helps! 希望这可以帮助!
You can see what's happening by simply adding some debug statements to your code: 您只需在代码中添加一些调试语句,即可看到发生了什么:
num = input("Enter a number: ")
result = 1024
print "Starting result %d"%(result)
print range(num)
for i in range(num):
result = result / 2
print "Looping result %d"%(result)
print result
If you run that and enter 4, you'll see: 如果运行该命令并输入4,您将看到:
Enter a number: 4
Starting result 1024
[0, 1, 2, 3]
Looping result 512
Looping result 256
Looping result 128
Looping result 64
64
The reason is that range(4)
gives you the list [0,1,2,3]
with four elements in it, so that's how many times the body of the loop is being executed. 原因是
range(4)
为列表[0,1,2,3]
提供了四个元素,因此这是循环主体执行的次数。
On each execution of the body, you simply halve the current value of the result: 每次执行主体时,您只需将结果的当前值减半:
iteration 1, 1024 -> 512
iteration 2, 512 -> 256
iteration 3, 256 -> 128
iteration 4, 128 -> 64
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.