Are you looking to add numbers in Python Using For Loop? In this article, I will let you know how you can add numbers quickly using For Loop in Python.
Below is the Algorithm to Add the numbers Using For Loop. Once you read through this I will be writing the actual code based on the below algorithm.
inputNumber = input("Enter the Number To get Sum from 1 to Input Number.")
totalSum = 0
for num in range(0, inputNumber + 1):
totalSum = totalSum + inputNumber
print("Total Sum from 1 to Input Number: ", inputNumber , "is: ", sum )
Python Code to Add Numbers in Python Using For Loop
As you have already seen the above algorithm, all you are required is to use the range method to start the loop from 1 to the given input value and then add those to the totalSum
variable.
#Receiving the Input Number and Casting it in Integer inputNumber = int(input("Enter the Number To get Sum from 1 to Input Number.\n")) #Initializing the Total Sum variable as 0 totalSum = 0 #Using the For loop to sum till inputNumber for number in range(1, inputNumber+1): totalSum = totalSum + number #Printing the Total Sum print("Total Sum from 1 to Input Number: {} is {}".format(inputNumber, totalSum))
Output:
Enter the Number To get Sum from 1 to Input Number.
10
Total Sum from 1 to Input Number: 10 is 55
Since the input method takes any input from the user in the string, hence you need to cast that input to integer in order to get the for loop running.
Alternative Method To Add Sum of Numbers in Python
You can use a while loop as well to add the sum from the range of 1 to the given input number. While the loop is also similar to for[1] loop but you need to make sure the loop ends when you have covered each number in the given range.
Let us see in the below example code to get the sum ranges in python using while loop.
#Receiving the Input Number and Casting it in Integer inputNumber = int(input("Enter the Number To get Sum from 1 to Input Number.\n")) #Initializing the Total Sum variable as 0 totalSum = 0 #Using the While loop to sum till inputNumber while inputNumber>0: totalSum = totalSum + inputNumber inputNumber = inputNumber - 1 #Printing the Total Sum print("Total Sum from 1 to Input Number is: {}".format(totalSum))
Output:
Enter the Number To get Sum from 1 to Input Number.
20
Total Sum from 1 to Input Number is: 210
Wrap Up
I hope you were able to get a quick answer to your question related to how to add numbers in Python using For Loop. I also showed you the alternative method that you can use to get the sum of the ranges using the while loop.
If you have any other method quicker than the above method then let us know in the comments section. I will add it here.
If you liked the above tutorial then please follow us on Facebook and Twitter. Let us know the questions and answer you want to cover in this blog.
Further Read: