Write a Python program to add n numbers accepted from the user

Introduction

Python is a general-purpose programming language that is easy to learn and use. It is used in a variety of applications, including web development, data science, and machine learning.

One of the most basic tasks that you can perform with Python is to add numbers. This can be done using the + operator. For example, to add the numbers 1 and 2, you would write:

Python
sum = 1 + 2

This would assign the value 3 to the variable sum.

You can also add multiple numbers together using a for loop. For example, to add the numbers 1 to 10, you would write:

Python
sum = 0
for i in range(1, 11):
    sum += i

print(sum)

This would print the number 55 to the console.

Adding n numbers accepted from the user

To add n numbers accepted from the user, you can use the following Python program:

Python
def add_n_numbers(n):
    sum = 0
    for i in range(n):
        number = int(input("Enter number {}: ".format(i + 1)))
        sum += number

    return sum


if __name__ == "__main__":
    n = int(input("Enter the number of numbers to add: "))
    sum = add_n_numbers(n)

    print("The sum of the numbers is {}".format(sum))

This program first prompts the user to enter the number of numbers to add. It then uses a for loop to iterate over the numbers and add them to the variable sum. Finally, it prints the sum of the numbers to the console.

Example

Here is an example of how to use the program:

Enter the number of numbers to add: 5

Enter number 1: 1
Enter number 2: 2
Enter number 3: 3
Enter number 4: 4
Enter number 5: 5

The sum of the numbers is 15

Variations

There are a few variations of the program that you can write. For example, you could modify the program to allow the user to add numbers of different types, such as integers, floats, and strings. You could also modify the program to print the sum of the numbers to a file instead of to the console.

Challenge

Write a Python program to add n numbers accepted from the user and then print the average of the numbers.

Post a Comment

0 Comments