Learning Python using automated test

Initial steps to learn Python using automated test

#automated-test, #python
I tried to learn Python briefly, if the code can be improved please leave a comment 😂.

So… I was watching the classes of Python for Zumbies (Brazilian Portuguese course) and I came across some code to do. There are some ways to see my code working:

  • Try by myself;
  • Ask for someone else to try to use it, and the best of all;
  • Writing automated test code 🙌;

So the best way to learn was writing automated test code;

Fibonacci number

First, of course, I am going to create the test.

After looking up for information I found out this to fib_test.py:

import unittest
from fib import fib

class FibTestCase(unittest.TestCase):
  def test_fib1(self):
    self.assertEqual(fib(1), 1)

  def test_fib0(self):
    self.assertEqual(fib(0), 0)

  def test_fib6(self):
    self.assertEqual(fib(6), 8)

  def test_fib6_again(self):
    self.assertTrue(fib(6) == 8)


If you call it you receive this error:

$ python fib_test.py
Traceback (most recent call last):
  File "fib_test.py", line 2, in <module>
    from fib import fib
ImportError: No module named 'fib'

So far so good, I did not write the code, let’s create it, file fib.py:

def fib(n):
  if n < 2:

  a = fib(n-1)
  b = fib(n-2)


If we call it we have:

$ python fib_test.py
Ran 4 tests in 0.000s


Object Orientation

While learning about object orientation I got the following example.

First the test:

import unittest
from television import Television

class TelevisionTestCase(unittest.TestCase):
  def setUp(self):
    self.tv = Television('Room')

  def test_a_new_tv_is_off(self):

  def test_i_can_change_the_status(self):
    self.tv.on = True

  def test_i_can_change_the_channel(self):
    selft.assertEqual(self.tv.channel, 2)


Now the class:

class Television:
  def __init__(self, local):
    self.on = False
    self.channel = 1
    self.local = local

This example of Television I used TDD, aka, red/green/refactor.

There is a method missing in Television, if you are studying python take it as an exercise 😉.

Posts in this series