Can you please explain the output of this code? | Sololearn: Learn to code for FREE!
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

16th Mar 2020, 10:28 AM
APC (Inactive for a while)
APC (Inactive for a while) - avatar
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
16th Mar 2020, 10:50 AM
andriy kan
andriy kan - avatar
+ 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.
16th Mar 2020, 10:48 AM
Jayakrishna 🇮🇳
+ 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?
17th Mar 2020, 7:37 AM
Anrico Gideon
Anrico Gideon - avatar
+ 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
17th Mar 2020, 7:49 AM
andriy kan
andriy kan - avatar
+ 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?
17th Mar 2020, 8:22 AM
Anrico Gideon
Anrico Gideon - avatar
+ 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.
17th Mar 2020, 9:04 AM
andriy kan
andriy kan - avatar
+ 1
Thanks Andriy Kan
17th Mar 2020, 11:15 AM
Anrico Gideon
Anrico Gideon - avatar
0
The answer is 6
12th May 2021, 10:58 PM
Obodai Niisai David
Obodai Niisai David - avatar