Here is one way to add the numbers from 1 to 100 in Python and display the sum:
1 2 3 4 5 6 7 8 | sum = 0 for i in range(1, 101): sum += i print(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:
1 2 3 | 5050 |
Here is an alternative way to add the numbers from 1 to 100 and display the sum in Python:
1 2 3 4 | sum = sum(range(1, 101)) print(sum) |
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:
1 2 3 | 5050 |
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:
1 2 3 4 | sum = reduce(lambda x, y: x + y, range(1, 101)) print(sum) |
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:
1 2 3 | 5050 |
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.