Python Forum
Thread Rating:
  • 4 Vote(s) - 2.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
beginner question
#1
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
Reply
#2
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
(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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Very Beginner question on simple variables Harvy 1 162 Apr-12-2024, 12:03 AM
Last Post: deanhystad
  A simple "If...Else" question from a beginner Serena2022 6 1,695 Jul-11-2022, 05:59 AM
Last Post: Serena2022
Question Beginner Boolean question [Guessing game] TKB 4 2,291 Mar-22-2022, 05:34 PM
Last Post: deanhystad
  Beginner question NameError amazing_python 6 2,437 Aug-13-2021, 07:28 AM
Last Post: amazing_python
  Beginner question - storing values cybertron2 4 3,185 Mar-09-2021, 04:21 AM
Last Post: deanhystad
  beginner question about lists and functions sudonym3 5 2,712 Oct-17-2020, 12:31 AM
Last Post: perfringo
  beginner question ___ 1 1,729 Jul-12-2020, 08:12 AM
Last Post: Gribouillis
  Beginner question: lxml's findall in an xml namespace aecklers 0 2,902 Jan-22-2020, 10:53 AM
Last Post: aecklers
  Super easy beginner question AkulaLA 3 3,245 Nov-07-2019, 03:42 AM
Last Post: Larz60+
  Basic Beginner question NHeav 4 2,750 Sep-13-2019, 11:43 AM
Last Post: NHeav

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020