.py file is a Python module.
A module serves as a collection of variables and functions that can be used by other modules.
Modules that are executed directly are also called scripts.
%%file math_stuff.py def add_three_numbers(a, b, c): return a + b + c def multiply_three_numbers(a, b, c): return a * b * c def average_three_numbers(a, b, c): return a + b + c / 3
%%file demo.py from math_stuff import add_three_numbers, multiply_three_numbers a = 7 b = 2 c = 3 print(add_three_numbers(a, b, c)) print(multiply_three_numbers(a, b, c))
%%file another_demo.py import math_stuff a = 3 b = 6 c = 8 print(math_stuff.add_three_numbers(a, b, c)) print(math_stuff.multiply_three_numbers(a, b, c))
! python demo.py
! python another_demo.py
another_demo.py use the functions defined in
Often, modules that provide functions that are intended to be used by other scripts are called libraries.
PyTest is a library we can use to test our code.
%%file test_math_stuff.py from math_stuff import add_three_numbers, multiply_three_numbers, average_three_numbers def test_add_three_numbers(): result = add_three_numbers(2, 3, 4) assert result == 9 result = add_three_numbers(-1, 0, 2) assert result == 1 def test_multiply_three_numbers(): result = multiply_three_numbers(2, 3, 4) assert result == 24 result = multiply_three_numbers(1, 0, 2) assert result == 0 def test_multiply_three_numbers_with_negatives(): assert multiply_three_numbers(-1, -2, -3) == -6 def test_average_three_numbers(): assert average_three_numbers(1, 2, 3) == 2
When writing tests:
math_stuff.pywould be in a file named
add_three_numberswould be tested by a function named
assertto test whether something you have tested matches your expectations
Our business-critical Python script isn't working correctly:
Write tests for the functions found in
and fix the problem!
important_business.py. It fails. We need better test coverage!
only_evenshas a bug.
0(should be treated as even)
%%file list_tools.py def only_evens(items): """Return a list containing only the even elements of the input list""" result =  for item in items: if item % 2 != 0: result.append(item) return result def twice_as_long(items): """Return a list that is twice as long as the input: A, B, C => A, B, C, A, B, C""" result =  for item in items: result.append(item) for item in items: result.append(item) return result def sum_all(numbers): """Sum all the numbers in a list""" result = 0 for item in numbers: result = result + item return result
%%file important_business.py from list_tools import only_evens, twice_as_long, sum_all numbers = [2, 0, 1, 3, 8, 4] numbers = only_evens(numbers) numbers = twice_as_long(numbers) result = sum_all(numbers) if result == 28: print("Success! 😊") else: print("Fail. ☠️")