Python @ DjangoSpin

PyPro #2 Sum of first n integers

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Sum of first n integers in Python

Sum of first n integers in Python

Given the value of an integer n, how to calculate the sum of first n integers using Python.

##
## Calculate the sum of first n integers
 
# Get input from user
n = int(input("Enter the value of n: "))
 
# Calculating the sum upto the provided number
summation = ( n * (n + 1) ) / 2
 
# Outputting the value on to the screen
print("Sum of first", str(n), "integers is:", int(summation))
 
## INPUT: 5 OUTPUT: 15
## summation variable becomes a float when there is a dividing operation in the expression. That is why, we cast the value of summation to an int in the print statement.
##
Try it online here.

See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply