Click here to Skip to main content
15,881,813 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Python
<pre># Program to illustrate a loop with condition at the top

# Try different numbers
n = 10

# Uncomment to get user input
#n = int(input("Enter n: "))

# initialize sum and counter
sum = 0 
i = 1 

while i <= n:
   sum = sum + i
   i = i+1    # update counter

# print the sum
print("The sum is",sum)


What I have tried:

I did not understand this,it is not clicking with me.
Posted
Updated 30-Apr-18 7:27am
Comments
Rajesh Anuhya 30-Apr-18 10:09am    
What do you think? Result should be 555 ????..
Rajesh Anuhya 30-Apr-18 10:09am    
It's Correct only ..
Richard Deeming 30-Apr-18 10:43am    
Simple maths: the sum of the integers from 1 to n is n × (n + 1) ÷ 2

Quote:
Why the output is "the sum is 55"?

Want to watch this code building the answer by yourself ?

Run your code on debugger step by step, and inspect variables.

The debugger is here to show you what your code is doing .
There is no magic in the debugger, it don't know what your is supposed to do, it don't find bugs.

To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.
Debugger - Wikipedia, the free encyclopedia[^]
27.3. pdb — The Python Debugger — Python 3.6.1 documentation[^]
Debugging in Python | Python Conquers The Universe[^]
pdb – Interactive Debugger - Python Module of the Week[^]
The debugger is here to only show you what your code is doing and your task is to compare with what it should do.
 
Share this answer
 
Because that is what you told it to do!
Look at the values at the end each time you go round the loop:
 i Sum
 2   1
 3   3
 4   6
 5  10
 6  15
 7  21
 8  28
 9  36
10  45
11  55
The sum is 55
 
Share this answer
 
Comments
Member 13798091 30-Apr-18 10:20am    
yeah, i got it thank you very much.
that was what i really needed.
OriginalGriff 30-Apr-18 10:27am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900