Python workshop
Problem 1:
- Definition: I need a list a leap years given the start and end year according to gregorian calender
- additional notes
2000: yes
2100: no
1996: yes
Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100, but these centurial years are leap years if they are exactly divisible by 400. For example, the years 1700, 1800, and 1900 are not leap years, but the years 1600 and 2000
def leap_years(start, end):
"""
This function returns a list of leap years
Arguments:
start (int): start year
end (int): end year
Returns:
a list of leap years
Usage:
leap_years(1998,2010) => [2000,2004,2008]
leap_years(2098, 2110) => [2104, 2108]
"""
pass
- topics
- use clear functions
- use filters
- optional: can use generator instead of returning list
- solution: Refer Here
Setup folder for unit testing
- Create a folder a workshop
mkdir workshop
- create a virtual environment
python -m venv .venv
- Activate your virtual environment
.venv/scripts/activate
- Now create a folder called as workshop and tests
workshop
|
--> workshop
|
--> tests
- create a file called as
pytest.ini
workshop
|
--> workshop
|
--> tests
pytest.ini
- create
__init__.py
files in workshop and tests folder
workshop
|
--> workshop
|
__init__.py
|
--> tests
|
__init__.py
pytest.ini
pip install pytest
pip install pytest-cov
pip install coverage
- Now lets add a module in workshop folder called as calculator.py with a simple add function
"""This module will have calculator functions
"""
def add(x,y):
"""This function performs addition
"""
return x + y
- Now add a test function test_calculator in tests folder with following
from workshop.calculator import add
def test_add():
"""
This function tests the add function
"""
assert add(1,2) == 3
- Now execute
pytest
and coverage run -m pytest
Like this:
Like Loading...