5/20/2020

Python - Unit Testing Your Code with the unittest Module

** Unit Testing Your Code with the unittest Module


==========================================

def add(x, y):
    """Add Function"""
    return x + y


def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
    return x * y


def divide(x, y):
    """Divide Function"""
    if y == 0:
        raise ValueError('Can not divide by zero!')
    return x / y


print(add(10,5))

---------------------------------

15

---------------------------------

==========================================

import unittest
import calc


class TestCalc(unittest.TestCase):

    def test_add(self):
        result = calc.add(10, 5)
        self.assertEqual(result, 15)

-----------calc.py-----------------

def add(x, y):
    """Add Function"""
    return x + y


def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
    return x * y


def divide(x, y):
    """Divide Function"""
    if y == 0:
        raise ValueError('Can not divide by zero!')
    return x / y

---------------------------------

C:\Users\purunet\Documents\py6>python -m unittest test_calc.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

---------------------------------

==========================================

import unittest
import calc


class TestCalc(unittest.TestCase):

    def test_add(self):
        result = calc.add(10, 5)
        self.assertEqual(result, 15)


if __name__ == '__main__':
    unittest.main()

-----------calc.py-----------------

def add(x, y):
    """Add Function"""
    return x + y


def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
    return x * y


def divide(x, y):
    """Divide Function"""
    if y == 0:
        raise ValueError('Can not divide by zero!')
    return x / y

---------------------------------

C:\Users\purunet\Documents\py6>python -m unittest test_calc.py
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK

---------------------------------

==========================================

import unittest
import calc


class TestCalc(unittest.TestCase):

    def add_test(self):
        result = calc.add(10, 5)
        self.assertEqual(result, 15)


if __name__ == '__main__':
    unittest.main()

---------------------------------


----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK

---------------------------------
==========================================

import unittest
import calc


class TestCalc(unittest.TestCase):

    def test_add(self):
        result = calc.add(10, 5)
        self.assertEqual(result, 15)


if __name__ == '__main__':
    unittest.main()

---------------------------------

.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

---------------------------------

==========================================

import unittest
import calc


class TestCalc(unittest.TestCase):

    def test_add(self):
        result = calc.add(10, 5)
        self.assertEqual(result, 14)


if __name__ == '__main__':
    unittest.main()

---------------------------------

F
======================================================================
FAIL: test_add (__main__.TestCalc)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\purunet\Documents\py6\test_calc.py", line 9, in test_add
    self.assertEqual(result, 14)
AssertionError: 15 != 14

----------------------------------------------------------------------
Ran 1 test in 0.013s

FAILED (failures=1)
[Finished in 0.5s with exit code 1]

---------------------------------

==========================================

import unittest
import calc


class TestCalc(unittest.TestCase):

    def test_add(self):
        self.assertEqual(calc.add(10, 5), 15)
        self.assertEqual(calc.add(-1, 1), 0)
        self.assertEqual(calc.add(-1, -1), -2)


if __name__ == '__main__':
    unittest.main()


---------------------------------

.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

---------------------------------

==========================================

import unittest
import calc


class TestCalc(unittest.TestCase):

    def test_add(self):
        self.assertEqual(calc.add(10, 5), 15)
        self.assertEqual(calc.add(-1, 1), 0)
        self.assertEqual(calc.add(-1, -1), -2)

    def test_subtract(self):
        self.assertEqual(calc.subtract(10, 5), 5)
        self.assertEqual(calc.subtract(-1, 1), -2)
        self.assertEqual(calc.subtract(-1, -1), 0)

    def test_multiply(self):
        self.assertEqual(calc.multiply(10, 5), 50)
        self.assertEqual(calc.multiply(-1, 1), -1)
        self.assertEqual(calc.multiply(-1, -1), 1)

    def test_divide(self):
        self.assertEqual(calc.divide(10, 5), 2)
        self.assertEqual(calc.divide(-1, 1), -1)
        self.assertEqual(calc.divide(-1, -1), 1)
        self.assertEqual(calc.divide(5, 2), 2.5)


if __name__ == '__main__':
    unittest.main()

---------------------------------

....
----------------------------------------------------------------------
Ran 4 tests in 0.001s

OK

---------------------------------

==========================================

import unittest
import calc


class TestCalc(unittest.TestCase):

    def test_add(self):
        self.assertEqual(calc.add(10, 5), 15)
        self.assertEqual(calc.add(-1, 1), 0)
        self.assertEqual(calc.add(-1, -1), -2)

    def test_subtract(self):
        self.assertEqual(calc.subtract(10, 5), 5)
        self.assertEqual(calc.subtract(-1, 1), -2)
        self.assertEqual(calc.subtract(-1, -1), 0)

    def test_multiply(self):
        self.assertEqual(calc.multiply(10, 5), 50)
        self.assertEqual(calc.multiply(-1, 1), -1)
        self.assertEqual(calc.multiply(-1, -1), 1)

    def test_divide(self):
        self.assertEqual(calc.divide(10, 5), 2)
        self.assertEqual(calc.divide(-1, 1), -1)
        self.assertEqual(calc.divide(-1, -1), 1)
        self.assertEqual(calc.divide(5, 2), 2.5)


if __name__ == '__main__':
    unittest.main()

-----------calc.py-----------------

def add(x, y):
    """Add Function"""
    return x + y


def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
# error
    return x ** y                             


def divide(x, y):
    """Divide Function"""
    if y == 0:
        raise ValueError('Can not divide by zero!')
    return x / y

---------------------------------

..F.
======================================================================
FAIL: test_multiply (__main__.TestCalc)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\purunet\Documents\py6\test_calc.py", line 18, in test_multiply
    self.assertEqual(calc.multiply(10, 5), 50)
AssertionError: 100000 != 50

----------------------------------------------------------------------
Ran 4 tests in 0.002s

FAILED (failures=1)
[Finished in 0.5s with exit code 1]

---------------------------------

==========================================

import unittest
import calc


class TestCalc(unittest.TestCase):

    def test_add(self):
        self.assertEqual(calc.add(10, 5), 15)
        self.assertEqual(calc.add(-1, 1), 0)
        self.assertEqual(calc.add(-1, -1), -2)

    def test_subtract(self):
        self.assertEqual(calc.subtract(10, 5), 5)
        self.assertEqual(calc.subtract(-1, 1), -2)
        self.assertEqual(calc.subtract(-1, -1), 0)

    def test_multiply(self):
        self.assertEqual(calc.multiply(10, 5), 50)
        self.assertEqual(calc.multiply(-1, 1), -1)
        self.assertEqual(calc.multiply(-1, -1), 1)

    def test_divide(self):
        self.assertEqual(calc.divide(10, 5), 2)
        self.assertEqual(calc.divide(-1, 1), -1)
        self.assertEqual(calc.divide(-1, -1), 1)
        self.assertEqual(calc.divide(5, 2), 2.5)

        self.assertRaises(ValueError, calc.divide, 10, 0)

if __name__ == '__main__':
    unittest.main()

-----------calc.py-----------------

def add(x, y):
    """Add Function"""
    return x + y


def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
# error
    return x ** y                             


def divide(x, y):
    """Divide Function"""
    if y == 0:
        raise ValueError('Can not divide by zero!')
    return x / y

---------------------------------

....
----------------------------------------------------------------------
Ran 4 tests in 0.001s

OK

---------------------------------

==========================================

import unittest
import calc


class TestCalc(unittest.TestCase):

    def test_add(self):
        self.assertEqual(calc.add(10, 5), 15)
        self.assertEqual(calc.add(-1, 1), 0)
        self.assertEqual(calc.add(-1, -1), -2)

    def test_subtract(self):
        self.assertEqual(calc.subtract(10, 5), 5)
        self.assertEqual(calc.subtract(-1, 1), -2)
        self.assertEqual(calc.subtract(-1, -1), 0)

    def test_multiply(self):
        self.assertEqual(calc.multiply(10, 5), 50)
        self.assertEqual(calc.multiply(-1, 1), -1)
        self.assertEqual(calc.multiply(-1, -1), 1)

    def test_divide(self):
        self.assertEqual(calc.divide(10, 5), 2)
        self.assertEqual(calc.divide(-1, 1), -1)
        self.assertEqual(calc.divide(-1, -1), 1)
        self.assertEqual(calc.divide(5, 2), 2.5)

        self.assertRaises(ValueError, calc.divide, 10, 2)

if __name__ == '__main__':
    unittest.main()

-----------calc.py-----------------

def add(x, y):
    """Add Function"""
    return x + y


def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
# error
    return x ** y                             


def divide(x, y):
    """Divide Function"""
    if y == 0:
        raise ValueError('Can not divide by zero!')
    return x / y

---------------------------------

.F..
======================================================================
FAIL: test_divide (__main__.TestCalc)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\purunet\Documents\py6\test_calc.py", line 28, in test_divide
    self.assertRaises(ValueError, calc.divide, 10, 2)
AssertionError: ValueError not raised by divide

----------------------------------------------------------------------
Ran 4 tests in 0.002s

FAILED (failures=1)
[Finished in 0.4s with exit code 1]

---------------------------------

==========================================

import unittest
import calc


class TestCalc(unittest.TestCase):

    def test_add(self):
        self.assertEqual(calc.add(10, 5), 15)
        self.assertEqual(calc.add(-1, 1), 0)
        self.assertEqual(calc.add(-1, -1), -2)

    def test_subtract(self):
        self.assertEqual(calc.subtract(10, 5), 5)
        self.assertEqual(calc.subtract(-1, 1), -2)
        self.assertEqual(calc.subtract(-1, -1), 0)

    def test_multiply(self):
        self.assertEqual(calc.multiply(10, 5), 50)
        self.assertEqual(calc.multiply(-1, 1), -1)
        self.assertEqual(calc.multiply(-1, -1), 1)

    def test_divide(self):
        self.assertEqual(calc.divide(10, 5), 2)
        self.assertEqual(calc.divide(-1, 1), -1)
        self.assertEqual(calc.divide(-1, -1), 1)
        self.assertEqual(calc.divide(5, 2), 2.5)

        with self.assertRaises(ValueError):
            calc.divide(10, 0)

if __name__ == '__main__':
    unittest.main()

-----------calc.py-----------------

def add(x, y):
    """Add Function"""
    return x + y


def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
# error
    return x ** y                             


def divide(x, y):
    """Divide Function"""
    if y == 0:
        raise ValueError('Can not divide by zero!')
    return x / y

---------------------------------

....
----------------------------------------------------------------------
Ran 4 tests in 0.001s

OK

---------------------------------

==========================================

import unittest
from employee import Employee


class TestEmployee(unittest.TestCase):

 
    def test_email(self):
        emp_1 = Employee('Corey', 'Schafer', 50000)
        emp_2 = Employee('Sue', 'Smith', 60000)

        self.assertEqual(emp_1.email, 'Corey.Schafer@email.com')
        self.assertEqual(emp_2.email, 'Sue.Smith@email.com')

        emp_1.first = 'John'
        emp_2.first = 'Jane'

        self.assertEqual(emp_1.email, 'John.Schafer@email.com')
        self.assertEqual(emp_2.email, 'Jane.Smith@email.com')

    def test_fullname(self):
        emp_1 = Employee('Corey', 'Schafer', 50000)
        emp_2 = Employee('Sue', 'Smith', 60000)

        self.assertEqual(emp_1.fullname, 'Corey Schafer')
        self.assertEqual(emp_2.fullname, 'Sue Smith')

        emp_1.first = 'John'
        emp_2.first = 'Jane'

        self.assertEqual(emp_1.fullname, 'John Schafer')
        self.assertEqual(emp_2.fullname, 'Jane Smith')

    def test_apply_raise(self):
        emp_1 = Employee('Corey', 'Schafer', 50000)
        emp_2 = Employee('Sue', 'Smith', 60000)

        emp_1.apply_raise()
        emp_2.apply_raise()

        self.assertEqual(emp_1.pay, 52500)
        self.assertEqual(emp_2.pay, 63000)


if __name__ == '__main__':
    unittest.main()

-----------employee.py--------------

import requests


class Employee:
    """A sample Employee class"""

    raise_amt = 1.05

    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.pay = pay

    @property
    def email(self):
        return '{}.{}@email.com'.format(self.first, self.last)

    @property
    def fullname(self):
        return '{} {}'.format(self.first, self.last)

    def apply_raise(self):
        self.pay = int(self.pay * self.raise_amt)

    def monthly_schedule(self, month):
        response = requests.get(f'http://company.com/{self.last}/{month}')
        if response.ok:
            return response.text
        else:
            return 'Bad Response!'

---------------------------------

...
----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK

---------------------------------

==========================================

import unittest

from employee import Employee

class TestEmployee(unittest.TestCase):

   def setUp(self):
        self.emp_1 = Employee('Corey', 'Schafer', 50000)
        self.emp_2 = Employee('Sue', 'Smith', 60000)

    def tearDown(self):
        pass
       

    def test_email(self):
        self.assertEqual(self.emp_1.email, 'Corey.Schafer@email.com')
        self.assertEqual(self.emp_2.email, 'Sue.Smith@email.com')

        self.emp_1.first = 'John'
        self.emp_2.first = 'Jane'

        self.assertEqual(self.emp_1.email, 'John.Schafer@email.com')
        self.assertEqual(self.emp_2.email, 'Jane.Smith@email.com')

    def test_fullname(self):
        self.assertEqual(self.emp_1.fullname, 'Corey Schafer')
        self.assertEqual(self.emp_2.fullname, 'Sue Smith')

        self.emp_1.first = 'John'
        self.emp_2.first = 'Jane'

        self.assertEqual(self.emp_1.fullname, 'John Schafer')
        self.assertEqual(self.emp_2.fullname, 'Jane Smith')

    def test_apply_raise(self):
        self.emp_1.apply_raise()
        self.emp_2.apply_raise()

        self.assertEqual(self.emp_1.pay, 52500)
        self.assertEqual(self.emp_2.pay, 63000)

if __name__ == '__main__':
    unittest.main()

-----------employee.py--------------

import requests


class Employee:
    """A sample Employee class"""

    raise_amt = 1.05

    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.pay = pay

    @property
    def email(self):
        return '{}.{}@email.com'.format(self.first, self.last)

    @property
    def fullname(self):
        return '{} {}'.format(self.first, self.last)

    def apply_raise(self):
        self.pay = int(self.pay * self.raise_amt)

    def monthly_schedule(self, month):
        response = requests.get(f'http://company.com/{self.last}/{month}')
        if response.ok:
            return response.text
        else:
            return 'Bad Response!'

---------------------------------

...
----------------------------------------------------------------------
Ran 3 tests in 0.001s

OK

---------------------------------

==========================================

import unittest

from employee import Employee

class TestEmployee(unittest.TestCase):

    def setUp(self):
        print('setUp')
        self.emp_1 = Employee('Corey', 'Schafer', 50000)
        self.emp_2 = Employee('Sue', 'Smith', 60000)

    def tearDown(self):
        print('tearDown\n')

    def test_email(self):
        print('test_email')
        self.assertEqual(self.emp_1.email, 'Corey.Schafer@email.com')
        self.assertEqual(self.emp_2.email, 'Sue.Smith@email.com')

        self.emp_1.first = 'John'
        self.emp_2.first = 'Jane'

        self.assertEqual(self.emp_1.email, 'John.Schafer@email.com')
        self.assertEqual(self.emp_2.email, 'Jane.Smith@email.com')

    def test_fullname(self):
        print('test_fullname')
        self.assertEqual(self.emp_1.fullname, 'Corey Schafer')
        self.assertEqual(self.emp_2.fullname, 'Sue Smith')

        self.emp_1.first = 'John'
        self.emp_2.first = 'Jane'

        self.assertEqual(self.emp_1.fullname, 'John Schafer')
        self.assertEqual(self.emp_2.fullname, 'Jane Smith')

    def test_apply_raise(self):
        print('test_apply_raise')
        self.emp_1.apply_raise()
        self.emp_2.apply_raise()

        self.assertEqual(self.emp_1.pay, 52500)
        self.assertEqual(self.emp_2.pay, 63000)

if __name__ == '__main__':
    unittest.main()

-----------employee.py--------------

import requests


class Employee:
    """A sample Employee class"""

    raise_amt = 1.05

    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.pay = pay

    @property
    def email(self):
        return '{}.{}@email.com'.format(self.first, self.last)

    @property
    def fullname(self):
        return '{} {}'.format(self.first, self.last)

    def apply_raise(self):
        self.pay = int(self.pay * self.raise_amt)

    def monthly_schedule(self, month):
        response = requests.get(f'http://company.com/{self.last}/{month}')
        if response.ok:
            return response.text
        else:
            return 'Bad Response!'

---------------------------------

setUp
test_apply_raise
tearDown

.setUp
test_email
tearDown

.setUp.
test_fullname
tearDown


----------------------------------------------------------------------
Ran 3 tests in 0.001s

OK

---------------------------------

==========================================

import unittest

from employee import Employee

class TestEmployee(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        print('setupClass')

    @classmethod
    def tearDownClass(cls):
        print('teardownClass')
    def setUp(self):
        print('setUp')
        self.emp_1 = Employee('Corey', 'Schafer', 50000)
        self.emp_2 = Employee('Sue', 'Smith', 60000)

    def tearDown(self):
        print('tearDown\n')

    def test_email(self):
        print('test_email')
        self.assertEqual(self.emp_1.email, 'Corey.Schafer@email.com')
        self.assertEqual(self.emp_2.email, 'Sue.Smith@email.com')

        self.emp_1.first = 'John'
        self.emp_2.first = 'Jane'

        self.assertEqual(self.emp_1.email, 'John.Schafer@email.com')
        self.assertEqual(self.emp_2.email, 'Jane.Smith@email.com')

    def test_fullname(self):
        print('test_fullname')
        self.assertEqual(self.emp_1.fullname, 'Corey Schafer')
        self.assertEqual(self.emp_2.fullname, 'Sue Smith')

        self.emp_1.first = 'John'
        self.emp_2.first = 'Jane'

        self.assertEqual(self.emp_1.fullname, 'John Schafer')
        self.assertEqual(self.emp_2.fullname, 'Jane Smith')

    def test_apply_raise(self):
        print('test_apply_raise')
        self.emp_1.apply_raise()
        self.emp_2.apply_raise()

        self.assertEqual(self.emp_1.pay, 52500)
        self.assertEqual(self.emp_2.pay, 63000)

if __name__ == '__main__':
    unittest.main()

-----------employee.py--------------

import requests


class Employee:
    """A sample Employee class"""

    raise_amt = 1.05

    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.pay = pay

    @property
    def email(self):
        return '{}.{}@email.com'.format(self.first, self.last)

    @property
    def fullname(self):
        return '{} {}'.format(self.first, self.last)

    def apply_raise(self):
        self.pay = int(self.pay * self.raise_amt)

    def monthly_schedule(self, month):
        response = requests.get(f'http://company.com/{self.last}/{month}')
        if response.ok:
            return response.text
        else:
            return 'Bad Response!'

---------------------------------

setupClass
setUp
test_apply_raise
tearDown

.setUp
test_email
tearDown

.setUp
test_fullname
tearDown

.teardownClass

----------------------------------------------------------------------
Ran 3 tests in 0.001s

OK

---------------------------------

==========================================

import unittest
from unittest.mock import patch
from employee import Employee


class TestEmployee(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        print('setupClass')

    @classmethod
    def tearDownClass(cls):
        print('teardownClass')

    def setUp(self):
        print('setUp')
        self.emp_1 = Employee('Corey', 'Schafer', 50000)
        self.emp_2 = Employee('Sue', 'Smith', 60000)

    def tearDown(self):
        print('tearDown\n')

    def test_email(self):
        print('test_email')
        self.assertEqual(self.emp_1.email, 'Corey.Schafer@email.com')
        self.assertEqual(self.emp_2.email, 'Sue.Smith@email.com')

        self.emp_1.first = 'John'
        self.emp_2.first = 'Jane'

        self.assertEqual(self.emp_1.email, 'John.Schafer@email.com')
        self.assertEqual(self.emp_2.email, 'Jane.Smith@email.com')

    def test_fullname(self):
        print('test_fullname')
        self.assertEqual(self.emp_1.fullname, 'Corey Schafer')
        self.assertEqual(self.emp_2.fullname, 'Sue Smith')

        self.emp_1.first = 'John'
        self.emp_2.first = 'Jane'

        self.assertEqual(self.emp_1.fullname, 'John Schafer')
        self.assertEqual(self.emp_2.fullname, 'Jane Smith')

    def test_apply_raise(self):
        print('test_apply_raise')
        self.emp_1.apply_raise()
        self.emp_2.apply_raise()

        self.assertEqual(self.emp_1.pay, 52500)
        self.assertEqual(self.emp_2.pay, 63000)

    def test_monthly_schedule(self):
        with patch('employee.requests.get') as mocked_get:
            mocked_get.return_value.ok = True
            mocked_get.return_value.text = 'Success'

            schedule = self.emp_1.monthly_schedule('May')
            mocked_get.assert_called_with('http://company.com/Schafer/May')
            self.assertEqual(schedule, 'Success')

            mocked_get.return_value.ok = False

            schedule = self.emp_2.monthly_schedule('June')
            mocked_get.assert_called_with('http://company.com/Smith/June')
            self.assertEqual(schedule, 'Bad Response!')


if __name__ == '__main__':
    unittest.main()

-----------employee.py--------------

import requests


class Employee:
    """A sample Employee class"""

    raise_amt = 1.05

    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.pay = pay

    @property
    def email(self):
        return '{}.{}@email.com'.format(self.first, self.last)

    @property
    def fullname(self):
        return '{} {}'.format(self.first, self.last)

    def apply_raise(self):
        self.pay = int(self.pay * self.raise_amt)

    def monthly_schedule(self, month):
        response = requests.get(f'http://company.com/{self.last}/{month}')
        if response.ok:
            return response.text
        else:
            return 'Bad Response!'

---------------------------------

setupClass
setUp
test_apply_raise
tearDown
.
setUp
test_email
tearDown

.setUp
test_fullname
tearDown

.setUp
tearDown
.

teardownClass
----------------------------------------------------------------------
Ran 4 tests in 0.022s

OK

---------------------------------


Python - if __name__ == '__main__'

** if __name__ == '__main__'


==========================================

print(__name__)

---------------------------------

__main__

---------------------------------

==========================================

print("First Module's Name: {}".format(__name__))

---------------------------------

First Module's Name: __main__

---------------------------------

==========================================

import first_module

-------first_module.py---------------

print("First Module's Name: {}".format(__name__))

---------------------------------

First Module's Name: first_module

---------------------------------

==========================================

import first_module

print("Second Module's Name: {}".format(__name__))


-------first_module.py---------------

print("First Module's Name: {}".format(__name__))

---------------------------------

First Module's Name: first_module
Second Module's Name: __main__

---------------------------------

==========================================


def main():
print("First Module's Name: {}".format(__name__))

if __name__ == '__main__':
main()

---------------------------------

First Module's Name: __main__

---------------------------------

==========================================

import first_module

print("Second Module's Name: {}".format(__name__))

-------first_module.py---------------

def main():
print("First Module's Name: {}".format(__name__))

if __name__ == '__main__':
main()

---------------------------------

Second Module's Name: __main__

---------------------------------

==========================================

import first_module

print("Second Module's Name: {}".format(__name__))

-------first_module.py---------------

if __name__ == '__main__':
print("Run Directly")

else:
print("Run From Import")

---------------------------------

Run From Import
Second Module's Name: __main__

---------------------------------

==========================================

print("This will always be run")

def main():
print("First Module's Main Method")

if __name__ == '__main__':
main()

---------------------------------

This will always be run
First Module's Main Method

---------------------------------

==========================================

import first_module

print("Second Module's Name: {}".format(__name__))

-------first_module.py---------------

print("This will always be run")

def main():
print("First Module's Main Method")

if __name__ == '__main__':
main()

---------------------------------

This will always be run
Second Module's Name: __main__

---------------------------------

==========================================

import first_module

first_module.main()

print("Second Module's Name: {}".format(__name__))

-------first_module.py---------------

print("This will always be run")

def main():
print("First Module's Main Method")

if __name__ == '__main__':
main()

---------------------------------

This will always be run
First Module's Main Method
Second Module's Name: __main__

---------------------------------


Python - Hiding Passwords and Secret Keys in Environment Variables (Windows)

** Hiding Passwords and Secret Keys in Environment Variables (Windows)


==========================================

import os

db_user = os.environ.get('DB_USER')
db_password = os.environ.get('DB_PASS')


print(db_user)
print(db_password)

---------------------------------

my_db_user
my_db_pass_123!

---------------------------------


5/19/2020

Python - Logging Advanced : Loggers, Handlers, and Formatters

**  Logging Advanced - Loggers, Handlers, and Formatters


==========================================


import logging

logging.basicConfig(filename='employee.log', level=logging.INFO,
                    format='%(levelname)s:%(name)s:%(message)s')


class Employee:
    """A sample Employee class"""

    def __init__(self, first, last):
        self.first = first
        self.last = last

        logging.info('Created Employee: {} - {}'.format(self.fullname, self.email))

    @property
    def email(self):
        return '{}.{}@email.com'.format(self.first, self.last)

    @property
    def fullname(self):
        return '{} {}'.format(self.first, self.last)


emp_1 = Employee('John', 'Smith')
emp_2 = Employee('Corey', 'Schafer')
emp_3 = Employee('Jane', 'Doe')

---------employee.log---------------

INFO:root:Created Employee: John Smith - John.Smith@email.com
INFO:root:Created Employee: Corey Schafer - Corey.Schafer@email.com
INFO:root:Created Employee: Jane Doe - Jane.Doe@email.com

---------------------------------

==========================================

import logging

logging.basicConfig(filename='sample.log', level = logging.DEBUG,
format = '%(asctime)s:%(name)s:%(message)s')


def add(x, y):
    """Add Function"""
    return x + y


def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
    return x * y


def divide(x, y):
    """Divide Function"""
    return x / y


num_1 = 20
num_2 = 10


add_result = add(num_1, num_2)
logging.debug('Add: {} + {} = {}'.format(num_1, num_2, add_result))

sub_result = subtract(num_1, num_2)
logging.debug('Sub: {} - {} = {}'.format(num_1, num_2, sub_result))

mul_result = multiply(num_1, num_2)
logging.debug('Mul: {} * {} = {}'.format(num_1, num_2, mul_result))

div_result = divide(num_1, num_2)
logging.debug('Div: {} / {} = {}'.format(num_1, num_2, div_result))

----------sample.log---------------

2020-05-19 18:22:39,155:root:Add: 20 + 10 = 30
2020-05-19 18:22:39,155:root:Sub: 20 - 10 = 10
2020-05-19 18:22:39,155:root:Mul: 20 * 10 = 200
2020-05-19 18:22:39,156:root:Div: 20 / 10 = 2.0

---------------------------------

==========================================

import logging
import employee

logging.basicConfig(filename='sample.log', level = logging.DEBUG,
format = '%(asctime)s:%(name)s:%(message)s')


def add(x, y):
    """Add Function"""
    return x + y


def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
    return x * y


def divide(x, y):
    """Divide Function"""
    return x / y


num_1 = 20
num_2 = 10


add_result = add(num_1, num_2)
logging.debug('Add: {} + {} = {}'.format(num_1, num_2, add_result))

sub_result = subtract(num_1, num_2)
logging.debug('Sub: {} - {} = {}'.format(num_1, num_2, sub_result))

mul_result = multiply(num_1, num_2)
logging.debug('Mul: {} * {} = {}'.format(num_1, num_2, mul_result))

div_result = divide(num_1, num_2)
logging.debug('Div: {} / {} = {}'.format(num_1, num_2, div_result))

----------employee.py---------------

import logging

logging.basicConfig(filename='employee.log', level=logging.INFO,
                    format='%(levelname)s:%(name)s:%(message)s')


class Employee:
    """A sample Employee class"""

    def __init__(self, first, last):
        self.first = first
        self.last = last

        logging.info('Created Employee: {} - {}'.format(self.fullname, self.email))

    @property
    def email(self):
        return '{}.{}@email.com'.format(self.first, self.last)

    @property
    def fullname(self):
        return '{} {}'.format(self.first, self.last)


emp_1 = Employee('John', 'Smith')
emp_2 = Employee('Corey', 'Schafer')
emp_3 = Employee('Jane', 'Doe')


---------employee.log---------------

INFO:root:Created Employee: John Smith - John.Smith@email.com
INFO:root:Created Employee: Corey Schafer - Corey.Schafer@email.com
INFO:root:Created Employee: Jane Doe - Jane.Doe@email.com

---------------------------------

==========================================

import logging
import employee

logging.basicConfig(filename='sample.log', level = logging.DEBUG,
format = '%(asctime)s:%(name)s:%(message)s')


def add(x, y):
    """Add Function"""
    return x + y


def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
    return x * y


def divide(x, y):
    """Divide Function"""
    return x / y


num_1 = 20
num_2 = 10


add_result = add(num_1, num_2)
logging.info('Add: {} + {} = {}'.format(num_1, num_2, add_result))

sub_result = subtract(num_1, num_2)
logging.info('Sub: {} - {} = {}'.format(num_1, num_2, sub_result))

mul_result = multiply(num_1, num_2)
logging.info('Mul: {} * {} = {}'.format(num_1, num_2, mul_result))

div_result = divide(num_1, num_2)
logging.info('Div: {} / {} = {}'.format(num_1, num_2, div_result))

----------employee.py---------------

import logging

logging.basicConfig(filename='employee.log', level=logging.INFO,
                    format='%(levelname)s:%(name)s:%(message)s')


class Employee:
    """A sample Employee class"""

    def __init__(self, first, last):
        self.first = first
        self.last = last

        logging.info('Created Employee: {} - {}'.format(self.fullname, self.email))

    @property
    def email(self):
        return '{}.{}@email.com'.format(self.first, self.last)

    @property
    def fullname(self):
        return '{} {}'.format(self.first, self.last)


emp_1 = Employee('John', 'Smith')
emp_2 = Employee('Corey', 'Schafer')
emp_3 = Employee('Jane', 'Doe')


---------employee.log---------------

INFO:root:Created Employee: John Smith - John.Smith@email.com
INFO:root:Created Employee: Corey Schafer - Corey.Schafer@email.com
INFO:root:Created Employee: Jane Doe - Jane.Doe@email.com
INFO:root:Add: 20 + 10 = 30
INFO:root:Sub: 20 - 10 = 10
INFO:root:Mul: 20 * 10 = 200
INFO:root:Div: 20 / 10 = 2.0

---------------------------------

==========================================

import logging

logger = logging.getLogger(__name__)

logging.basicConfig(filename='employee.log', level=logging.INFO,
                    format='%(levelname)s:%(name)s:%(message)s')


class Employee:
    """A sample Employee class"""

    def __init__(self, first, last):
        self.first = first
        self.last = last

        logger.info('Created Employee: {} - {}'.format(self.fullname, self.email))

    @property
    def email(self):
        return '{}.{}@email.com'.format(self.first, self.last)

    @property
    def fullname(self):
        return '{} {}'.format(self.first, self.last)


emp_1 = Employee('John', 'Smith')
emp_2 = Employee('Corey', 'Schafer')
emp_3 = Employee('Jane', 'Doe')

---------employee.log---------------

INFO:__main__:Created Employee: John Smith - John.Smith@email.com
INFO:__main__:Created Employee: Corey Schafer - Corey.Schafer@email.com
INFO:__main__:Created Employee: Jane Doe - Jane.Doe@email.com

---------------------------------

==========================================

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

formatter = logging.Formatter('%(levelname)s:%(name)s:%(message)s')

file_handler = logging.FileHandler('employee.log')
file_handler.setFormatter(formatter)


logger.addHandler(file_handler)

class Employee:
    """A sample Employee class"""

    def __init__(self, first, last):
        self.first = first
        self.last = last

        logger.info('Created Employee: {} - {}'.format(self.fullname, self.email))

    @property
    def email(self):
        return '{}.{}@email.com'.format(self.first, self.last)

    @property
    def fullname(self):
        return '{} {}'.format(self.first, self.last)


emp_1 = Employee('John', 'Smith')
emp_2 = Employee('Corey', 'Schafer')
emp_3 = Employee('Jane', 'Doe')

---------employee.log---------------

INFO:__main__:Created Employee: John Smith - John.Smith@email.com
INFO:__main__:Created Employee: Corey Schafer - Corey.Schafer@email.com
INFO:__main__:Created Employee: Jane Doe - Jane.Doe@email.com

---------------------------------

==========================================

import logging
import employee

logging.basicConfig(filename='sample.log', level = logging.DEBUG,
format = '%(asctime)s:%(name)s:%(message)s')


def add(x, y):
    """Add Function"""
    return x + y


def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
    return x * y


def divide(x, y):
    """Divide Function"""
    return x / y


num_1 = 20
num_2 = 10


add_result = add(num_1, num_2)
logging.info('Add: {} + {} = {}'.format(num_1, num_2, add_result))

sub_result = subtract(num_1, num_2)
logging.info('Sub: {} - {} = {}'.format(num_1, num_2, sub_result))

mul_result = multiply(num_1, num_2)
logging.info('Mul: {} * {} = {}'.format(num_1, num_2, mul_result))

div_result = divide(num_1, num_2)
logging.info('Div: {} / {} = {}'.format(num_1, num_2, div_result))

---------employee.py----------------

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

formatter = logging.Formatter('%(levelname)s:%(name)s:%(message)s')

file_handler = logging.FileHandler('employee.log')
file_handler.setFormatter(formatter)


logger.addHandler(file_handler)

class Employee:
    """A sample Employee class"""

    def __init__(self, first, last):
        self.first = first
        self.last = last

        logger.info('Created Employee: {} - {}'.format(self.fullname, self.email))

    @property
    def email(self):
        return '{}.{}@email.com'.format(self.first, self.last)

    @property
    def fullname(self):
        return '{} {}'.format(self.first, self.last)


emp_1 = Employee('John', 'Smith')
emp_2 = Employee('Corey', 'Schafer')
emp_3 = Employee('Jane', 'Doe')

-----------sample.log---------------

2020-05-19 18:40:59,594:root:Add: 20 + 10 = 30
2020-05-19 18:40:59,594:root:Sub: 20 - 10 = 10
2020-05-19 18:40:59,594:root:Mul: 20 * 10 = 200
2020-05-19 18:40:59,594:root:Div: 20 / 10 = 2.0

---------employee.log---------------

INFO:employee:Created Employee: John Smith - John.Smith@email.com
INFO:employee:Created Employee: Corey Schafer - Corey.Schafer@email.com
INFO:employee:Created Employee: Jane Doe - Jane.Doe@email.com

---------------------------------

==========================================

import logging
import employee

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(asctime)s:%(name)s:%(message)s')

file_handler = logging.FileHandler('sample.log')
file_handler.setFormatter(formatter)


logger.addHandler(file_handler)



def add(x, y):
    """Add Function"""
    return x + y


def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
    return x * y


def divide(x, y):
    """Divide Function"""
    return x / y


num_1 = 20
num_2 = 10


add_result = add(num_1, num_2)
logger.debug('Add: {} + {} = {}'.format(num_1, num_2, add_result))

sub_result = subtract(num_1, num_2)
logger.debug('Sub: {} - {} = {}'.format(num_1, num_2, sub_result))

mul_result = multiply(num_1, num_2)
logger.debug('Mul: {} * {} = {}'.format(num_1, num_2, mul_result))

div_result = divide(num_1, num_2)
logger.debug('Div: {} / {} = {}'.format(num_1, num_2, div_result))

---------employee.py----------------

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

formatter = logging.Formatter('%(levelname)s:%(name)s:%(message)s')

file_handler = logging.FileHandler('employee.log')
file_handler.setFormatter(formatter)


logger.addHandler(file_handler)

class Employee:
    """A sample Employee class"""

    def __init__(self, first, last):
        self.first = first
        self.last = last

        logger.info('Created Employee: {} - {}'.format(self.fullname, self.email))

    @property
    def email(self):
        return '{}.{}@email.com'.format(self.first, self.last)

    @property
    def fullname(self):
        return '{} {}'.format(self.first, self.last)


emp_1 = Employee('John', 'Smith')
emp_2 = Employee('Corey', 'Schafer')
emp_3 = Employee('Jane', 'Doe')

-----------sample.log---------------

2020-05-19 18:50:07,802:__main__:Add: 20 + 10 = 30
2020-05-19 18:50:07,802:__main__:Sub: 20 - 10 = 10
2020-05-19 18:50:07,803:__main__:Mul: 20 * 10 = 200
2020-05-19 18:50:07,803:__main__:Div: 20 / 10 = 2.0

---------employee.log---------------

INFO:employee:Created Employee: John Smith - John.Smith@email.com
INFO:employee:Created Employee: Corey Schafer - Corey.Schafer@email.com
INFO:employee:Created Employee: Jane Doe - Jane.Doe@email.com

---------------------------------

==========================================

import logging
import employee

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(asctime)s:%(name)s:%(message)s')

file_handler = logging.FileHandler('sample.log')
file_handler.setLevel(logging.ERROR)
file_handler.setFormatter(formatter)


logger.addHandler(file_handler)



def add(x, y):
    """Add Function"""
    return x + y


def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
    return x * y


def divide(x, y):
    """Divide Function"""
    return x / y


num_1 = 20
num_2 = 10


add_result = add(num_1, num_2)
logger.debug('Add: {} + {} = {}'.format(num_1, num_2, add_result))

sub_result = subtract(num_1, num_2)
logger.debug('Sub: {} - {} = {}'.format(num_1, num_2, sub_result))

mul_result = multiply(num_1, num_2)
logger.debug('Mul: {} * {} = {}'.format(num_1, num_2, mul_result))

div_result = divide(num_1, num_2)
logger.debug('Div: {} / {} = {}'.format(num_1, num_2, div_result))

-----------sample.log---------------

<~~ ERROR 가 없기 때문에, sample.log 파일에 내용 없음

---------------------------------

==========================================

import logging
import employee

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(asctime)s:%(name)s:%(message)s')

file_handler = logging.FileHandler('sample.log')
file_handler.setLevel(logging.ERROR)
file_handler.setFormatter(formatter)


logger.addHandler(file_handler)



def add(x, y):
    """Add Function"""
    return x + y


def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
    return x * y


def divide(x, y):
    """Divide Function"""
    try:
    result = x / y
    except ZeroDivisionError:
    logger.error('Tried to divide by zero')
    else:
    return resule

 


num_1 = 20
num_2 = 0


add_result = add(num_1, num_2)
logger.debug('Add: {} + {} = {}'.format(num_1, num_2, add_result))

sub_result = subtract(num_1, num_2)
logger.debug('Sub: {} - {} = {}'.format(num_1, num_2, sub_result))

mul_result = multiply(num_1, num_2)
logger.debug('Mul: {} * {} = {}'.format(num_1, num_2, mul_result))

div_result = divide(num_1, num_2)
logger.debug('Div: {} / {} = {}'.format(num_1, num_2, div_result))


-----------sample.log---------------

2020-05-19 18:59:07,508:__main__:Tried to divide by zero

---------------------------------

==========================================


import logging
import employee

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(asctime)s:%(name)s:%(message)s')

file_handler = logging.FileHandler('sample.log')
file_handler.setLevel(logging.ERROR)
file_handler.setFormatter(formatter)


logger.addHandler(file_handler)



def add(x, y):
    """Add Function"""
    return x + y


def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
    return x * y


def divide(x, y):
    """Divide Function"""
    try:
    result = x / y
    except ZeroDivisionError:
    logger.exception('Tried to divide by zero')
    else:
    return resule

 


num_1 = 20
num_2 = 0


add_result = add(num_1, num_2)
logger.debug('Add: {} + {} = {}'.format(num_1, num_2, add_result))

sub_result = subtract(num_1, num_2)
logger.debug('Sub: {} - {} = {}'.format(num_1, num_2, sub_result))

mul_result = multiply(num_1, num_2)
logger.debug('Mul: {} * {} = {}'.format(num_1, num_2, mul_result))

div_result = divide(num_1, num_2)
logger.debug('Div: {} / {} = {}'.format(num_1, num_2, div_result))


-----------sample.log---------------

2020-05-19 19:15:59,921:__main__:Tried to divide by zero
Traceback (most recent call last):
  File "C:\Users\purunet\Documents\py6\log1.py", line 37, in divide
    result = x / y
ZeroDivisionError: division by zero

---------------------------------

==========================================

import logging
import employee

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(asctime)s:%(name)s:%(message)s')

file_handler = logging.FileHandler('sample.log')
file_handler.setLevel(logging.ERROR)
file_handler.setFormatter(formatter)

stream_handler = logging.StreamHandler()


logger.addHandler(file_handler)
logger.addHandler(stream_handler)


def add(x, y):
    """Add Function"""
    return x + y


def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
    return x * y


def divide(x, y):
    """Divide Function"""
    try:
    result = x / y
    except ZeroDivisionError:
    logger.exception('Tried to divide by zero')
    else:
    return resule

 


num_1 = 20
num_2 = 0


add_result = add(num_1, num_2)
logger.debug('Add: {} + {} = {}'.format(num_1, num_2, add_result))

sub_result = subtract(num_1, num_2)
logger.debug('Sub: {} - {} = {}'.format(num_1, num_2, sub_result))

mul_result = multiply(num_1, num_2)
logger.debug('Mul: {} * {} = {}'.format(num_1, num_2, mul_result))

div_result = divide(num_1, num_2)
logger.debug('Div: {} / {} = {}'.format(num_1, num_2, div_result))

---------------------------------

Add: 20 + 0 = 20
Sub: 20 - 0 = 20
Mul: 20 * 0 = 0
Tried to divide by zero
Traceback (most recent call last):
  File "C:\Users\purunet\Documents\py6\log1.py", line 39, in divide
    result = x / y
ZeroDivisionError: division by zero
Div: 20 / 0 = None

---------------------------------

==========================================


import logging
import employee

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(asctime)s:%(name)s:%(message)s')

file_handler = logging.FileHandler('sample.log')
file_handler.setLevel(logging.ERROR)
file_handler.setFormatter(formatter)

stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)


logger.addHandler(file_handler)
logger.addHandler(stream_handler)


def add(x, y):
    """Add Function"""
    return x + y


def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
    return x * y


def divide(x, y):
    """Divide Function"""
    try:
    result = x / y
    except ZeroDivisionError:
    logger.exception('Tried to divide by zero')
    else:
    return resule

 


num_1 = 20
num_2 = 0


add_result = add(num_1, num_2)
logger.debug('Add: {} + {} = {}'.format(num_1, num_2, add_result))

sub_result = subtract(num_1, num_2)
logger.debug('Sub: {} - {} = {}'.format(num_1, num_2, sub_result))

mul_result = multiply(num_1, num_2)
logger.debug('Mul: {} * {} = {}'.format(num_1, num_2, mul_result))

div_result = divide(num_1, num_2)
logger.debug('Div: {} / {} = {}'.format(num_1, num_2, div_result))

---------------------------------

2020-05-19 19:20:20,756:__main__:Add: 20 + 0 = 20
2020-05-19 19:20:20,756:__main__:Sub: 20 - 0 = 20
2020-05-19 19:20:20,757:__main__:Mul: 20 * 0 = 0
2020-05-19 19:20:20,758:__main__:Tried to divide by zero
Traceback (most recent call last):
  File "C:\Users\purunet\Documents\py6\log1.py", line 40, in divide
    result = x / y
ZeroDivisionError: division by zero
2020-05-19 19:20:20,762:__main__:Div: 20 / 0 = None

---------------------------------

Python - Logging Basics : Logging to Files, Setting Levels, and Formatting

** Logging Basics - Logging to Files, Setting Levels, and Formatting



==========================================

def add(x, y):
    """Add Function"""
    return x + y


def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
    return x * y


def divide(x, y):
    """Divide Function"""
    return x / y


num_1 = 10
num_2 = 5


add_result = add(num_1, num_2)
print('Add: {} + {} = {}'.format(num_1, num_2, add_result))

sub_result = subtract(num_1, num_2)
print('Sub: {} - {} = {}'.format(num_1, num_2, sub_result))

mul_result = multiply(num_1, num_2)
print('Mul: {} * {} = {}'.format(num_1, num_2, mul_result))

div_result = divide(num_1, num_2)
print('Div: {} / {} = {}'.format(num_1, num_2, div_result))

---------------------------------

Add: 10 + 5 = 15
Sub: 10 - 5 = 5
Mul: 10 * 5 = 50
Div: 10 / 5 = 2.0

---------------------------------

==========================================

import logging

# DEBUG: Detailed information, typically of interest only when diagnosing problems.

# INFO: Confirmation that things are working as expected.

# WARNING: An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected.

# ERROR: Due to a more serious problem, the software has not been able to perform some function.

# CRITICAL: A serious error, indicating that the program itself may be unable to continue running.


def add(x, y):
    """Add Function"""
    return x + y


def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
    return x * y


def divide(x, y):
    """Divide Function"""
    return x / y


num_1 = 10
num_2 = 5


add_result = add(num_1, num_2)
logging.warning('Add: {} + {} = {}'.format(num_1, num_2, add_result))

sub_result = subtract(num_1, num_2)
logging.warning('Sub: {} - {} = {}'.format(num_1, num_2, sub_result))

mul_result = multiply(num_1, num_2)
logging.warning('Mul: {} * {} = {}'.format(num_1, num_2, mul_result))

div_result = divide(num_1, num_2)
logging.warning('Div: {} / {} = {}'.format(num_1, num_2, div_result))

---------------------------------

WARNING:root:Add: 10 + 5 = 15
WARNING:root:Sub: 10 - 5 = 5
WARNING:root:Mul: 10 * 5 = 50
WARNING:root:Div: 10 / 5 = 2.0

---------------------------------

==========================================

import logging

# DEBUG: Detailed information, typically of interest only when diagnosing problems.

# INFO: Confirmation that things are working as expected.

# WARNING: An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected.

# ERROR: Due to a more serious problem, the software has not been able to perform some function.

# CRITICAL: A serious error, indicating that the program itself may be unable to continue running.


logging.basicConfig(level = logging.DEBUG)

def add(x, y):
    """Add Function"""
    return x + y


def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
    return x * y


def divide(x, y):
    """Divide Function"""
    return x / y


num_1 = 10
num_2 = 5


add_result = add(num_1, num_2)
logging.debug('Add: {} + {} = {}'.format(num_1, num_2, add_result))

sub_result = subtract(num_1, num_2)
logging.debug('Sub: {} - {} = {}'.format(num_1, num_2, sub_result))

mul_result = multiply(num_1, num_2)
logging.debug('Mul: {} * {} = {}'.format(num_1, num_2, mul_result))

div_result = divide(num_1, num_2)
logging.debug('Div: {} / {} = {}'.format(num_1, num_2, div_result))

---------------------------------

DEBUG:root:Add: 10 + 5 = 15
DEBUG:root:Sub: 10 - 5 = 5
DEBUG:root:Mul: 10 * 5 = 50
DEBUG:root:Div: 10 / 5 = 2.0

---------------------------------

==========================================

import logging

# DEBUG: Detailed information, typically of interest only when diagnosing problems.

# INFO: Confirmation that things are working as expected.

# WARNING: An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected.

# ERROR: Due to a more serious problem, the software has not been able to perform some function.

# CRITICAL: A serious error, indicating that the program itself may be unable to continue running.


logging.basicConfig(filename='test.log', level = logging.DEBUG)

def add(x, y):
    """Add Function"""
    return x + y


def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
    return x * y


def divide(x, y):
    """Divide Function"""
    return x / y


num_1 = 10
num_2 = 5


add_result = add(num_1, num_2)
logging.debug('Add: {} + {} = {}'.format(num_1, num_2, add_result))

sub_result = subtract(num_1, num_2)
logging.debug('Sub: {} - {} = {}'.format(num_1, num_2, sub_result))

mul_result = multiply(num_1, num_2)
logging.debug('Mul: {} * {} = {}'.format(num_1, num_2, mul_result))

div_result = divide(num_1, num_2)
logging.debug('Div: {} / {} = {}'.format(num_1, num_2, div_result))


---------test.log------------------

DEBUG:root:Add: 10 + 5 = 15
DEBUG:root:Sub: 10 - 5 = 5
DEBUG:root:Mul: 10 * 5 = 50
DEBUG:root:Div: 10 / 5 = 2.0

---------------------------------

==========================================

import logging

# DEBUG: Detailed information, typically of interest only when diagnosing problems.

# INFO: Confirmation that things are working as expected.

# WARNING: An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected.

# ERROR: Due to a more serious problem, the software has not been able to perform some function.

# CRITICAL: A serious error, indicating that the program itself may be unable to continue running.


logging.basicConfig(filename='test.log', level = logging.DEBUG)

def add(x, y):
    """Add Function"""
    return x + y


def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
    return x * y


def divide(x, y):
    """Divide Function"""
    return x / y


num_1 = 20
num_2 = 10


add_result = add(num_1, num_2)
logging.debug('Add: {} + {} = {}'.format(num_1, num_2, add_result))

sub_result = subtract(num_1, num_2)
logging.debug('Sub: {} - {} = {}'.format(num_1, num_2, sub_result))

mul_result = multiply(num_1, num_2)
logging.debug('Mul: {} * {} = {}'.format(num_1, num_2, mul_result))

div_result = divide(num_1, num_2)
logging.debug('Div: {} / {} = {}'.format(num_1, num_2, div_result))

---------test.log------------------

DEBUG:root:Add: 10 + 5 = 15
DEBUG:root:Sub: 10 - 5 = 5
DEBUG:root:Mul: 10 * 5 = 50
DEBUG:root:Div: 10 / 5 = 2.0
DEBUG:root:Add: 20 + 10 = 30
DEBUG:root:Sub: 20 - 10 = 10
DEBUG:root:Mul: 20 * 10 = 200
DEBUG:root:Div: 20 / 10 = 2.0

---------------------------------

==========================================

https://docs.python.org/3/library/logging.html

==========================================


import logging

# DEBUG: Detailed information, typically of interest only when diagnosing problems.

# INFO: Confirmation that things are working as expected.

# WARNING: An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected.

# ERROR: Due to a more serious problem, the software has not been able to perform some function.

# CRITICAL: A serious error, indicating that the program itself may be unable to continue running.


logging.basicConfig(filename='test.log', level = logging.DEBUG,
format = '%(asctime)s:%(levelname)s:%(message)s')


def add(x, y):
    """Add Function"""
    return x + y


def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
    return x * y


def divide(x, y):
    """Divide Function"""
    return x / y


num_1 = 20
num_2 = 10


add_result = add(num_1, num_2)
logging.debug('Add: {} + {} = {}'.format(num_1, num_2, add_result))

sub_result = subtract(num_1, num_2)
logging.debug('Sub: {} - {} = {}'.format(num_1, num_2, sub_result))

mul_result = multiply(num_1, num_2)
logging.debug('Mul: {} * {} = {}'.format(num_1, num_2, mul_result))

div_result = divide(num_1, num_2)
logging.debug('Div: {} / {} = {}'.format(num_1, num_2, div_result))


---------test.log------------------

DEBUG:root:Add: 10 + 5 = 15
DEBUG:root:Sub: 10 - 5 = 5
DEBUG:root:Mul: 10 * 5 = 50
DEBUG:root:Div: 10 / 5 = 2.0
DEBUG:root:Add: 20 + 10 = 30
DEBUG:root:Sub: 20 - 10 = 10
DEBUG:root:Mul: 20 * 10 = 200
DEBUG:root:Div: 20 / 10 = 2.0
2020-05-19 18:03:54,008:DEBUG:Add: 20 + 10 = 30
2020-05-19 18:03:54,033:DEBUG:Sub: 20 - 10 = 10
2020-05-19 18:03:54,033:DEBUG:Mul: 20 * 10 = 200
2020-05-19 18:03:54,033:DEBUG:Div: 20 / 10 = 2.0

---------------------------------

==========================================

class Employee:
    """A sample Employee class"""

    def __init__(self, first, last):
        self.first = first
        self.last = last

        print('Created Employee: {} - {}'.format(self.fullname, self.email))

    @property
    def email(self):
        return '{}.{}@email.com'.format(self.first, self.last)

    @property
    def fullname(self):
        return '{} {}'.format(self.first, self.last)


emp_1 = Employee('John', 'Smith')
emp_2 = Employee('Corey', 'Schafer')

---------------------------------

Created Employee: John Smith - John.Smith@email.com
Created Employee: Corey Schafer - Corey.Schafer@email.com

---------------------------------

==========================================

import logging

logging.basicConfig(filename = 'employee.log', level = logging.INFO,
format = '%(levelname)s:%(message)s')

class Employee:
    """A sample Employee class"""

    def __init__(self, first, last):
        self.first = first
        self.last = last

        logging.info('Created Employee: {} - {}'.format(self.fullname, self.email))

    @property
    def email(self):
        return '{}.{}@email.com'.format(self.first, self.last)

    @property
    def fullname(self):
        return '{} {}'.format(self.first, self.last)


emp_1 = Employee('John', 'Smith')
emp_2 = Employee('Corey', 'Schafer')
emp_3 = Employee('Jane', 'Doe')

---------employee.log--------------

INFO:Created Employee: John Smith - John.Smith@email.com
INFO:Created Employee: Corey Schafer - Corey.Schafer@email.com
INFO:Created Employee: Jane Doe - Jane.Doe@email.com

---------------------------------




5/17/2020

Python - SQLite

** SQLite : Complete Overview - Creating a Database, Table, and Running Queries


==========================================

import sqlite3

conn = sqlite3.connect('employee.db')

==========================================

import sqlite3

conn = sqlite3.connect('employee.db')

c = conn.cursor()

c.execute("""CREATE TABLE employees (
first text,
last text,
pay integer
)""")

conn.commit()

conn.close()

---------------------------------

 c.execute("""CREATE TABLE employees (
sqlite3.OperationalError: table employees already exists

---------------------------------

==========================================


import sqlite3

conn = sqlite3.connect('employee.db')

c = conn.cursor()

c.execute("SELECT * FROM employees WHERE last='Schafer'")

print(c.fetchone())

conn.commit()

conn.close()

---------------------------------

('Corey', 'Schafer', 50000)

---------------------------------

==========================================

import sqlite3

conn = sqlite3.connect('employee.db')

c = conn.cursor()

c.execute("SELECT * FROM employees WHERE last='Smith'")

print(c.fetchone())

conn.commit()

conn.close()

---------------------------------

None

---------------------------------

==========================================

import sqlite3

conn = sqlite3.connect('employee.db')

c = conn.cursor()

c.execute("SELECT * FROM employees WHERE last='Schafer'")

print(c.fetchall())

conn.commit()

conn.close()

---------------------------------

[('Corey', 'Schafer', 50000)]

---------------------------------

==========================================

import sqlite3

conn = sqlite3.connect('employee.db')

c = conn.cursor()

c.execute("INSERT INTO employees VALUES ('Mary', 'Schafer', 70000)")

conn.commit()

c.execute("SELECT * FROM employees WHERE last='Schafer'")

print(c.fetchall())

conn.commit()

conn.close()

---------------------------------

[('Corey', 'Schafer', 50000), ('Mary', 'Schafer', 70000)]

---------------------------------

==========================================

import sqlite3
from employee import Employee


conn = sqlite3.connect('employee.db')

c = conn.cursor()


emp_1 = Employee('John', 'Doe', 80000)
emp_2 = Employee('Jane', 'Doe', 90000)

print(emp_1.first)
print(emp_1.last)
print(emp_1.pay)

c.execute("SELECT * FROM employees WHERE last='Schafer'")

print(c.fetchall())

conn.commit()

conn.close()

---------------------------------

John
Doe
80000
[('Corey', 'Schafer', 50000), ('Mary', 'Schafer', 70000)]

---------------------------------

==========================================

import sqlite3
from employee import Employee


conn = sqlite3.connect('employee.db')

c = conn.cursor()


emp_1 = Employee('John', 'Doe', 80000)
emp_2 = Employee('Jane', 'Doe', 90000)

# c.execute("INSERT INTO employees VALUES ('{}', '{}', '{})".format(emp_1.first, emp_1.last, emp_1.pay))
c.execute("INSERT INTO employees VALUES (?, ?, ?)", (emp_1.first, emp_1.last, emp_1.pay))


conn.commit()

c.execute("INSERT INTO employees VALUES (:first, :last, :pay)", {'first': emp_2.first, 'last': emp_2.last, 'pay': emp_2.pay})

conn.commit()

c.execute("SELECT * FROM employees WHERE last='Schafer'")

print(c.fetchall())

conn.commit()

conn.close()

---------------------------------

[('Corey', 'Schafer', 50000), ('Mary', 'Schafer', 70000)]

---------------------------------

==========================================

import sqlite3
from employee import Employee


conn = sqlite3.connect('employee.db')

c = conn.cursor()


emp_1 = Employee('John', 'Doe', 80000)
emp_2 = Employee('Jane', 'Doe', 90000)

c.execute("SELECT * FROM employees WHERE last=?", ('Schafer',))

print(c.fetchall())

c.execute("SELECT * FROM employees WHERE last=:last", {'last': 'Doe'})

print(c.fetchall())

conn.commit()

conn.close()

---------------------------------

[('Corey', 'Schafer', 50000), ('Mary', 'Schafer', 70000)]
[('John', 'Doe', 80000), ('Jane', 'Doe', 90000)]

---------------------------------

==========================================

import sqlite3
from employee import Employee


conn = sqlite3.connect(':memory:')

c = conn.cursor()

c.execute("""CREATE TABLE employees (
first text,
last text,
pay integer
)""")

emp_1 = Employee('John', 'Doe', 80000)
emp_2 = Employee('Jane', 'Doe', 90000)


# c.execute("INSERT INTO employees VALUES ('{}', '{}', '{})".format(emp_1.first, emp_1.last, emp_1.pay))
c.execute("INSERT INTO employees VALUES (?, ?, ?)", (emp_1.first, emp_1.last, emp_1.pay))


conn.commit()

c.execute("INSERT INTO employees VALUES (:first, :last, :pay)", {'first': emp_2.first, 'last': emp_2.last, 'pay': emp_2.pay})

conn.commit()


# c.execute("SELECT * FROM employees WHERE last='Schafer'")

c.execute("SELECT * FROM employees WHERE last=?", ('Schafer',))

print(c.fetchall())

c.execute("SELECT * FROM employees WHERE last=:last", {'last': 'Doe'})

print(c.fetchall())

conn.commit()

conn.close()

---------------------------------

[]
[('John', 'Doe', 80000), ('Jane', 'Doe', 90000)]

---------------------------------

==========================================

import sqlite3
from employee import Employee


conn = sqlite3.connect(':memory:')

c = conn.cursor()

c.execute("""CREATE TABLE employees (
first text,
last text,
pay integer
)""")


def insert_emp(emp):
with conn:
c.execute("INSERT INTO employees VALUES (:first, :last, :pay)", {'first': emp.first, 'last': emp.last, 'pay': emp.pay})


def get_emps_by_name(lastname):
    c.execute("SELECT * FROM employees WHERE last=:last", {'last': lastname})
    return c.fetchall()

def update_pay(emp, pay):
    with conn:
        c.execute("""UPDATE employees SET pay = :pay
                    WHERE first = :first AND last = :last""",
                  {'first': emp.first, 'last': emp.last, 'pay': pay})


def remove_emp(emp):
    with conn:
        c.execute("DELETE from employees WHERE first = :first AND last = :last",
                  {'first': emp.first, 'last': emp.last})


emp_1 = Employee('John', 'Doe', 80000)
emp_2 = Employee('Jane', 'Doe', 90000)


insert_emp(emp_1)
insert_emp(emp_2)

emps = get_emps_by_name('Doe')
print(emps)

update_pay(emp_2, 95000)
remove_emp(emp_1)

emps = get_emps_by_name('Doe')
print(emps)


conn.close()

---------------------------------

[('John', 'Doe', 80000), ('Jane', 'Doe', 90000)]
[('Jane', 'Doe', 95000)]

---------------------------------


Python - str() vs repr()

** str() vs repr()


==========================================

# The goal of __repr__ is to be unambiguous
# The goal of __str__ is to be readable

==========================================

==========================================

a = [1, 2, 3, 4]
b = 'sample string'

print(str(a))
print(repr(a))

print(str(b))
print(repr(b))

---------------------------------

[1, 2, 3, 4]
[1, 2, 3, 4]
sample string
'sample string'

---------------------------------

==========================================

import datetime
import pytz

a = datetime.datetime.utcnow().replace(tzinfo=pytz.UTC)

b = str(a)

print('str(a): {}'.format(str(a)))
print('str(b): {}'.format(str(b)))

print()

print('repr(a): {}'.format(repr(a)))
print('repr(b): {}'.format(repr(b)))

print()

---------------------------------

str(a): 2020-05-17 01:18:15.230995+00:00
str(b): 2020-05-17 01:18:15.230995+00:00

repr(a): datetime.datetime(2020, 5, 17, 1, 18, 15, 230995, tzinfo=)
repr(b): '2020-05-17 01:18:15.230995+00:00'

---------------------------------

Python - Context Managers : Efficiently Managing Resources

** Context Managers - Efficiently Managing Resources


==========================================

class Open_File():

def __init__(self, filename, mode):
self.filename = filename
self.mode = mode

def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file

def __exit__(self, exc_type, exc_val, traceback):
self.file.close()


with Open_File('sample.txt', 'w') as f:
f.write('Testing')


print(f.closed)

---------------------------------

True

---------------------------------

Testing  <~~ sample.txt

---------------------------------

==========================================

from contextlib import contextmanager


@contextmanager
def open_file(file, mode):
    f = open(file, mode)
    yield f
    f.close()


with open_file('sample.txt', 'w') as f:
    f.write('Hi, LinuxerHAN !!')

print(f.closed)

---------------------------------

True

---------------------------------

Hi, LinuxerHAN !!  <~~ sample.txt

---------------------------------

==========================================


import os
from contextlib import contextmanager


cwd = os.getcwd()
os.chdir('Sample-Dir-One')
print(os.listdir())
os.chdir(cwd)

cwd = os.getcwd()
os.chdir('Sample-Dir-Two')
print(os.listdir())
os.chdir(cwd)

---------------------------------

['1-1.txt', '1-2.txt', '1-3.txt']
['2-1.txt', '2-2.txt', '2-3.txt']

---------------------------------

==========================================

import os
from contextlib import contextmanager


@contextmanager
def change_dir(destination):
try:
cwd = os.getcwd()
os.chdir(destination)
yield

finally:
os.chdir(cwd)

with change_dir('Sample-Dir-One'):
print(os.listdir())

with change_dir('Sample-Dir-Two'):
print(os.listdir())

---------------------------------

['1-1.txt', '1-2.txt', '1-3.txt']
['2-1.txt', '2-2.txt', '2-3.txt']

---------------------------------




Python - Calculate Number of Days, Weeks, or Months to Reach Specific Goals

** Calculate Number of Days, Weeks, or Months to Reach Specific Goals



==========================================

import datetime
import calendar

balance = 5000
interest_rate = 13 * .01
monthly_payment = 500

today = datetime.date.today()

days_in_current_month = calendar.monthrange(today.year, today.month)

print(days_in_current_month)

---------------------------------

(4, 31)

---------------------------------

==========================================

import datetime
import calendar

balance = 5000
interest_rate = 13 * .01
monthly_payment = 500

today = datetime.date.today()

days_in_current_month = calendar.monthrange(today.year, today.month)[1]

print(days_in_current_month)

---------------------------------

31

---------------------------------

==========================================

import datetime
import calendar

balance = 5000
interest_rate = 13 * .01
monthly_payment = 500

today = datetime.date.today()

days_in_current_month = calendar.monthrange(today.year, today.month)[1]
days_till_end_month = days_in_current_month - today.day

print(days_till_end_month)

---------------------------------

14

---------------------------------

==========================================

import datetime
import calendar

balance = 5000
interest_rate = 13 * .01
monthly_payment = 500

today = datetime.date.today()

days_in_current_month = calendar.monthrange(today.year, today.month)[1]
days_till_end_month = days_in_current_month - today.day

start_date = today + datetime.timedelta(days = days_till_end_month + 1)

print(start_date)

---------------------------------

2020-06-01

---------------------------------

==========================================

import datetime
import calendar

balance = 5000
interest_rate = 13 * .01
monthly_payment = 500

today = datetime.date.today()
days_in_current_month = calendar.monthrange(today.year, today.month)[1]
days_till_end_month = days_in_current_month - today.day

start_date = today + datetime.timedelta(days = days_till_end_month + 1)
end_date = start_date

while balance > 0:
interest_charge = (interest_rate / 12) * balance
balance += interest_charge
balance -= monthly_payment

balance = round(balance, 2)
if balance < 0:
balance = 0

# balance = 0 if balance < 0 else round(balance, 2)

print(end_date, balance)


days_in_current_month = calendar.monthrange(end_date.year, end_date.month)[1]
end_date = end_date + datetime.timedelta(days = days_in_current_month)

---------------------------------

2020-06-01 4554.17
2020-07-01 4103.51
2020-08-01 3647.96
2020-09-01 3187.48
2020-10-01 2722.01
2020-11-01 2251.5
2020-12-01 1775.89
2021-01-01 1295.13
2021-02-01 809.16
2021-03-01 317.93
2021-04-01 0

---------------------------------

==========================================

import datetime
import calendar

balance = 10000
interest_rate = 13 * .01
monthly_payment = 500

today = datetime.date.today()
days_in_current_month = calendar.monthrange(today.year, today.month)[1]
days_till_end_month = days_in_current_month - today.day

start_date = today + datetime.timedelta(days = days_till_end_month + 1)
end_date = start_date

while balance > 0:
interest_charge = (interest_rate / 12) * balance
balance += interest_charge
balance -= monthly_payment

balance = round(balance, 2)
if balance < 0:
balance = 0

# balance = 0 if balance < 0 else round(balance, 2)

print(end_date, balance)


days_in_current_month = calendar.monthrange(end_date.year, end_date.month)[1]
end_date = end_date + datetime.timedelta(days = days_in_current_month)


---------------------------------

2020-06-01 9608.33
2020-07-01 9212.42
2020-08-01 8812.22
2020-09-01 8407.69
2020-10-01 7998.77
2020-11-01 7585.42
2020-12-01 7167.6
2021-01-01 6745.25
2021-02-01 6318.32
2021-03-01 5886.77
2021-04-01 5450.54
2021-05-01 5009.59
2021-06-01 4563.86
2021-07-01 4113.3
2021-08-01 3657.86
2021-09-01 3197.49
2021-10-01 2732.13
2021-11-01 2261.73
2021-12-01 1786.23
2022-01-01 1305.58
2022-02-01 819.72
2022-03-01 328.6
2022-04-01 0

---------------------------------

==========================================

import datetime
import calendar

balance = 10000
interest_rate = 13 * .01
monthly_payment = 110

today = datetime.date.today()
days_in_current_month = calendar.monthrange(today.year, today.month)[1]
days_till_end_month = days_in_current_month - today.day

start_date = today + datetime.timedelta(days = days_till_end_month + 1)
end_date = start_date

while balance > 0:
interest_charge = (interest_rate / 12) * balance
balance += interest_charge
balance -= monthly_payment

balance = round(balance, 2)
if balance < 0:
balance = 0

# balance = 0 if balance < 0 else round(balance, 2)

print(end_date, balance)


days_in_current_month = calendar.monthrange(end_date.year, end_date.month)[1]
end_date = end_date + datetime.timedelta(days = days_in_current_month)

---------------------------------

2020-06-01 9998.33
2020-07-01 9996.65
2020-08-01 9994.95
2020-09-01 9993.23
2020-10-01 9991.49
2020-11-01 9989.73
2020-12-01 9987.95
2021-01-01 9986.15
2021-02-01 9984.33
2021-03-01 9982.49
2021-04-01 9980.63
2021-05-01 9978.75
2021-06-01 9976.85
2021-07-01 9974.93
2021-08-01 9972.99
2021-09-01 9971.03
2021-10-01 9969.05
2021-11-01 9967.05
2021-12-01 9965.03
2022-01-01 9962.98
2022-02-01 9960.91
2022-03-01 9958.82
2022-04-01 9956.71
2022-05-01 9954.57
2022-06-01 9952.41
2022-07-01 9950.23
2022-08-01 9948.02
2022-09-01 9945.79
2022-10-01 9943.54
2022-11-01 9941.26
2022-12-01 9938.96
2023-01-01 9936.63
2023-02-01 9934.28
2023-03-01 9931.9
2023-04-01 9929.5
2023-05-01 9927.07
2023-06-01 9924.61
2023-07-01 9922.13
2023-08-01 9919.62
2023-09-01 9917.08
2023-10-01 9914.52
2023-11-01 9911.93
2023-12-01 9909.31
2024-01-01 9906.66
2024-02-01 9903.98
2024-03-01 9901.27
2024-04-01 9898.53
2024-05-01 9895.76
2024-06-01 9892.96
2024-07-01 9890.13
2024-08-01 9887.27
2024-09-01 9884.38
2024-10-01 9881.46
2024-11-01 9878.51
2024-12-01 9875.53
2025-01-01 9872.51
2025-02-01 9869.46
2025-03-01 9866.38
2025-04-01 9863.27
2025-05-01 9860.12
2025-06-01 9856.94
2025-07-01 9853.72
2025-08-01 9850.47
2025-09-01 9847.18
2025-10-01 9843.86
2025-11-01 9840.5
2025-12-01 9837.11
2026-01-01 9833.68
2026-02-01 9830.21
2026-03-01 9826.7
2026-04-01 9823.16
2026-05-01 9819.58
2026-06-01 9815.96
2026-07-01 9812.3
2026-08-01 9808.6
2026-09-01 9804.86
2026-10-01 9801.08
2026-11-01 9797.26
2026-12-01 9793.4
2027-01-01 9789.5
2027-02-01 9785.55
2027-03-01 9781.56
2027-04-01 9777.53
2027-05-01 9773.45
2027-06-01 9769.33
2027-07-01 9765.16
2027-08-01 9760.95
2027-09-01 9756.69
2027-10-01 9752.39
2027-11-01 9748.04
2027-12-01 9743.64
2028-01-01 9739.2
2028-02-01 9734.71
2028-03-01 9730.17
2028-04-01 9725.58
2028-05-01 9720.94
2028-06-01 9716.25
2028-07-01 9711.51
2028-08-01 9706.72
2028-09-01 9701.88
2028-10-01 9696.98
2028-11-01 9692.03
2028-12-01 9687.03
2029-01-01 9681.97
2029-02-01 9676.86
2029-03-01 9671.69
2029-04-01 9666.47
2029-05-01 9661.19
2029-06-01 9655.85
2029-07-01 9650.46
2029-08-01 9645.01
2029-09-01 9639.5
2029-10-01 9633.93
2029-11-01 9628.3
2029-12-01 9622.61
2030-01-01 9616.85
2030-02-01 9611.03
2030-03-01 9605.15
2030-04-01 9599.21
2030-05-01 9593.2
2030-06-01 9587.13
2030-07-01 9580.99
2030-08-01 9574.78
2030-09-01 9568.51
2030-10-01 9562.17
2030-11-01 9555.76
2030-12-01 9549.28
2031-01-01 9542.73
2031-02-01 9536.11
2031-03-01 9529.42
2031-04-01 9522.66
2031-05-01 9515.82
2031-06-01 9508.91
2031-07-01 9501.92
2031-08-01 9494.86
2031-09-01 9487.72
2031-10-01 9480.5
2031-11-01 9473.21
2031-12-01 9465.84
2032-01-01 9458.39
2032-02-01 9450.86
2032-03-01 9443.24
2032-04-01 9435.54
2032-05-01 9427.76
2032-06-01 9419.89
2032-07-01 9411.94
2032-08-01 9403.9
2032-09-01 9395.78
2032-10-01 9387.57
2032-11-01 9379.27
2032-12-01 9370.88
2033-01-01 9362.4
2033-02-01 9353.83
2033-03-01 9345.16
2033-04-01 9336.4
2033-05-01 9327.54
2033-06-01 9318.59
2033-07-01 9309.54
2033-08-01 9300.39
2033-09-01 9291.14
2033-10-01 9281.79
2033-11-01 9272.34
2033-12-01 9262.79
2034-01-01 9253.14
2034-02-01 9243.38
2034-03-01 9233.52
2034-04-01 9223.55
2034-05-01 9213.47
2034-06-01 9203.28
2034-07-01 9192.98
2034-08-01 9182.57
2034-09-01 9172.05
2034-10-01 9161.41
2034-11-01 9150.66
2034-12-01 9139.79
2035-01-01 9128.8
2035-02-01 9117.7
2035-03-01 9106.48
2035-04-01 9095.13
2035-05-01 9083.66
2035-06-01 9072.07
2035-07-01 9060.35
2035-08-01 9048.5
2035-09-01 9036.53
2035-10-01 9024.43
2035-11-01 9012.19
2035-12-01 8999.82
2036-01-01 8987.32
2036-02-01 8974.68
2036-03-01 8961.91
2036-04-01 8949.0
2036-05-01 8935.95
2036-06-01 8922.76
2036-07-01 8909.42
2036-08-01 8895.94
2036-09-01 8882.31
2036-10-01 8868.54
2036-11-01 8854.62
2036-12-01 8840.55
2037-01-01 8826.32
2037-02-01 8811.94
2037-03-01 8797.4
2037-04-01 8782.71
2037-05-01 8767.86
2037-06-01 8752.85
2037-07-01 8737.67
2037-08-01 8722.33
2037-09-01 8706.82
2037-10-01 8691.14
2037-11-01 8675.29
2037-12-01 8659.27
2038-01-01 8643.08
2038-02-01 8626.71
2038-03-01 8610.17
2038-04-01 8593.45
2038-05-01 8576.55
2038-06-01 8559.46
2038-07-01 8542.19
2038-08-01 8524.73
2038-09-01 8507.08
2038-10-01 8489.24
2038-11-01 8471.21
2038-12-01 8452.98
2039-01-01 8434.55
2039-02-01 8415.92
2039-03-01 8397.09
2039-04-01 8378.06
2039-05-01 8358.82
2039-06-01 8339.37
2039-07-01 8319.71
2039-08-01 8299.84
2039-09-01 8279.75
2039-10-01 8259.45
2039-11-01 8238.93
2039-12-01 8218.19
2040-01-01 8197.22
2040-02-01 8176.02
2040-03-01 8154.59
2040-04-01 8132.93
2040-05-01 8111.04
2040-06-01 8088.91
2040-07-01 8066.54
2040-08-01 8043.93
2040-09-01 8021.07
2040-10-01 7997.96
2040-11-01 7974.6
2040-12-01 7950.99
2041-01-01 7927.13
2041-02-01 7903.01
2041-03-01 7878.63
2041-04-01 7853.98
2041-05-01 7829.06
2041-06-01 7803.87
2041-07-01 7778.41
2041-08-01 7752.68
2041-09-01 7726.67
2041-10-01 7700.38
2041-11-01 7673.8
2041-12-01 7646.93
2042-01-01 7619.77
2042-02-01 7592.32
2042-03-01 7564.57
2042-04-01 7536.52
2042-05-01 7508.17
2042-06-01 7479.51
2042-07-01 7450.54
2042-08-01 7421.25
2042-09-01 7391.65
2042-10-01 7361.73
2042-11-01 7331.48
2042-12-01 7300.9
2043-01-01 7269.99
2043-02-01 7238.75
2043-03-01 7207.17
2043-04-01 7175.25
2043-05-01 7142.98
2043-06-01 7110.36
2043-07-01 7077.39
2043-08-01 7044.06
2043-09-01 7010.37
2043-10-01 6976.32
2043-11-01 6941.9
2043-12-01 6907.1
2044-01-01 6871.93
2044-02-01 6836.38
2044-03-01 6800.44
2044-04-01 6764.11
2044-05-01 6727.39
2044-06-01 6690.27
2044-07-01 6652.75
2044-08-01 6614.82
2044-09-01 6576.48
2044-10-01 6537.73
2044-11-01 6498.56
2044-12-01 6458.96
2045-01-01 6418.93
2045-02-01 6378.47
2045-03-01 6337.57
2045-04-01 6296.23
2045-05-01 6254.44
2045-06-01 6212.2
2045-07-01 6169.5
2045-08-01 6126.34
2045-09-01 6082.71
2045-10-01 6038.61
2045-11-01 5994.03
2045-12-01 5948.97
2046-01-01 5903.42
2046-02-01 5857.37
2046-03-01 5810.82
2046-04-01 5763.77
2046-05-01 5716.21
2046-06-01 5668.14
2046-07-01 5619.54
2046-08-01 5570.42
2046-09-01 5520.77
2046-10-01 5470.58
2046-11-01 5419.84
2046-12-01 5368.55
2047-01-01 5316.71
2047-02-01 5264.31
2047-03-01 5211.34
2047-04-01 5157.8
2047-05-01 5103.68
2047-06-01 5048.97
2047-07-01 4993.67
2047-08-01 4937.77
2047-09-01 4881.26
2047-10-01 4824.14
2047-11-01 4766.4
2047-12-01 4708.04
2048-01-01 4649.04
2048-02-01 4589.4
2048-03-01 4529.12
2048-04-01 4468.19
2048-05-01 4406.6
2048-06-01 4344.34
2048-07-01 4281.4
2048-08-01 4217.78
2048-09-01 4153.47
2048-10-01 4088.47
2048-11-01 4022.76
2048-12-01 3956.34
2049-01-01 3889.2
2049-02-01 3821.33
2049-03-01 3752.73
2049-04-01 3683.38
2049-05-01 3613.28
2049-06-01 3542.42
2049-07-01 3470.8
2049-08-01 3398.4
2049-09-01 3325.22
2049-10-01 3251.24
2049-11-01 3176.46
2049-12-01 3100.87
2050-01-01 3024.46
2050-02-01 2947.22
2050-03-01 2869.15
2050-04-01 2790.23
2050-05-01 2710.46
2050-06-01 2629.82
2050-07-01 2548.31
2050-08-01 2465.92
2050-09-01 2382.63
2050-10-01 2298.44
2050-11-01 2213.34
2050-12-01 2127.32
2051-01-01 2040.37
2051-02-01 1952.47
2051-03-01 1863.62
2051-04-01 1773.81
2051-05-01 1683.03
2051-06-01 1591.26
2051-07-01 1498.5
2051-08-01 1404.73
2051-09-01 1309.95
2051-10-01 1214.14
2051-11-01 1117.29
2051-12-01 1019.39
2052-01-01 920.43
2052-02-01 820.4
2052-03-01 719.29
2052-04-01 617.08
2052-05-01 513.77
2052-06-01 409.34
2052-07-01 303.77
2052-08-01 197.06
2052-09-01 89.19
2052-10-01 0

---------------------------------

==========================================


import datetime

current_weight = 220
goal_weight = 180
avg_lbs_week = 1.5

start_date = datetime.date.today()
end_date = start_date

while current_weight > goal_weight:
end_date += datetime.timedelta(days = 7)
current_weight -= avg_lbs_week

print(f'Reached goal in {(end_date - start_date).days // 7} weeks')

---------------------------------

Reached goal in 27 weeks

---------------------------------

==========================================

import datetime

current_weight = 220
goal_weight = 180
avg_lbs_week = 1.5

start_date = datetime.date.today()
end_date = start_date

while current_weight > goal_weight:
end_date += datetime.timedelta(days = 7)
current_weight -= avg_lbs_week

print(end_date)
print(f'Reached goal in {(end_date - start_date).days // 7} weeks')


---------------------------------

2020-11-22
Reached goal in 27 weeks

---------------------------------

==========================================

import datetime

current_weight = 220
goal_weight = 180
avg_lbs_week = 2

start_date = datetime.date.today()
end_date = start_date

while current_weight > goal_weight:
end_date += datetime.timedelta(days = 7)
current_weight -= avg_lbs_week

print(end_date)
print(f'Reached goal in {(end_date - start_date).days // 7} weeks')

---------------------------------

2020-10-04
Reached goal in 20 weeks

---------------------------------

==========================================

import datetime
import math

goal_subs = 100000
current_subs = 85000
subs_to_go = goal_subs - current_subs

avg_subs_day = 200
days_to_go = math.ceil(subs_to_go / avg_subs_day)

today = datetime.date.today()

print(today + datetime.timedelta(days = days_to_go))

---------------------------------

2020-07-31

---------------------------------

==========================================

import datetime
import math

goal_subs = 150000
current_subs = 85000
subs_to_go = goal_subs - current_subs

avg_subs_day = 200
days_to_go = math.ceil(subs_to_go / avg_subs_day)

today = datetime.date.today()

print(today + datetime.timedelta(days = days_to_go))

---------------------------------

2021-04-07

---------------------------------