Types

Overview


Version

  • Let’s find out what version is loaded on our system
import sys
print(sys.version)
3.12.2 (tags/v3.12.2:6abddd9, Feb  6 2024, 21:26:36) [MSC v.1937 64 bit (AMD64)]

Error

Python is what is called an interpreted language.

  • Compiled languages examine your entire program at compile time, and are able to warn you about a whole class of errors prior to execution.
  • In contrast, Python interprets your script line by line as it executes it. Python will stop executing the entire program when it encounters an error

Infinite Loop

If you ever catch yourself in an infinite loop, use CTRL+C to stop the script from running

Type


We can find the type of an object by using type()

Int

  • Non-decimal numbers, negative or positive

Float

  • Numbers including integers and in-between the integers: decimals
  • Floats represent real numbers; they are a superset of integer numbers but also include “numbers with decimals”.

Str

  • Is a non-integer or a non-float object. It’s a sequence of characters
  • We can use indexing to access each object in the sequence

Boolean

  • Takes on two values: True (T) or False(F)

Convert

  • You can convert a type by type casting
  • All you do is use the type of the object you want to convert to and the object inside the ()
  • Just remember that converting a float to an integer might cause you to lose accuracy
  • You can convert a string if it contains an integer value to an integer
  • You can convert an integer or a float to a string
  • If you cast int(True)->1, int(False)->0
float(45) = 45.0
int(974.75) = 974
int(3.99) = 3
int('34') = 34
str(1) = '1'
str(89.75) = '89.75'
bool(1) = True
type(False) = 'bool'
float(True) = 1.0
type(6/2) = float
type(6//2) = int
type("hello" == "world") = bool

Expressions & Variables


Expression

Is a type of operation the computer performs, like adding multiple numbers where the numbers are operands, and the math symbols are operators.

  • In Python 3 divisions will result in a float unless a double slash is used // which indicates an integer division 25//6 = 4
  • Python will always perform multiplications before other operations unless specified by parenthesis, that’s when operations inside the parenthesis are performed first

Variables

Variables are used to store values and we assign values to variable using the assign = operator my_variable = 89, now my_variable has been assigned the value 89 indicated like this: my_variable:89

Operators

  • +, -, *
  • / divides one value by another, returns a float
  • // floor division divides one value by another, returns the quotient as an integer
  • % modulo returns the remainder after division

Methods


Methods will be covered later but to summarize: Methods are stored functions/procedures/subroutines, subroutines haven’t been used since the Fortran days, but basically they are stored procedures we can access by using the .methodname()

To access the extend method we use: listname.extend()

Static Code Analysis


Pylint

Static code analysis, or static analysis, is an application code efficiency verification activity that analyses source code for quality, reliability, and security without executing the code. Static code analysis is an essential part of any application development cycle and is available as a part of multiple frameworks with Python.

One of the most popular frameworks is PyLint. PyLint basically evaluates the code against compliance with the PEP8 coding style guide and generates comments wherever it finds an issue.

  • First thing, is you have to install pylint
  • Then look at the example below
pip install pylint

# Define a function named 'add' that takes two arguments, 'number1' and 'number2'.
def add(number1, number2):
    # The function returns the sum of 'number1' and 'number2'.
    return number1 + number2

# Initialize the variable 'num1' with the value 4.
num1 = 4

# Initialize the variable 'num2' with the value 5.
num2 = 5

# Call the 'add' function with 'num1' and 'num2' as arguments and store the result in 'total'.
total = add(num1, num2)

# Print the result of adding 'num1' and 'num2' using the 'format' method to insert the values into the string.
print("The sum of {} and {} is {}".format(num1, num2, total))
  • Back at the terminal execute the code you just wrote and saved in file: sample1.py
 pylint sample1.py
  • After running pylint you are provided with warnings

  • Based on the report given by pylint changes were made to this code to address the following issues.

    • Exactly one space required after comma
    • Exactly one space required around assignment
    • Make the corrections, save the file in sample2.py and run it again
    • Here is the corrected script
    # Define a function named 'add' that takes two arguments, 'number1' and 'number2'.
    # The purpose of this function is to add the two numbers and return the result.
    def add(number1, number2):
        # Return the sum of 'number1' and 'number2'.
        # This line computes the addition of the two input numbers and outputs the result.
        return number1 + number2
    
    # Initialize the constant variable 'NUM1' with the value 4.
    # Constants are usually written in uppercase letters to indicate that they should not be changed.
    NUM1 = 4
    
    # Initialize the variable 'num2' with the value 5.
    # This variable will be used as the second input to the 'add' function.
    num2 = 5
    
    # Call the 'add' function with 'NUM1' and 'num2' as arguments.
    # The result of this addition operation is stored in the variable 'total'.
    total = add(NUM1, num2)
    
    # Print a formatted string that displays the sum of 'NUM1' and 'num2'.
    # The 'format' method is used to insert the values of 'NUM1', 'num2', and 'total' into the string.
    print("The sum of {} and {} is {}".format(NUM1, num2, total))

Unit Testing


Create Module

  • Let’s create a file: mymodule.py
  • Create two simple functions
def square(number):
    """
    This function returns the square of a given number
    """
    return number ** 2

def double(number):
    """
    This function returns twice the value of a given number
    """
    return number * 2
  • Let’s write test cases for square function, let’s imagine three scenarios:
    • when 2 is given as input, output must be 4
    • when 3.0 is given as input, output must be 9.0
    • when -3 is given as input, output must be -9
  • Let us write test cases for double function, with these three scenarios:
    • When 2 is given as input the output must be 4.
    • When -3.1 is given as input the output must be -6.2.
    • When 0 is given as input the output must be 0.

Create Test Script

Create a new file and call it test_module.py

# Import the 'unittest' module to create unit tests for your code.
import unittest

# Import the 'square' and 'double' functions from the 'mymodule' module.
from mymodule import square, double

# Define a test case class for testing the 'square' function.
# A test case is a single unit of testing. It checks a specific aspect of the code's behavior.
class TestSquare(unittest.TestCase): 

    # Define the first test method for the 'square' function.
    # Test methods should start with the word 'test' so that the test runner recognizes them as test cases.
    def test1(self): 
        # Check that calling 'square(2)' returns 4.
        # This tests if the function correctly computes the square of 2.
        self.assertEqual(square(2), 4) # test when 2 is given as input the output is 4.

        # Check that calling 'square(3.0)' returns 9.0.
        # This tests if the function correctly computes the square of 3.0, verifying that it handles float inputs.
        self.assertEqual(square(3.0), 9.0)  # test when 3.0 is given as input the output is 9.0.

        # Check that calling 'square(-3)' does not return -9.
        # This tests that the function's output is not -9, verifying that the square of -3 should be 9.
        self.assertNotEqual(square(-3), -9)  # test when -3 is given as input the output is not -9.

# Define a test case class for testing the 'double' function.
class TestDouble(unittest.TestCase): 

    # Define the first test method for the 'double' function.
    def test1(self): 
        # Check that calling 'double(2)' returns 4.
        # This tests if the function correctly computes double of 2.
        self.assertEqual(double(2), 4) # test when 2 is given as input the output is 4.

        # Check that calling 'double(-3.1)' returns -6.2.
        # This tests if the function correctly computes double of -3.1, verifying that it handles negative float inputs.
        self.assertEqual(double(-3.1), -6.2) # test when -3.1 is given as input the output is -6.2.

        # Check that calling 'double(0)' returns 0.
        # This tests if the function correctly computes double of 0, verifying that the function works for edge cases.
        self.assertEqual(double(0), 0) # test when 0 is given as input the output is 0.
        
# Run all the test cases defined in the module when the script is executed.
# This will automatically discover and run all the test cases defined in the module.
unittest.main()

Run Test

  • Go to new terminal
  • make sure you’re in the same directory where test_mymodule.py is located
  • run it
  • an OK in the last line indicates that all tests passed
  • FAILED and python will print which tests failed
python3 test_mymodule.py

Summary of Packaging, Testing, Static Code


Package/Method Description Code Example
Packaging

To create a package, the folder structure is as follows:

  1. Project folderPackage nameinit.py, module_1.py, module_2.py, and so on.

  2. In the init.py file, add code to reference the modules in the package.

module1.py

def function_1(arg):

    return <operation output>

init.py:

from . import function_1

Python Style Guide
  • Four spaces for indentation

  • Use blank lines to separate functions and classes

  • Use spaces around operators and after commas

  • Add larger blocks of code inside functions

  • Name functions and files using lowercase with underscores

  • Name classes using CamelCase

  • Name constants in capital letters with underscores separating words

def function_1(a, b):

     if a > b:

         c = c + 5

    else:

        c = c - 3

    return c

c = function_1(a, b)

Constant Definition example

MAX_FILE_UPLOAD_SIZE

Static Code Analysis

Use Static code analysis method to evaluate your code against a predefined style and standard without executing the code.

For example, use Pylint to perform static code analysis.

Shell code:

pylint code.py

Unit Testing

Unit testing is a method to validate if units of code are operating as designed.

During code development, each unit is tested. The unit is tested in a continuous integration/continuous delivery test server environment.

You can use different test functions to build unit tests and review the unit test output to determine if the test passed or failed.

import unittest

from mypackage.mymodule import my_function

class TestMyFunction(unittest.TestCase):

    def test_my_function(self):

        result = my_function(<args>)

        self.asserEqual(result, <response>)

unittest.main()