Sum the integers from 1 to 100 in Python #
To sum the integers from 1 to 100:
- Pass
1
and100 + 1
to therange
class, e.g.range[1, 100 + 1]
. - Pass the
range
object to thesum[]
function. - The
sum
function will sum the integers from 1 to 100.
Copied!
num = 100 total = sum[range[1, num + 1]] print[total] # 👉️ 5050 # 👇️ [1, 2, 3, ... 98, 99, 100] print[list[range[1, num + 1]]] # ------------------------------------------------ # 👇️ alternatively, you can use a formula total_2 = num * [num + 1] // 2 print[total_2] # 👉️ 5050
We used the range[]
class to sum the numbers from 1 to 100.
The range class is commonly used for looping a specific number of times in for
loops and takes the following arguments:
start
| An integer representing the start of the range [defaults to 0 ]
|
stop
| Go up to, but not including the provided integer |
step
| Range will consist of every N numbers from start to stop [defaults to 1 ]
|
Notice that we added 1
to the stop
value. The stop
argument is exclusive, so we had to add 1
to include 100
in the result.
If you only pass a single argument to the range[]
constructor, it is considered to be the value for the stop
parameter.
Copied!
num = 100 total = sum[range[num + 1]] print[total] # 👉️ 5050 # 👇️ [1, 2, 3, ... 98, 99, 100] print[list[range[num + 1]]]
The example shows that if the start
argument is omitted, it defaults to 0
and if the step
argument is omitted, it
defaults to 1
.
Since the start
argument of the range is 0
, you can omit it and you'd get the same result.
If values for the start
and stop
parameters are provided, the start
value is inclusive, whereas the stop
value is exclusive.
The sum
function can be used to calculate the sum of the numbers in the range.
The sum function takes an iterable, sums its items from left to right and returns the total.
Copied!
num = 100 total = sum[range[1, num + 1]] print[total] # 👉️ 5050
The sum
function takes the following 2 arguments:
iterable | the iterable whose items to sum |
start | sums the start value and the items of the iterable. sum defaults to 0 [optional]
|
If you need to get a range with a step, pass a value for the third argument of the range[]
class.
Copied!
start = 1 stop = 100 step = 3 total_2 = sum[range[start, stop + 1, step]] print[total_2] # 👉️ 1717 # 👇️ [1, 4, 7, 10, ... 94, 97, 100] print[list[range[start, stop + 1, step]]]
When the step
argument is provided, the range will consist of every N numbers from start
to stop
.
The value for the step
argument defaults to 1
.
You can also sum the numbers from 1 to 100 using a formula.
Copied!
num = 100 total_2 = num * [num + 1] // 2 print[total_2] # 👉️ 5050
We multiply 100 by 100 + 1
and floor-divide the result by 2
to get the sum of
the integers from 1 to 100.
Division /
of integers yields a float, while floor division //
of integers result in an integer.
The result of using the floor division operator is that of a mathematical division with the floor[]
function applied to the result.