Python Exercises For Beginners – #1 – Sum all integers from Zero to N

Create a Python function that sums all the numbers from 0 to a number N. If a non-positive or a non-integer number is provided, the function should return 0.

This Google Colab notebook is part of my “Python Problemns for Beginners” Youtube series: https://youtube.com/playlist?list=PL3OV2Akk7XpC-fsHuJ3RLpnzOXmED7oAI

In this video, the first in the series, I show you how to solve a simple Python problem using three different solutions, and while making sure we write unit tests. A good habit to learn and develop from early on.
This is our warm-up exercise, more to come!

Python Solution 1 – Using Recursion

def sum_all_up(number:int) -> int:
  if number > 0:
    return number + sum_all_up(number - 1) 
  else:
    return 0

Python Solution 2 – Using sum() and range() function in Python

def sum_all_up(number:int) -> int:
  return sum(range(number + 1))

Python Solution 3 – Using numpy.arange(..).sum()

import numpy

def sum_all_up(number: int) -> int:
  return numpy.arange(number + 1).sum()

Python Unit tests using Python unittest library

import unittest

class TestStringMethods(unittest.TestCase):

  def test_sum_all_up_of_zero_returns_zero(self):
    self.assertEqual(0, sum_all_up(0))

  def test_sum_all_up_of_one_returns_one(self):
    self.assertEqual(1, sum_all_up(1))

  def test_sum_all_up_of_two_returns_three(self):
    self.assertEqual(3, sum_all_up(2))

  def test_sum_all_up_of_three_returns_six(self):
    self.assertEqual(6, sum_all_up(3))

  def test_sum_all_up_of_four_returns_ten(self):
    self.assertEqual(10, sum_all_up(4))

  def test_sum_all_up_of_negative_number_returns_0(self):
    self.assertEqual(0, sum_all_up(-10))
if __name__ == '__main__':
   unittest.main(argv=['first-arg-is-ignored'], exit=False)
......
----------------------------------------------------------------------
Ran 6 tests in 0.013s

OK


Resources

Google Colab Notebook

https://colab.research.google.com/github/armindocachada/python-for-beginners-exercises/blob/main/Sum_It_all_Up_Python_Video_Problem_1.ipynb

Python Problems for Beginners – Playlist

Python for Complete Beginners


Posted

in

,

by