Write a Python program to find the sum of all numbers between 1 and a given number:-
n=int(input('Enter the number : '))
sum=0
for i in range(1,n+1):
sum=sum+i
print(sum)
Output :
Enter the number : 10
55
Here's a line-by-line explanation of what the code does:
n=int(input('Enter the number: ')):
This line prompts the user to enter a number and stores it in the variablen
. Theint()
function is used to convert the user input, which is a string, to an integer.sum=0
: This line initializes the variablesum
to 0. This variable will be used to store the sum of all integers from 1 ton
.for i in range(1,n+1):
: This line starts a for loop that iterates over all integers from 1 up to and includingn
. Therange()
function generates a sequence of integers from 1 ton
, and the loop variablei
take on each value in this sequence in turn.sum=sum+i
: This line adds the current value ofi
to the running total stored in the variablesum
.print(sum)
: This line prints the final value ofsum
, which is the sum of all integers from 1 ton
.
Overall, this code calculates the sum of all integers from 1 to n
using a simple loop and variable manipulation.
If you are a beginner and want to know more about python programming, you can read my basics of python blogs (From part 1 to part 15).
Happy Learning !!!