Adding Consecutive integers in Python

>>> x = input("Please input an integer: ")
Please input an integer: 5
>>> x = int(x)
>>>
>>> for i in range(1, x+1):
...     nums = range(1, i+1)
...     print(' + '.join(map(str, nums)), '=', sum(nums))
...
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
range(1, x+1) would give me [1, 2, 3, 4, 5], this acts as the controller for how many times we want to print out a sum. So, this for loop will happen 5 times for your example.
nums = range(1, i+1) notice we are using i instead here, (taken from the range above), which I am using to define which number I am up to in the sequence.
' + '.join(map(str, nums)):
  • map(str, nums) is used to convert all elements of nums into strings using str, since the joinmethod expects an iterable filled with strings.
  • ' + '.join is used to "join" elements together with a common string, in this case, ' + '. In cases where there is only 1 element, join will just return that element.
sum(nums) is giving you the sum of all numbers defined in range(1, i+1):
  • When nums = range(1, 2)sum(nums) = 1
  • When nums = range(1, 3)sum(nums) = 3
  • Etc...

No comments:

Post a Comment