Bottom Page

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
You like this post
Quote
#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
You like this post
Quote
#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
You like this post
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Basic Beginner question NHeav 4 158 Sep-13-2019, 11:43 AM
Last Post: NHeav
  Beginner Question - Esaping the Escape Character correctly? Bramen 4 249 Aug-27-2019, 02:38 PM
Last Post: Bramen
  question by a beginner salahoum 11 773 Jan-28-2019, 12:02 PM
Last Post: perfringo
  "if" beginner question Naito 13 1,076 Jan-13-2019, 02:15 PM
Last Post: perfringo
  Absolute Beginner Python Question matchamochi7 5 702 Nov-02-2018, 12:09 PM
Last Post: wookie
  Beginner Loop question BigDisAok 5 812 Jul-24-2018, 02:04 PM
Last Post: BigDisAok
  Beginner question: help ensuring input is a number ycrad 2 898 Dec-23-2017, 10:49 PM
Last Post: snippsat
  Beginner question HimynameisBen 4 1,147 Nov-03-2017, 07:58 PM
Last Post: nilamo
  Total beginner question AngelForge 8 2,252 Apr-08-2017, 07:19 AM
Last Post: Low_Ki_

Forum Jump:


Users browsing this thread: 1 Guest(s)