New course! Every coder should learn Generative AI!
Try a free lesson+ 4
Can you please explain the output of this code?
x = 0 for i in range (-4, 4): if i: x += i print(x) Answer is -4
8 Answers
+ 4
for i in range(-4, 4) :
i will iterate through all integer values from range [-4... 4), 4 is not included.
if i:
will be true for any i except 0
So, you sum numbers -4, -3, -2, -1, 1, 2, 3
-4 + -3 + -2 + -1 + 1 + 2 + 3 = -4
+ 4
-4 + -3 + -2 + -1 + 1 + 2 + 3 = -4
For - 4 to 3 values are added to x. If condition is true for any value otherthan zero.
+ 1
What do you mean the answer is -4? Isn't the answer consist of all sum of x+i from range of -4 to 4? So the printed answer is -4, -7, -9, -10, -10, -9, -7, -4, right?
+ 1
Anrico Gideon,
No, print(x) is not executed on each iteration of the forl-oop.
As you can see print(x) is not indented, so it will be called after for-loop have been ended and it will output the total sum of all numbers
+ 1
Andriy kan,
Oh that's right, thanks. May i ask again? I'm sorry if this question sounds stupid but how is the output is the total sum of all numbers besides 0? Doesn't it just take the last value of x from the number on my comment before this which is -4? I mean x += i just adds 0 to i and then saves it as a new value of x and then it goes to the next range right?
+ 1
Anrico Gideon,
when "i" equals 0 statement
x += i
is not executed because it is a body of conditional statement "if i:" (pay attention to identation).
if statement checks the given condition and if it is evaluated to true then its body is executed
In the given code condition of if statement is variable "i".
variable i have integer value. All numbers except zero are evaluated to true.
zero is evaluated to false.
So x += i will be executed when i is evaluted to true or in other words when i is not equal to zero.
+ 1
Thanks Andriy Kan
0
The answer is 6