Now we are going to discuss how to find the sum of all the numbers between two given numbers using a while loop in python.
This program finds the sum of all the numbers between two given numbers using a while loop.
Simple code:
start = int(input("Enter the start number: "))
end = int(input("Enter the end number: "))
sum = 0
while(start <= end):
sum += start
start += 1
print("The sum of numbers between Start and End is", sum)
Output:
Enter the start number: 0
Enter the end number: 5
The sum of numbers between Start and End is 15
Code with explanation:
# Ask the user to enter the two numbers
start = int(input("Enter the start number: "))
end = int(input("Enter the end number: "))
# Initialize a variable to store the sum of the numbers
sum = 0
# Use a while loop to iterate through all the numbers between start and end (inclusive)
while(start <= end):
# Add the current number to the sum
sum += start
# Move to the next number
start += 1
# Print the sum of the numbers
print("The sum of numbers between Start and End is", sum)
Explanation:
- The program prompts the user to enter two numbers using the input() function and stores them in variables called ‘start’ and ‘end’, respectively.
- A variable ‘sum’ is initialized to 0, which will be used to store the sum of all the numbers between the start and end.
- A while loop is used to iterate through all the numbers between the start and end (inclusive). At each iteration, the current number is added to the sum variable and the loop continues to the next number.
- Finally, the program prints the sum of the numbers using the print() function.
Discover more from Python Mania
Subscribe to get the latest posts sent to your email.