简体   繁体   English

在for循环外打印一个值

[英]printing a value outside of the for loop

I am studying for a final in a beginners programming class. 我正在初学者编程课上学习决赛。 I received this question wrong on my midterm. 期中考试我错了。 I said the answer is 1, however, the answer is actually 0. I was wondering if anyone could explain to me why it is 0. Is it because z is originally assigned to 0? 我说答案是1,但是答案实际上是0。我想知道是否有人可以向我解释为什么它是0。这是因为z最初分配为0吗? I am not sure how to tell if it's a local variable with this limited code. 我不确定如何使用此受限代码来判断它是否是局部变量。 Thank you for any help you provide! 感谢您提供的任何帮助!

z=0
for x in range(1, 200, -1):
    z=z+1
print(z)

There is no elements at range(1, 200, -1) , the loop not even starts. range(1, 200, -1)处没有元素,循环甚至没有开始。 So z never changed its value. 因此z从未改变其值。

Read about the step(third arg of range) arg here: 在此处阅读有关步骤(范围的第三个参数)arg的信息:

https://docs.python.org/2/library/functions.html#range https://docs.python.org/2/library/functions.html#range

A nice way to see this is convert the range to list: 一种很好的查看方式是将范围转换为列表:

print(list(range(1, 200, -1)))
>>> []

You should test it out in your interpreter. 您应该在解释器中对其进行测试。 The loop never makes an iteration. 循环永远不会进行迭代。 Think of what is being incremented. 想想正在增加什么。

Your range is 1 through 200, but you are choosing to increment by -1 at each step starting at 1, so you cannot move backwards in this case. 您的范围是1到200,但是您选择从1开始的每一步都以-1递增,因此在这种情况下您不能向后移动。

它保持为零,因为范围是1、200,但您步进-1,因此for循环内的表达式从未真正执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM