Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Understanding the code
#1
Hi, I am new here. Can someone please help me understand this code? I know the output is 6 but I don't understand what res and i are.
def func(x):
    res=0
    for i in range(x):
        res+=1
    return res
print(fund(4))
Reply
#2
Hello and welcome to Python and the forums!
Next time please use Python code tags, this time I have added them for you.
Have you ran the code you posted? The result I get is 4, and looking at the code, it seems right.
i is a variable that is assigned a value from range(x) in each iteration. range(4) will give you 0, 1, 2 and 3. See more on range in Python docs.
Res is a variable, which has an initial value of 0, but in each iteration of for loop, it gets incremented by 1. res += 1 is just shorthand for res = res + 1.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Code understanding: Need help in understanding dictionary code jt123 0 476 Jul-09-2023, 01:13 PM
Last Post: jt123
  New to python/coding Need help on Understanding why this code isn't working. Thanks! mat3372 8 1,759 May-09-2023, 08:47 AM
Last Post: buran
  Understanding a piece of code Michael1 4 1,420 Jan-20-2022, 07:14 PM
Last Post: Michael1
  Beginner: I need help understanding few lines of a code. hop_090 1 1,697 Sep-07-2020, 04:02 PM
Last Post: Larz60+
  Extracting Rows From Data Frame and Understanding The Code JoeDainton123 0 1,445 Aug-03-2020, 04:08 PM
Last Post: JoeDainton123
  Help Understanding Code Variables 1 1,917 May-02-2019, 05:53 PM
Last Post: micseydel
  Need help understanding simple Array code. Please. stluwa 1 2,218 Apr-13-2019, 07:16 PM
Last Post: loomski
  Trouble Understanding Why This Code Works crocolicious 2 2,714 Apr-09-2019, 05:24 PM
Last Post: crocolicious
  Help Understanding Portion of Code caroline_d_124 3 2,722 Jan-15-2019, 12:12 AM
Last Post: caroline_d_124
  Understanding GerbMerge code djsb 1 2,397 Oct-27-2018, 02:04 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

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