![]() |
beginner question - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: beginner question (/thread-15371.html) |
beginner question - Naito - Jan-15-2019 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 RE: beginner question - buran - Jan-15-2019 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 RE: beginner question - Naito - Jan-15-2019 (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) thank you it's much clear now |