user11475647
user11475647

Reputation:

I am having a problem with understanding this python code

I want to learn Python and I took a test. I the test I came across this code and I needed to get it's output.

I put the correct answer which was 6, but I didn't understand the code, I just put it in an online python compiler!

Why does this code output a 6?

def func(x):
    res = 0
    for i in range(x):
        res += i
    return res

print(func(4))

Upvotes: 1

Views: 501

Answers (3)

Alok Mishra
Alok Mishra

Reputation: 704

You assign the value of i to the res and then res value is added to the value of i and your output is assign to the value of res that is when x=3, res become 3 and added with the value 3 is equal to 6 boom

def is used to define function and range means from start to the end point you want so in your case you passed 4 as variable x into your function that means your loop start with the value of 0 and end when value is 4.

Upvotes: 1

Mr.Riply
Mr.Riply

Reputation: 845

you're passing number 4 as variable x into the function and printing the result in the end.

in the for loop, i is a temporary variable representing each number in range 0 to 4.

so the steps in the code look like this

for 0 in range 0 to 4

add 0 to variable res = 0 + 0 = 0

now res = 0

next step/loop for 1 in range 0 to 4

add 1 to variable res = 0 + 1 = 1

now res = 1

next step/loop for 2 in range 0 to 4

add 2 to variable res = 1 + 2 = 3

now res = 3

next step/loop for 3 in range 0 to 4

add 3 to variable res = 3 + 3 = 6

now res = 6

and the loop is done, giving you the result 6

Upvotes: 1

user11471261
user11471261

Reputation:

I thing this will solve your problem buddy

def func(x):
    res = 0

    for i in range(x):
        print "x",i
        print "res",res
        res += i
        print "res out", res
    return res
print(func(4))

result:

x 0
res 0
res out 0
x 1
res 0
res out 1
x 2
res 1
res out 3
x 3
res 3
res out 6
6

Upvotes: 3

Related Questions