Python

How to add the numbers from 1 to 100 in Python1 min read

Here is one way to add the numbers from 1 to 100 in Python and display the sum:

This code uses a for loop to iterate through the range 1 to 100. On each iteration, the value of i is added to the sum variable. After the loop finishes executing, the final value of sum is printed to the console.





Here is the output of this code:

Here is an alternative way to add the numbers from 1 to 100 and display the sum in Python:

This code uses the built-in sum function to add the numbers in the range 1 to 100. The result is then printed to the console.

Here is the output of this code:

Note that this method is shorter and simpler, but it may be slightly less efficient than the for loop method, since it involves creating a new list object (the range) and then iterating over it to compute the sum.


Here is another alternative way to add the numbers from 1 to 100 and display the sum in Python:

This code uses the reduce function from the functools module and a lambda function to add the numbers in the range 1 to 100. The result is then printed to the console.

Here is the output of this code:

This method is similar to the sum function method in terms of simplicity and readability, but it may be slightly less efficient, since it involves creating a lambda function and calling reduce on it.

Note that you will need to import the functools module at the top of your file in order to use the reduce function.

Leave a Comment