Print the sum of the current number and the previous number in Python

Here’s an example code in Python to print the sum of the current number and the previous number:

# Define a list of numbers
numbers = [1, 2, 3, 4, 5]

# Loop through the list
for i in range(1, len(numbers)):
    # Calculate the sum of the current number and the previous number
    current_number = numbers[i]
    previous_number = numbers[i - 1]
    sum = current_number + previous_number
    
    # Print the sum
    print("The sum of", current_number, "and", previous_number, "is", sum)

In this code, we first define a list of numbers called numbers. Then we loop through the list using the range() function, starting from index 1 (the second element in the list) and ending at the length of the list.

For each element in the list, we calculate the sum of the current number and the previous number by using the current index i and the previous index i-1. We assign the current number to the variable current_number, the previous number to the variable previous_number, and the sum to the variable sum.

Finally, we print out the sum using the print() function, along with a message that describes the sum.

When you run this code, it should output:

The sum of 2 and 1 is 3
The sum of 3 and 2 is 5
The sum of 4 and 3 is 7
The sum of 5 and 4 is 9

Note that you can replace the values in the numbers list with any other sequence of numbers you want to calculate the sum of the current number and the previous number.

Related Examples

1. Python Program to Print Hello world!

2. Calculate the multiplication and sum of two numbers

3. Python Program to Find the Square Root

4. Python Program to Calculate the Area of a Triangle

5. Python Program to Solve Quadratic Equation

6. Python Program to Swap Two Variables

7. Python Program to Generate a Random Number

8. Return the count of a given substring from a string

9. Print the following pattern

10. Python Program to check if the given number is a palindrome number

11. Python Program to print multiplication table form 1 to 10

12. Print downward Half-Pyramid Pattern with Star (asterisk)

13. Python Program to Convert Kilometers to Miles

14. Python Program to Check if a Number is Positive, Negative or 0

15. Python Program to Find the Sum of Natural Numbers

Leave a Reply

Your email address will not be published. Required fields are marked *

Wordpress Social Share Plugin powered by Ultimatelysocial
Wordpress Social Share Plugin powered by Ultimatelysocial