Objective: Acquire essential Python programming fundamentals to start data analysis with libraries like Pandas and NumPy.
Table of Contents
- Course Overview
- Conditional Statements and Boolean Values
- Implementing Loops
- Code Reuse with Functions
- Grouping Data and Functions in Objects (OOP)
- Reference Diagrams
- 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.
| Value | bool() result |
|---|---|
None | False |
0, 0.0 | False |
"" (empty string) | False |
[] (empty list) | False |
{} (empty dict) | False |
() (empty tuple) | False |
| Any number ≠ 0 | True |
| Any non-empty collection | True |
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
| Operator | Description | Example | Result |
|---|---|---|---|
< | Less than | 3 < 5 | True |
> | Greater than | 3 > 5 | False |
<= | Less than or equal | 3 <= 3 | True |
>= | Greater than or equal | 5 >= 3 | True |
== | Equal to | 3 == 3 | True |
!= | Not equal to | 3 != 5 | True |
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
| Operator | Description | Example | Result |
|---|---|---|---|
and | True if both conditions are true | True and False | False |
or | True if at least one condition is true | True or False | True |
not | Inverts boolean value | not True | False |
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}")
continueskips 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 Type | Syntax | Description |
|---|---|---|
| Positional | def f(x, y) | Order required |
| Default value | def f(x, y=10) | Optional at call |
| Keyword argument | f(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!
| Type | Examples | Passing | External modification |
|---|---|---|---|
| Immutable | int, float, str, tuple | By value (copy) | No |
| Mutable | list, dict, set | By reference | Yes |
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
| Paradigm | Description |
|---|---|
| Procedural | Code structured around separate functions and data |
| Object-oriented | Code 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
| Type | Mutable | Example | Empty |
|---|---|---|---|
int | No | 42 | 0 |
float | No | 3.14 | 0.0 |
str | No | "hello" | "" |
bool | No | True | False |
list | Yes | [1, 2, 3] | [] |
dict | Yes | {"a": 1} | {} |
set | Yes | {1, 2, 3} | set() |
tuple | No | (1, 2, 3) | () |
Control Flow Summary
| Statement | Syntax | Purpose |
|---|---|---|
if | if condition: | Conditional execution |
else | else: | Default branch |
elif | elif condition: | Additional conditions |
while | while condition: | Loop while true |
for | for item in iterable: | Iterate over sequence |
break | break | Exit loop immediately |
continue | continue | Skip to next iteration |
return | return value | Exit function with value |
OOP Concepts
| Concept | Python | Description |
|---|---|---|
| Class | class MyClass: | Blueprint for objects |
| Constructor | def __init__(self, ...) | Initializes instance |
| Instance | obj = MyClass(...) | Object created from class |
| Attribute | self.name = value | Instance data |
| Method | def my_method(self): | Instance behavior |
| Dot notation | obj.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