PRO
Ymlsurgeon
asked

Expert
Abhay Jajodia answered
Great question. This trips a lot of people up when they first start using Python.
The key thing to remember is that range() stops one number before the value you put in as the second argument. So if you write:
range(1, n)
Python will count like this:
1, 2, 3, ..., n-1
It never reaches n, which is why your loop feels like it’s stopping too early.
If you actually want to include n in the loop, just add 1 to the stop value:
for i in range(1, n + 1):
total_sum += i
Now Python will count:
1, 2, 3, ..., n
and you get the full sum you expected.
If anything still feels confusing, I’m happy to walk through another example with you.
Python
This question was asked as part of the Practice: Python Basics course.
Our Experts
Sudip BhandariHead of Growth/Marketing
Apekchhya ShresthaSenior Product Manager
Kelish RaiTechnical Content Writer
Abhilekh GautamSystem Engineer
Palistha SinghTechnical Content Writer
Sarthak BaralSenior Content Editor
Saujanya Poudel
Abhay Jajodia
Nisha SharmaTechnical Content Writer
Udayan ShakyaTechnical Content Writer
