Some basics in Python before you start with DoE

Tools like ChatGPT have democratized access to programming knowledge and tools, enabling learners from diverse backgrounds to explore the realm of coding without needing a formal computer science education.

However, while these tools can guide you through coding challenges, a solid understanding of the foundational programming concepts is still crucial. It enables you to think critically and to solve problems creatively.

Variables

A variable in Python is like a box you can put stuff in. You give the box a name, and then you can use that name to get the stuff back out again.

Here’s how you might assign a value to a variable:

my_number = 10
my_name = "Alex"

In this example, my_number is a variable that stores the integer 10, and my_name is a variable that stores the string "Alex".

Data Types

Python has several built-in data types. The most common ones you'll encounter are:

  • Integers (int): Whole numbers like 3, 42, or 2048.
  • Floating-point numbers (float): Numbers with a decimal point, like 3.14, 0.001, or 2.0.
  • Strings (str): Sequences of characters, used for text. You define them by surrounding your text with quotes, as in "hello" or 'world'.
  • Booleans (bool): Represents True or False values, useful for conditional and comparison operations.
age = 30               # This is an integer
temperature = 98.6     # This is a float
name = "Jamie"         # This is a string
is_adult = True        # This is a boolean
  • Single-line Comments: start with the hash symbol #. Everything following the # on that line is considered a comment and is ignored by the Python interpreter.
# This is a single-line comment in Python
print("Hello, world!")  # This comment is inline with code
  • Multi-line Comments: Python does not have a specific way to denote multi-line comments directly. However, you can use triple quotes (''' or """) to create a string that spans multiple lines, and if not assigned to a variable, it can serve a similar purpose. While technically these are multi-line strings, they're often used as a workaround for multi-line comments.
"""
This is a multi-line comment
using triple quotes. It spans
several lines.
"""
print("Hello, world!")

Operators

Arithmetic Operators

Used for performing mathematical operations like addition, subtraction, multiplication, and division.

  • + Addition: Adds two operands. E.g., 5 + 3 equals 8.
  • `` Subtraction: Subtracts the second operand from the first. E.g., 10 - 2 equals 8.
  • `` Multiplication: Multiplies two operands. E.g., 4 * 7 equals 28.
  • / Division: Divides the first operand by the second. E.g., 20 / 4 equals 5.0 (note the result is a float).
  • * Exponentiation: Raises the first operand to the power of the second. E.g., 2 ** 3 equals 8.

Comparison Operators

Used for comparing two values and returns a boolean value (True or False).

  • == Equal to: Checks if the values of two operands are equal. E.g., 5 == 5 is True.
  • != Not equal to: Checks if the values of two operands are not equal. E.g., 5 != 2 is True.
  • > Greater than: Checks if the value of the left operand is greater than the value of the right operand. E.g., 7 > 5 is True.
  • < data-preserve-html-node="true" Less than: Checks if the value of the left operand is less than the value of the right operand. E.g., 2 < 5 is True.
  • >= Greater than or equal to: Checks if the value of the left operand is greater than or equal to the value of the right operand. E.g., 5 >= 5 is True.
  • <= data-preserve-html-node="true" Less than or equal to: Checks if the value of the left operand is less than or equal to the value of the right operand. E.g., 3 <= 4 is True.

Logical Operators

Used to combine conditional statements.

  • and Returns True if both statements are true. E.g., (5 > 3) and (6 > 4) is True.
  • or Returns True if one of the statements is true. E.g., (5 > 3) or (5 < 3) is True.
  • not Reverses the result, returns False if the result is true. E.g., not(5 > 3) is False.

Conditional Statements

Conditional statements allow your program to execute different blocks of code based on certain conditions.

  • if Statement: It runs the code inside it if the condition is True.
if condition:
    # code to execute if condition is True
  • else Statement: Follows an if statement and contains code that runs if the if statement's condition is False.
if condition:
    # code to execute if condition is True
else:
    # code to execute if condition is False
  • elif Statement (short for "else if"): Allows you to check multiple conditions after the initial if condition. If the if condition is False, it checks the condition of the elif, and so on.
if condition:
    # code to execute if condition is True
elif another_condition:
    # code to execute if the another_condition is True
else:
    # code to execute if all above conditions are False

Loops

Loops allow you to execute a block of code repeatedly.

  • while Loop: Repeats a block of code as long as a condition is True.
while condition:
    # code to execute repeatedly while condition is True
  • for Loop: Iterates over a sequence (like a list, tuple, dictionary, or string) and executes a block of code for each item in the sequence.
for item in sequence:
    # code to execute for each item in sequence

Loop Control Statements

  • break: Exits the loop immediately, regardless of the iteration number.
  • continue: Skips the rest of the code inside the loop for the current iteration and moves to the next iteration.
  • pass: Does nothing; used as a placeholder for future code.

Functions

Functions in Python are a way to organize your code into blocks that can perform specific tasks and can be reused throughout your program. They help make your code more readable, maintainable, and testable. Let's explore the basics of functions:

Defining a Function

A function is defined using the def keyword, followed by a function name, parentheses () which may include parameters, and a colon :. The indented block of code following the : is run whenever the function is called.

def my_function():
    print("Hello from a function!")

Parameters and Arguments

Parameters are variables listed inside the parentheses in the function definition. Arguments are the values you pass into the function's parameters when you call it.

def greet(name):
    print(f"Hello, {name}!")

greet("Alice")  # Prints "Hello, Alice!"

Return Values

Functions can send Python values/objects back to the caller. This is done using the return statement. A function stops executing when it hits a return statement.

def add(a, b):
    return a + b

result = add(5, 3)
print(result)  # Prints "8"

Default Parameter Values

You can assign default values to parameters. If the argument is omitted when the function is called, the parameter uses the default value.

def greet(name="World"):
    print(f"Hello, {name}!")

greet()            # Prints "Hello, World!"
greet("Everybody") # Prints "Hello, Everybody!"

Keyword Arguments

When you call a function, you can specify arguments by naming the parameter followed by its value. This allows you to skip arguments or place them out of order because the Python interpreter will match the values with parameters by name.

def describe_pet(animal_type, pet_name):
    print(f"I have a {animal_type} named {pet_name}.")

describe_pet(pet_name="Harry", animal_type="hamster")

Lists

A list in Python is an ordered collection of items. Lists are mutable, meaning you can modify them after they have been created. They can hold items of any data type, and items in a list are separated by commas and enclosed in square brackets [].

Creating a List

my_list = [1, "Hello", 3.14]

Accessing List Items

Items in a list can be accessed by their index, starting from 0 for the first item.

print(my_list[1])  # Outputs: Hello

Modifying Lists

You can add, remove, or change items in a list.

  • Adding: Use append() to add an item to the end of a list, or insert() to add it at a specific position.
  • Removing: Use remove() to remove an item by value, or pop() to remove an item by index.

Example

my_list.append("Python")
my_list.pop(0)  # Removes the first item
print(my_list)  # Outputs: ["Hello", 3.14, "Python"]

Dictionaries

A dictionary in Python is an unordered collection of items. While other compound data types have only value as an element, a dictionary has a key: value pair. Dictionaries are enclosed by curly braces {} and values can be assigned and accessed using square brackets [].

Creating a Dictionary

my_dict = {"name": "Alice", "age": 25}

Accessing Dictionary Items

You can access the value of a specific item by referring to its key name.

print(my_dict["name"])  # Outputs: Alice

Modifying Dictionaries

  • Adding/Updating: Assign a value to a new key to add an item, or to an existing key to update that item.
  • Removing: Use pop() to remove an item by key, or del to remove an item or the dictionary itself.

Example

my_dict["age"] = 26  # Updates Alice's age
my_dict["email"] = "alice@example.com"  # Adds a new key-value pair
del my_dict["name"]  # Removes the name key
print(my_dict)  # Outputs: {'age': 26, 'email': 'alice@example.com'}

Packages

Packages in Python are collections of pre-written code that include for example functions, which someone else has developed to perform specific tasks. These packages can make your life significantly easier because you do not have to reinvent the wheel and since python is an open source programming language with a big community behind it, there are a lot of these packages.

One example is the pyDOE2 package that we can use to plan our DoE’s. If this package did not exist, you had to come up with the following code to generate a full factorial design.

In Python, packages are comprehensive collections of pre-written code, including functions developed by others to execute particular tasks. These packages can greatly simplify your programming efforts, eliminating the need to "reinvent the wheel." Thanks to Python's open-source nature and its vast, supportive community, there's a rich ecosystem of packages available for almost any application you can imagine.

Take, for example, the pyDOE2 package, which is specifically designed for creating experimental designs. Without it, you would have to manually write intricate code to e.g. generate a full factorial design like this:

def fullfact(levels):
    """
    Create a general full-factorial design

    Parameters
    ----------
    levels : array-like
        An array of integers that indicate the number of levels of each input
        design factor.

    Returns
    -------
    mat : 2d-array
        The design matrix with coded levels 0 to k-1 for a k-level factor

"""

    n = len(levels)  # number of factors
    nb_lines = np.prod(levels)  # number of trial conditions
    H = np.zeros((nb_lines, n))

    level_repeat = 1
    range_repeat = np.prod(levels)
    for i in range(n):
        range_repeat //= levels[i]
        lvl = []
        for j in range(levels[i]):
            lvl += [j]*level_repeat
        rng = lvl*range_repeat
        level_repeat *= levels[i]
        H[:, i] = rng

    return H

But since this work already has been done by somebody else, we can just use the pyDOE2 package and write:

import pyDOE2

# Create a 2-level factorial design
design = pyDOE2.fullfact([2, 2, 2])  # Assuming 3 factors, each with 2 levels
print(design)

Installing packages

Before using a package for the first time, you need to install it once. You can do so directly from your Jupyter Notebook, running the following command:

!pip install package_name

For example:

!pip install pyDOE2

After that, you only need to import your packages once at the beginning of your Jupyter Notebooks.

import package_name
import pyDOE2

Further reading

Python Data Science Handbook by Jake VanderBlas

Go through the basics together with ChatGPT:

Previous
Previous

Create a full factorial design in DoE with Python

Next
Next

Getting started with Python for DoE