Adding n Numbers in Python

Adding N numbers might seem basic, but it’s a crucial concept that lays the foundation for more complex programming tasks. Whether you’re summing a list of expenses or calculating total scores, this technique is widely applicable. So, let’s jump right into it!

Code for adding n Numbers

First, let’s start by writing a Python script that adds N numbers. We’ll use a list to store the numbers and then sum them up using a loop and Python’s built-in functions. Here’s the step-by-step process.

let’s create a new Python file named as add_numbers.py.

# add_numbers.py

# Function to add N numbers
def add_numbers(numbers):
    total = 0
    for number in numbers:
        total += number
    return total

# Main function
if __name__ == "__main__":
    # Example list of numbers
    numbers = [1, 2, 3, 4, 5]
    
    # Adding the numbers
    result = add_numbers(numbers)
    
    # Displaying the result
    print(f"The sum of {numbers} is {result}")

We define a function called add_numbers that takes a list of numbers as input. Inside this function, we initialize a variable total to zero.Then, we use a for loop to iterate through each number in the list, adding it to total.In the __main__ section of our script, we create an example list of numbers and call our add_numbers function with this list. Finally, we print out the result.

Output

 

$ python add_numbers.py
The sum of [1, 2, 3, 4, 5] is 15

 

 

Leave a Comment

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

Scroll to Top