Python Forum

Full Version: beginner question
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hi guys can you please help me understand the difference bteween these 2 codes?
my interpretation is def function has a loop in it (im not smart)

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

print(func(5))
output is 10

and

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

print(func(5))
output is 4
thanks for helping me
In the first snippet you make res==0 before the loop and then only add i in every iteration of the loop. So at the end it's the sum of all values in range(x)
In the second example you make res==0 in every iteration. So at the end res value is equal to the last value of i.

You can use http://www.pythontutor.com/visualize.html#mode=edit to visualise the execution of the code step by step for better understanding
(Jan-15-2019, 07:41 AM)buran Wrote: [ -> ]In the first snippet you make res==0 before the loop and then only add i in every iteration of the loop. So at the end it's the sum of all values in range(x)
In the second example you make res==0 in every iteration. So at the end res value is equal to the last value of i.

You can use http://www.pythontutor.com/visualize.html#mode=edit to visualise the execution of the code step by step for better understanding

thank you it's much clear now