Beginner

Python Data Essentials: Programming Fundamentals

Conditionals, loops, functions and object-oriented basics to prepare for pandas and NumPy.

Objective: Acquire essential Python programming fundamentals to start data analysis with libraries like Pandas and NumPy.


Table of Contents

  1. Course Overview
  2. Conditional Statements and Boolean Values
  3. Implementing Loops
  4. Code Reuse with Functions
  5. Grouping Data and Functions in Objects (OOP)
  6. Reference Diagrams
  7. Reference Tables

1. Course Overview

This course targets complete beginners who want to acquire the minimum Python fundamentals to work with data analysis libraries. It covers control flow, functions, and classes — the pillars of Python.

Prerequisites:
Knowledge of basic types: int, float, str, list, dict, tuple, set.

Tools used:

  • Python runtime
  • VS Code or any IDE
  • Jupyter Notebooks (.ipynb)

2. Conditional Statements and Boolean Values

2.1 Boolean Types

In Python, the bool type can only hold two values: True or False. These values represent logical states for making decisions in code.

balance = 150.0

if balance > 0:
    print("Account has funds.")

Python evaluates statements top to bottom, line by line.

2.2 Truthy and Falsy Values

Python allows implicit conversion of any value to a boolean. This defines truthy (treated as True) and falsy (treated as False) concepts.

Valuebool() result
NoneFalse
0, 0.0False
"" (empty string)False
[] (empty list)False
{} (empty dict)False
() (empty tuple)False
Any number ≠ 0True
Any non-empty collectionTrue
print(bool(None))      # False
print(bool(0))         # False
print(bool(""))        # False
print(bool([]))        # False

print(bool(42))        # True
print(bool("hello"))   # True
print(bool([1, 2, 3])) # True

2.3 Comparison Operators

OperatorDescriptionExampleResult
<Less than3 < 5True
>Greater than3 > 5False
<=Less than or equal3 <= 3True
>=Greater than or equal5 >= 3True
==Equal to3 == 3True
!=Not equal to3 != 5True
balance = float(input("What is your bank account balance? "))

if balance < 0:
    print("You are in debt.")

2.4 else and elif Statements

balance = float(input("What is your bank account balance? "))

if balance < 0:
    print("You are in debt.")
else:
    print("You are not in debt.")
    if balance < 2000:
        print("You cannot ask for a loan.")
    else:
        print("You can ask for a loan.")

With elif:

score = int(input("Enter your score: "))

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: F")

2.5 Logical Operators

OperatorDescriptionExampleResult
andTrue if both conditions are trueTrue and FalseFalse
orTrue if at least one condition is trueTrue or FalseTrue
notInverts boolean valuenot TrueFalse
age = 25
has_id = True

if age >= 18 and has_id:
    print("Access granted.")

is_member = False
has_coupon = True

if is_member or has_coupon:
    print("Discount applied.")

is_logged_in = False
if not is_logged_in:
    print("Please log in.")

3. Implementing Loops

3.1 The while Loop

The while loop executes a code block as long as its condition is true.

print("Grocery list program")
grocery_list = []
user_input = None

while user_input != "end":
    user_input = input("Input an item (type 'end' to finish): ")
    if user_input != "end":
        grocery_list.append(user_input)

print("Here is your grocery list:")
print(grocery_list)

3.2 Iterables

An iterable is any object you can iterate over. Python iterables include: list, tuple, dict, set, str.

3.3 The for Loop

The for loop is the preferred method for iterating over sequences.

grocery_list = ["apples", "bread", "milk"]

for item in grocery_list:
    print(item)

# With enumerate() to get index and value
for index, item in enumerate(grocery_list):
    print(f"{index}: {item}")

# Iterating over a dictionary
prices = {"apples": 1.5, "bread": 2.0, "milk": 3.0}

for name, price in prices.items():
    print(f"{name}: {price}")

3.4 The range() Function

for i in range(5):
    print(i)  # 0, 1, 2, 3, 4

# range(start, stop, step)
for i in range(0, 10, 2):
    print(i)  # 0, 2, 4, 6, 8

print(list(range(5)))  # [0, 1, 2, 3, 4]

3.5 The break Statement

break immediately exits the loop.

grocery_list = []

while True:
    user_input = input("Input an item (type 'end' to finish): ")
    if user_input == "end":
        break
    grocery_list.append(user_input)

for item in grocery_list:
    print(f"{item}")

continue skips the current iteration and moves to the next, without exiting the loop.

3.6 for-else and while-else Loops

In Python, loops can have an else block. It executes only if the loop completed normally (no break).

grocery_list = ["apples", "milk", "eggs"]

for item in grocery_list:
    if item == "bread":
        print("Bread is on the list!")
        break
else:
    print("Bread is not on the list.")

4. Code Reuse with Functions

4.1 Defining a Function

A function is a named, reusable code block. Defined with the def keyword.

def print_separator():
    print("-" * 80)

print_separator()

Naming convention: snake_case (lowercase + underscores), descriptive name.

4.2 Arguments and Parameters

Parameters are variables defined in the function signature. Arguments are values passed at call time.

def find_in_list(some_list, item_name="bread"):
    """Search for an item in a list."""
    for item in some_list:
        if item == item_name:
            print(f"{item_name} is on the list!")
            break
    else:
        print(f"{item_name} is not on the list!")

find_in_list(grocery_list, "carrots")    # positional argument
find_in_list(grocery_list)               # uses default value "bread"
find_in_list(item_name="carrots", some_list=grocery_list)  # keyword args
Parameter TypeSyntaxDescription
Positionaldef f(x, y)Order required
Default valuedef f(x, y=10)Optional at call
Keyword argumentf(y=5, x=3)Free order at call

4.3 Variadic Functions

def find_in_list(some_list, *item_names):
    for item_name in item_names:
        for item in some_list:
            if item == item_name:
                print(f"{item_name} is on the list!")
                break
        else:
            print(f"{item_name} is not on the list.")

find_in_list(grocery_list, "potatoes", "carrots", "bread")
# *args: tuple of all extra positional arguments
def demo_args(x, *args):
    print(f"x = {x}")
    print(f"args = {args}")

demo_args("a", "b", "c", "d")
# x = a
# args = ('b', 'c', 'd')

# **kwargs: dict of all extra keyword arguments
def demo_kwargs(**kwargs):
    print(kwargs)

demo_kwargs(name="Alice", balance=20000)
# {'name': 'Alice', 'balance': 20000}

4.4 Return Values

def groceries_total_cost(grocery_list):
    total_cost = 0
    for item_price in grocery_list.values():
        total_cost += item_price
    return total_cost

grocery_list = {"apples": 1.5, "bread": 2.0, "milk": 3.0}
price = groceries_total_cost(grocery_list)
print("Total amount:", price)  # 6.5

4.5 Mutability and Pass by Reference

# Immutable object: x is not modified
def add_two(num):
    num += 2
    return num

x = 2
add_two(x)
print(x)  # 2 — x unchanged

# Mutable object: list is modified directly
def append_item(some_list, item):
    some_list.append(item)

my_list = [1, 2, 3]
append_item(my_list, 4)
print(my_list)  # [1, 2, 3, 4] — modified!
TypeExamplesPassingExternal modification
Immutableint, float, str, tupleBy value (copy)No
Mutablelist, dict, setBy referenceYes

4.6 Built-in Functions and Imports

# Built-in functions
len([1, 2, 3])       # 3
type(42)             # <class 'int'>
int("42")            # 42
float("3.14")        # 3.14
list(range(5))       # [0, 1, 2, 3, 4]
sorted([3, 1, 2])    # [1, 2, 3]
sum([1, 2, 3])       # 6
max([1, 5, 3])       # 5

# Import from module
from random import randint
random_number = randint(1, 100)
print(random_number)

5. Grouping Data and Functions in Objects (OOP)

5.1 Object-Oriented Paradigm in Python

ParadigmDescription
ProceduralCode structured around separate functions and data
Object-orientedCode structured around objects encapsulating data and behavior

A class is a blueprint for creating objects. Each object created is an instance of the class.

5.2 Creating Objects with __init__

class BankAccount:
    def __init__(self, name, number, balance):
        self.name = name
        self.number = number
        self.balance = balance

account1 = BankAccount("Alice", "021000012", 20000)
account2 = BankAccount("Bob", "001302933", 32000)

print(account1.name)     # Alice
print(account2.balance)  # 32000

self is a reference to the current instance. Always the first parameter of instance methods.

5.3 Adding Methods

class BankAccount:
    def __init__(self, name, number, balance):
        self.name = name
        self.number = number
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount

    def withdraw(self, amount):
        if self.balance >= amount:
            self.balance -= amount
        else:
            print("Insufficient funds.")

    def info(self):
        return f"{self.name} {self.number} {self.balance}"

account = BankAccount("Alice", "021000012", 20000)
print(account.info())     # Alice 021000012 20000
account.deposit(5000)
account.withdraw(100000)  # Insufficient funds.
print(account.info())     # Alice 021000012 25000

5.4 Everything is an Object in Python

In Python, everything is an object — integers, strings, lists, functions. Every object has methods accessible via dot notation.

OOP refactoring of a procedural program:

class GroceryList:
    def __init__(self, name):
        self.name = name
        self.items = {}  # dict {item_name: price}

    def add_item(self):
        while True:
            item_name = input("Input an item (type 'end' to finish): ")
            if item_name == "end":
                break
            price = float(input("Input an item's price: "))
            self.items[item_name] = price

    def display(self):
        print(f"\nGrocery list: {self.name}")
        print("-" * 40)
        for name, price in self.items.items():
            print(f"  {name}: ${price:.2f}")

    def total_cost(self):
        return sum(self.items.values())

    def find_item(self, item_name):
        if item_name in self.items:
            print(f"{item_name} is on the list!")
        else:
            print(f"{item_name} is not on the list.")

my_list = GroceryList("Weekly Shopping")
my_list.add_item()
my_list.display()
print(f"Total: ${my_list.total_cost():.2f}")
my_list.find_item("bread")

5.5 Using Third-Party Library Classes

import pandas as pd

grocery_data = {
    "item": ["apples", "bread", "milk"],
    "price": [1.5, 2.0, 3.0]
}

df = pd.DataFrame(grocery_data)
print(df)

print(df["price"].sum())  # 6.5

6. Reference Diagrams

Python Control Flow

flowchart TD
    A([Program Start]) --> B[Statement 1]
    B --> C{if condition}
    C -- True --> D[if block]
    C -- False --> E{elif?}
    E -- True --> F[elif block]
    E -- False --> G[else block]
    D --> H[Rest of program]
    F --> H
    G --> H
    H --> I{while condition}
    I -- True --> J[Loop body]
    J --> K{break?}
    K -- Yes --> L[Exit loop]
    K -- No --> I
    I -- False --> L

Function Anatomy

flowchart LR
    subgraph DEF[Function Definition]
        direction TB
        N[def function_name] --> P[parameters]
        P --> B[function body]
        B --> R[return value]
    end

    subgraph CALL[Function Call]
        direction TB
        A[arguments] --> F[function_name]
        F --> RES[result]
    end

    DEF --> CALL

7. Reference Tables

Python Data Types

TypeMutableExampleEmpty
intNo420
floatNo3.140.0
strNo"hello"""
boolNoTrueFalse
listYes[1, 2, 3][]
dictYes{"a": 1}{}
setYes{1, 2, 3}set()
tupleNo(1, 2, 3)()

Control Flow Summary

StatementSyntaxPurpose
ifif condition:Conditional execution
elseelse:Default branch
elifelif condition:Additional conditions
whilewhile condition:Loop while true
forfor item in iterable:Iterate over sequence
breakbreakExit loop immediately
continuecontinueSkip to next iteration
returnreturn valueExit function with value

OOP Concepts

ConceptPythonDescription
Classclass MyClass:Blueprint for objects
Constructordef __init__(self, ...)Initializes instance
Instanceobj = MyClass(...)Object created from class
Attributeself.name = valueInstance data
Methoddef my_method(self):Instance behavior
Dot notationobj.attribute / obj.method()Access members

Search Terms

python · data · essentials · programming · fundamentals · foundations · analysis · engineering · analytics · functions · function · reference · values · boolean · control · flow · loop · loops · objects · oop · operators · statements · types

Interested in this course?

Contact us to book it or get a custom training plan for your team.