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? 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. So z
never changed its value.
Read about the step(third arg of range) arg here:
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,因此for循环内的表达式从未真正执行。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.