0% found this document useful (0 votes)
21 views76 pages

Complete Python Notes

The document introduces Python programming through the perspective of its creator, Maurice Otieno, and outlines the basics of coding, including how computers interpret instructions. It covers key concepts such as the difference between human and computer languages, the structure of programming languages, and the importance of Python as a high-level language. Additionally, it explains data types, arithmetic operators, and string properties, emphasizing Python's user-friendly nature and versatility.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views76 pages

Complete Python Notes

The document introduces Python programming through the perspective of its creator, Maurice Otieno, and outlines the basics of coding, including how computers interpret instructions. It covers key concepts such as the difference between human and computer languages, the structure of programming languages, and the importance of Python as a high-level language. Additionally, it explains data types, arithmetic operators, and string properties, emphasizing Python's user-friendly nature and versatility.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Lesson 1: Introduction

About the Creator: Maurice Otieno

Maurice Otieno is the Founder, CEO, and Director of Tech Savvy Institute. He began his
journey in statistical programming during his Bachelor's degree in Applied Statistics.

Maurice is an expert in Python, Julia, and R Programming. He is also passionate about Artificial
Intelligence.

He is currently pursuing a Master's degree in Financial Engineering at WorldQuant


University, combining math skills with real-world tech.
Welcome to Python!

Welcome! This lesson is your first step into the world of coding. We will learn how computers think
and how we can talk to them using Python.

What You'll Learn


How to give instructions to a computer and understand different computer languages.

What is a Program?
A program is just a list of instructions (like a recipe) that tells the computer exactly what to
do.

1. How a Computer Program Works

Computers are powerful, but they are not smart on their own. They need you to tell them exactly
what to do.
🍽️ REAL LIFE EXAMPLE: THE KITCHEN RECIPE

Imagine you want to bake a cake. You cannot just tell a kitchen: "Make cake." You need a
recipe with steps:

1. Get flour, eggs, and sugar.


2. Mix them in a bowl.
3. Put the mixture in the oven for 30 minutes.
4. Take it out and serve.

A computer program is just a recipe. The computer is the cook that follows your steps
blindly.

In a computer context, if you want to calculate speed, you must tell the computer:
Accept the number for distance.
Accept the number for time.
Divide distance by time.
Show the result on the screen.
2. Human Language vs. Computer Language

We speak "Natural Languages" (English, Swahili, Spanish). Computers speak "Machine Language"
(Zeros and Ones). We need a way to bridge this gap.

Natural Languages (Human)


Evolved naturally over time.

Full of ambiguity. Example: "I saw a bat." (Did you see a flying animal or a baseball
bat?)
Humans use context to understand meaning.

Programming Languages
Created by humans to talk to machines.

Zero ambiguity. An instruction means one thing only.


Very strict rules. If you miss a comma, it might break!

3. The Building Blocks of a Language

Every language consists of four main parts. Think of it like learning English grammar.
Alphabet Lexis
The Symbols The Vocabulary
English: A, B, C... English: "Apple", "Run"
Python: a, b, @, #, *, ... Python: "print", "if", "else"

Syntax Semantics
The Grammar The Meaning
Rules on how to arrange words. Does it make sense?
"I store go" is bad syntax. "I ate a shoe" is correct grammar, but
bad semantics (nonsense).

4. High-Level Languages

Computers only understand "Machine Code" (binary: 00101110). This is incredibly hard for humans
to read.
High-Level Languages (like Python) act as a bridge. They look like English, making them easy for
us to write.

🗣️ REAL LIFE EXAMPLE: THE TRANSLATOR

Imagine you only speak English, and your friend only speaks Japanese.
You (Programmer): Write "High-Level" instructions (English).
The Computer: Needs "Machine Code" (Japanese).
Python: Is the translator in the middle that converts your English into Japanese so the
computer understands.

🧑‍💻 Programmer writes ⚙️ 💻 Computer runs Machine


Python
→ Translator
→ Code

5. Compiler vs. Interpreter

There are two ways to translate code: Compilation and Interpretation.


🍲 REAL LIFE EXAMPLE: COOKING

Compiler (Pre-cooked Meal)


You cook the entire meal beforehand, freeze it, and send it. The user just heats it up.
Result: Fast to eat (run), but if you want to change an ingredient, you have to cook the whole
thing again.

Interpreter (Live Cooking Show)


You bring the ingredients and cook one step at a time while the user watches.
Result: Starts immediately, but eating takes longer. If you make a mistake, you can fix it on the
spot. Python is like this.

Compilation
Translates the whole program at once.
Creates a separate file (executable).
Runs very fast.

Interpretation (Python)
Translates one line at a time.
Runs immediately, no waiting for translation.
Easier to find errors (debugging).

6. How Python Runs Code

Since Python is an interpreter, it reads your code top-to-bottom, line-by-line.

1. Read Code
Python reads one line.

2. Check Grammar
Is the syntax correct?

3. Run It!
Execute the instruction.

4. Next Line
Repeat until finished.

⚠️ If Python finds an error on Line 5, it stops immediately. It won't run Line 6.


7. Introducing Python

Python is one of the world's most popular programming languages. It is known for being easy to
read and very powerful.

🐍 Fun Fact
It is NOT named after the snake! It was named after the British comedy show "Monty Python's
Flying Circus."

Guido van Rossum


The creator of Python (from the Netherlands). He wanted to make a
language that was easy for anyone to read, just like English.

8. Python's Philosophy

When Guido created Python, he had specific goals to make it different from other languages:
1. Easy to Read
Code should look clean. Less clutter, more meaning.

2. Open Source
It's free! Anyone can download it, use it, or even help improve it.

3. Plain English
It uses words like `and`, `not`, and `is` instead of confusing symbols.

9. Why Choose Python?

Beginner Friendly
It has a simple learning curve. You can write your first program in minutes.

Versatile
You can build websites, analyze data, create AI, or automate boring tasks.

High Demand
Companies everywhere (Google, Netflix, NASA) use Python, meaning lots of job
opportunities.

Practice Questions

Let's check what you remember:


1. In the "Kitchen Recipe" analogy, what represents the program?
2. What is the main difference between Human Language and Computer Language regarding
"Ambiguity"?
3. Which two building blocks of language describe the "Grammar" rules versus the "Meaning" of the
code?
4. Is Python a "Compiled" language or an "Interpreted" language? What does that mean for error
checking?
5. Why is Python named "Python"?
Conclusion

Congratulations! You've finished Lesson 1. You now understand that programming is just giving
clear recipes to a computer using a language it understands. Next, we will start writing actual code!
Lesson 2: Data Types

Introduction

In Python, every piece of data is considered an Object. A "variable" is just a name or label attached
to that data.

🚐 REAL LIFE EXAMPLE: MATATU ROUTES

Imagine a specific Matatu (bus) parked in the stage.

The Object is the physical Matatu vehicle itself.


The Variable is the Route Number sticker on the windshield (e.g., "Route 125").
If you take the "Route 125" sticker and put it on a different bus, the original bus is still
there, but the variable "Route 125" now refers to a different vehicle.

1. Mutable vs. Immutable

This concept asks: "Can I change this object after I make it?"

📝 REAL LIFE EXAMPLE: INK VS. PENCIL

Immutable (Ink)
If you make a mistake, you cannot change it. You must throw the paper away and write a new
one.
Examples: Numbers, Strings, Tuples.

Mutable (Pencil)
You can erase items or add new ones without replacing the whole page.
Examples: Lists, Dictionaries, Sets.

2. The Numbers

2.1 Integers (int)


These are whole numbers. They can be positive or negative and do not have decimal points.
x = 100
print(type(x))
print(100 + 20)

<class 'int'>
120

2.2 Floats (float)


These are numbers with decimals (e.g., 3.14, 2.5). They are used for precision.

y = 3.14
print(type(y))
print(10 / 3)

<class 'float'>
3.3333333333333335

3. Booleans (bool)

The simplest type. It represents truth values and can only be True or False.
is_valid = True
print(is_valid)
print(type(is_valid))

True
<class 'bool'>

4. Text (Strings)

Strings (str) are used for text. They are Immutable sequences of characters enclosed in quotes.

name = "Alice"
print(name)
print(type(name))

Alice
<class 'str'>

5. Lists and Tuples

5.1 Lists (list)


Lists are ordered, Mutable collections of items created with square brackets [].
shopping = ["Eggs", "Milk", "Bread"]
print(shopping)

['Eggs', 'Milk', 'Bread']

5.2 Tuples (tuple)


Tuples are ordered, Immutable collections created with parentheses (). They cannot be changed
once created.

coordinates = (10, 20)


print(coordinates)

(10, 20)

5.3 Range
A range is a sequence of numbers used mainly in loops. It does not store all numbers in memory.

nums = range(5)
print(list(nums))

[0, 1, 2, 3, 4]
6. Dictionaries (dict)

A dictionary stores data in Key-Value pairs using curly brackets {}.

phonebook = {
"Alice": "555-1234",
"Bob": "555-9876"
}
print(phonebook)

{'Alice': '555-1234', 'Bob': '555-9876'}

Practice Questions

Test your understanding:

1. Should you use a List or a Tuple for a collection that needs to be modified?
2. In the "Ink vs. Pencil" analogy, which one represents an Immutable object?
3. What is the main difference between an Integer and a Float?
4. Which data type uses Key-Value pairs?
5. Can you change a character inside a String directly?
Lesson 3: Arithmetic Operators

Introduction

Operators are symbols in Python that perform specific mathematical or logical computations. They
are the "verbs" of programming; they tell the code what action to perform on the data.

🛒 REAL LIFE EXAMPLE: THE DUKA (SHOP)

Imagine you are at a local Duka to buy snacks.

The Items: A loaf of bread (60 KES) and a packet of milk (50 KES). These are your
Operands (data).
The Action: You put them both on the counter to calculate the total.
The Operator: The addition symbol (+) is the action of combining the prices.

1. Basic Math

Python acts like a powerful calculator. It uses standard symbols for basic math.
1.1 Addition (+)
Adds two numbers together.

print(50 + 60)

110

1.2 Subtraction (-)


Subtracts the second number from the first.
print(100 - 45)

55

1.3 Multiplication (*)


Multiplies two numbers. Note that we use the asterisk symbol *, not 'x'.

print(5 * 20)

100

1.4 Division (/)


Divides the first number by the second. In Python, standard division always returns a Float (a
number with a decimal point), even if the division is clean.

print(20 / 5)

4.0
1.5 Floor Division (//)
Floor division uses two slashes //. It divides numbers but chops off the decimal part, leaving only
the whole integer. It always rounds down to the nearest whole number.

🚐 REAL LIFE EXAMPLE: MATATU FARE

You have 105 Shillings. The fare to town is 50 Shillings.

105 divided by 50 is 2.1.


But you cannot pay for "0.1" of a person.
You can only pay for 2 people fully. The remaining 5 shillings (the decimal part) is
ignored for the count.

print(105 // 50)

2. Modulus (%)

The Modulus operator is written with the percent symbol %. It does not calculate percentage. It
calculates the Remainder of a division.

🍬 REAL LIFE EXAMPLE: SHARING SWEETS

Imagine you have a bag of 10 sweets and you want to share them equally among 3 kids.

Each kid gets 3 sweets (3 x 3 = 9 sweets used).


There is 1 sweet left over in the bag.
That leftover sweet is the Modulus.
print(10 % 3)

3. Exponentiation (**)

This is used to raise a number to the power of another. It uses two asterisks **.

# This means 2 * 2 * 2
print(2 ** 3)

4. Precedence & Associativity

Instead of standard BODMAS, Python uses Precedence (priority) and Associativity (direction) to
determine which calculation happens first.
Precedence (Who wins?)
Some operators are "stronger" and grab the numbers near them before others do.
Associativity (Tie-breaker)
If two operators have the same strength, Associativity decides the order. Most operators are Left-
to-Right, but Exponentiation is Right-to-Left.

🏆 THE HIERARCHY OF POWER

1. () : Parentheses (Always wins, used to force order)


2. ** : Exponentiation (Right-to-Left)
3. * / // % : Multiplication & Divisions (Left-to-Right)
4. + - : Addition & Subtraction (Left-to-Right)
# Multiplication (*) beats Addition (+)
print(10 + 5 * 2)

# Parentheses () beat everything


print((10 + 5) * 2)

# Exponentiation (**) is Right-to-Left


# 2 ** 3 ** 2 means 2 ** (3 ** 2) -> 2 ** 9
print(2 ** 3 ** 2)

20
30
512

Practice Questions

Test your understanding:

1. Which symbol is used for Division in Python, and what type of number does it always return?
2. If you have 10 sweets and 3 children, which operator helps you find out how many sweets are
left over?
3. What is the result of 3 ** 2?
4. In the expression 5 + 2 * 3, which part is calculated first due to Precedence?
5. What is the difference between / and //?
Lesson 4: Strings

Introduction to Strings

A String in Python is a sequence of characters used to represent text. In Python, you can create
strings by enclosing text in single quotes ('...') or double quotes ("...").

📿 REAL LIFE EXAMPLE: MAASAI BEADWORK

Think of a String like a traditional beaded bracelet.

Each individual bead is a Character.


The string holding them together makes it a String object.
The beads are arranged in a specific order to form a pattern or word.

# Single quotes
print('Karibu Kenya')

# Double quotes
print("Jambo")

# Triple quotes for multiple lines


print("""This is a string
that spans across
multiple lines.""")

Karibu Kenya
Jambo
This is a string
that spans across
multiple lines.
1. String Properties

Strings have two very important characteristics that dictate how we use them.
1.1 Immutability
Strings are Immutable. This means once you create a string, you cannot change a single character
inside it directly. You must create a whole new string if you want to make changes.
Just like a printed newspaper: if there is a typo, you cannot magically move the ink. You have to print
a new page.
1.2 Ordered Sequence
Strings are Ordered. Every character has a specific position. The character 'A' in "Apple" is always
at the beginning unless you create a new string.
2. Indexing and Slicing

Since strings are ordered, we can access specific characters using their position, known as an
Index.
2.1 Indexing
Python starts counting from 0.
You can also count backwards from the end using negative numbers (starting from -1).

word = "PYTHON"

# Positive Indexing (Left to Right)


print(word[0]) # First letter
print(word[1]) # Second letter

# Negative Indexing (Right to Left)


print(word[-1]) # Last letter

P
Y
N

2.2 Slicing
Slicing allows you to grab a "chunk" or substring. The syntax is [start:stop].
Note: The stop index is exclusive (it is NOT included in the result).
text = "NAIROBI"

# Grab from index 0 up to (but not including) 3


print(text[0:3])

# Grab from index 3 to the end


print(text[3:])

NAI
ROBI

3. Concatenation and Repetition

You can perform basic "math" on strings to join or repeat them.


3.1 Concatenation (+)
Using the plus symbol + joins two strings together.

🚄 REAL LIFE EXAMPLE: SGR TRAIN

Concatenation is like connecting two railway carriages. You hook "Carriage A" to "Carriage
B" to make one long train.

a = "Ngori"
b = "Sana"
print(a + " " + b)

Ngori Sana
3.2 Repetition (*)
Using the asterisk * repeats a string multiple times.

print("Goal! " * 3)

Goal! Goal! Goal!

4. String Formatting (f-strings)

Often, you want to insert variables directly into a string. The best way to do this in modern Python is
using f-strings.
Simply put the letter f before the opening quote, and put your variables inside curly brackets {}.

📲 REAL LIFE EXAMPLE: M-PESA MESSAGES

When you receive an M-Pesa message, Safaricom doesn't type it manually. They have a
template (string) and they fill in your specific details (variables).
Template: "Confirmed. Ksh {amount} sent to {name}."

name = "Kamau"
balance = 500

# Using an f-string
print(f"Hello {name}, your balance is {balance}.")

Hello Kamau, your balance is 500.


5. Escape Characters

Sometimes you need to use special characters that Python normally interprets as code (like
quotes) or invisible characters (like a new line). You use a backslash (\) to "escape" them.
Code Description Example Output
Line 1
\n New Line (Moves text to the next line)
Line 2
\t Tab (Adds a large space) Col1 Col2
\' or \" Quotes (Prints a quote symbol) It's Kenya
\\ Backslash (Prints a literal backslash) \

# New line example


print("First Line\nSecond Line")

# Quote inside a string


print('It\'s a beautiful day')

First Line
Second Line
It's a beautiful day

Practice Questions

Test your understanding:

1. Which character index represents the first letter of a string in Python?


2. If s = "KENYA", what does s[-1] return?
3. What symbol is used to concatenate (join) two strings together?
4. How do you start an f-string to insert variables?
5. Which escape character would you use to move text to a new line?
Lesson 5: Variables

Introduction to Variables

A Variable in Python is essentially a name or a label that refers to a value stored in the computer's
memory. It allows you to store data, retrieve it, and manipulate it later.
Unlike some other languages where a variable is a "box" that you put things into, in Python, a
variable is more like a sticky note that you attach to an object.

🏷️ REAL LIFE EXAMPLE: THE KITCHEN JAR

Imagine your kitchen pantry has several plastic containers.

The white powder inside is the Data (Sugar).


The sticker on the outside that says "SUGAR" is the Variable.
If you move the "SUGAR" sticker to a jar of Salt, you haven't changed the sugar; you've
just changed what the label points to (which would be very confusing in a kitchen, but
common in programming!).

1. Variable Naming Rules

You can name a variable almost anything, but there are strict rules you must follow so Python
doesn't get confused.
1.1 The Must-Dos
Start with a letter (a-z, A-Z) or an underscore (_).
Contain only letters, numbers, or underscores.
Case Sensitive: Age, age, and AGE are three different variables.
1.2 The Don'ts
NO starting with a number (e.g., 1st_prize is invalid).
NO spaces (e.g., my name is invalid). Use underscores instead (my_name).
NO using Python keywords (words that mean something special to Python like print, if, for,
True).
# Good variable names
first_name = "Kamau"
age_2024 = 25
_secret_code = 1234

# Bad variable names (Would cause errors)


# 2nd_place = "Silver" <- Starts with number
# my name = "John" <- Contains space
# print = "Text" <- Overwrites the print function!

1.3 Naming Conventions (Snake Case)


Python developers prefer snake_case. This means using all lowercase letters and separating
words with underscores.
Example: total_monthly_revenue is better than totalMonthlyRevenue.
2. Assignment

We use the equals sign = to create a variable and give it a value. This is called Assignment.
The variable name goes on the Left, and the value goes on the Right.

city = "Nairobi"
population = 4400000

print(city)
print(population)

Nairobi
4400000

3. Reassignment

Variables are called "variable" because their values can vary (change). You can change the value of
a variable simply by assigning a new value to the same name.
⚽ REAL LIFE EXAMPLE: FOOTBALL SCOREBOARD

During a Mashemeji Derby (Gor Mahia vs AFC Leopards):

At the start, the variable gor_score is 0.


When they score, you don't buy a new scoreboard. You just update gor_score to 1.
The variable name stays the same, but the data it holds changes over time.

score = 0
print("Start of match:", score)

score = 1
print("After first goal:", score)

score = score + 1
print("After second goal:", score)

Start of match: 0
After first goal: 1
After second goal: 2

4. Multiple Assignment

Python allows you to assign values to multiple variables in a single line. This keeps your code short
and clean.
# Assigning different values to different variables
x, y, z = 10, 20, 30
print(x)
print(y)
print(z)

# Assigning the SAME value to multiple variables


a = b = c = 100
print(a)
print(b)

10
20
30
100
100

5. Constants

Sometimes you have a value that should NEVER change during the program, like the value of Pi
(3.142) or the M-Pesa Transaction Fee.
Python doesn't strictly prevent you from changing these, but by convention, we use ALL CAPITAL
LETTERS to shout to other developers: "DO NOT CHANGE THIS!"

PI = 3.14159
MAX_LOGIN_ATTEMPTS = 3
MPESA_PAYBILL = 522522

print(f"Pay to Paybill {MPESA_PAYBILL}")

Pay to Paybill 522522


Practice Questions

Test your understanding:

1. Which of the following is a valid variable name: 2nd_user, user-name, or user_name_2?


2. What operator is used to assign a value to a variable?
3. If x = 10 and then you write x = 20, what happened to the value 10?
4. How do you write a variable name to indicate it is a constant that shouldn't change?
5. What style of naming variables (e.g. my_variable_name) is preferred in Python?
Lesson 6: Data Structures

Introduction

Data structures are simply containers that allow us to store, organize, and manage multiple items
together in different ways. Rather than having a separate variable for every single item, we group
them.

🎒 REAL LIFE EXAMPLE: CONTAINERS

Think about how you pack for a trip:

List: A Shopping Bag. You toss items in, take them out, and rearrange them anytime.
(Mutable, Ordered)
Tuple: A Sealed Delivery Box. The items inside are fixed; you can't change them
without breaking the box. (Immutable, Ordered)
Dictionary: A Phonebook. You look up a specific name (Key) to find their number
(Value). (Key-Value Pairs)
Set: A Sack of Potatoes. It doesn't matter which potato went in first (Unordered), and
you can't have the exact same physical potato twice (Unique).

1. Lists

A List is an ordered collection of items. It is Mutable, meaning you can add, remove, or change
items after creating it.
Syntax: Uses square brackets [].
1.1 Examples of Lists

# 1. A list of Strings (Counties)


counties = ["Nairobi", "Mombasa", "Kisumu", "Nakuru"]

# 2. A list of Integers (M-Pesa transaction amounts)


amounts = [50, 100, 500, 1000]

# 3. A Mixed List (Different data types)


student_info = ["Kamau", 21, True, 3.5]

# 4. A List of Lists (Nested List - like a grid)


grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

# 5. An Empty List (Waiting for items)


cart = []

1.2 List Properties & Operations


We can manipulate lists using various methods.
Accessing Items (Indexing)
We use the index number to grab an item. Remember, counting starts at 0!
counties = ["Nairobi", "Mombasa", "Kisumu", "Nakuru"]

print(counties[0]) # First item: Nairobi


print(counties[-1]) # Last item: Nakuru
print(counties[1:3]) # Slicing (index 1 to 2): ['Mombasa', 'Kisumu']

Nairobi
Nakuru
['Mombasa', 'Kisumu']

Adding Items
Use .append() to add to the end, or .insert() to add at a specific spot.

fruits = ["Mango", "Banana"]

# Append adds to the end


[Link]("Avocado")

# Insert adds at index 1 (pushes others to the right)


[Link](1, "Orange")

# Extend adds multiple items from another list


[Link](["Pineapple", "Watermelon"])

print(fruits)

['Mango', 'Orange', 'Banana', 'Avocado', 'Pineapple', 'Watermelon']


Removing Items

cart = ["Bread", "Milk", "Soap", "Sugar"]

# Remove by value (deletes the first one found)


[Link]("Soap")

# Pop removes by index (default is the last item)


last_item = [Link]()

# Delete by index using 'del'


del cart[0]

print(cart)
print("Popped item:", last_item)

['Milk']
Popped item: Sugar

Other Useful Properties


len(list): Counts how many items are inside.
[Link](): Arranges items in order (A-Z or 0-9).
[Link](): Flips the list backwards.
2. Tuples

A Tuple is like a list, but Immutable. Once created, it cannot be changed. It is faster and safer for
fixed data.
Syntax: Uses parentheses ().
2.1 Examples of Tuples

# 1. GPS Coordinates (Latitude, Longitude)


location_kicc = (-1.2921, 36.8219)

# 2. RGB Color Codes (Red, Green, Blue)


color_red = (255, 0, 0)

# 3. Days of the Week


days = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")

# 4. A single item tuple (Must have a comma!)


single_item = (50,)

# 5. Database Record (ID, Name, Email)


user_record = (101, "Alice", "alice@[Link]")

2.2 Tuple Properties & Operations


Accessing Items
Just like lists, we use indexes.

days = ("Mon", "Tue", "Wed")


print(days[0])
print(days[-1])

Mon
Wed

Unpacking
You can assign tuple values to variables in one line.
coords = (10, 20)
x, y = coords

print("X is:", x)
print("Y is:", y)

X is: 10
Y is: 20

Immutability Check
Trying to change a tuple creates an error.

fixed_data = (1, 2, 3)
# fixed_data[0] = 5 <-- TypeError: 'tuple' object does not support item assig

3. Dictionaries

A Dictionary stores data in Key-Value pairs. It allows you to look up values using a unique Key
rather than an index number.
Syntax: Uses curly brackets {} with key: value pairs.
3.1 Examples of Dictionaries

# 1. Student Profile
student = {"name": "Otieno", "age": 22, "course": "IT"}

# 2. Matatu Details
matatu = {
"route": "125",
"sacca": "Super Metro",
"driver": "Njoroge",
"fare": 100
}

# 3. M-Pesa Transaction
transaction = {
"code": "SDF342...",
"amount": 500,
"recipient": "KPLC Prepaid",
"balance": 2400
}

# 4. English to Swahili Dictionary


translate = {
"Hello": "Jambo",
"Thank you": "Asante",
"Friend": "Rafiki"
}

# 5. Kenya County Codes


county_codes = {
47: "Nairobi",
1: "Mombasa",
12: "Meru"
}

3.2 Dictionary Properties & Operations


Accessing Values
Use the key inside square brackets or the .get() method (safer).
matatu = {"route": "125", "sacca": "Super Metro"}

print(matatu["route"])
print([Link]("sacca"))

125
Super Metro

Adding and Modifying

profile = {"name": "Jane"}

# Add new key-value pair


profile["city"] = "Nakuru"

# Update existing value


profile["name"] = "Jane Doe"

print(profile)

{'name': 'Jane Doe', 'city': 'Nakuru'}


Removing Items

car = {"brand": "Toyota", "model": "Vitz", "year": 2015}

# Pop removes specific key and returns value


model = [Link]("model")

# Popitem removes the last inserted item


[Link]()

print(car)

{'brand': 'Toyota'}

Looping Keys and Values


You can get a list of just keys, just values, or both.

data = {"a": 1, "b": 2}


print([Link]())
print([Link]())

dict_keys(['a', 'b'])
dict_values([1, 2])

4. Sets

A Set is an unordered collection of Unique items. It is great for removing duplicates and doing math
logic (like finding common items).
Syntax: Uses curly brackets {}.
4.1 Examples of Sets

# 1. Unique ID numbers (No duplicates allowed)


ids = {101, 102, 103, 104}

# 2. Ingredients in a recipe (Order doesn't matter)


ingredients = {"Flour", "Water", "Salt", "Oil"}

# 3. Unique Phone Numbers visiting a website


visitors = {"0712...", "0722...", "0733..."}

# 4. Lotto Numbers
lotto = {4, 12, 33, 45, 1}

# 5. Creating a set from a list to remove duplicates


raw_list = [1, 2, 2, 3, 3, 3]
unique_set = set(raw_list)
4.2 Set Properties & Operations
Adding and Removing

colors = {"Red", "Green"}

# Add an item
[Link]("Blue")

# Remove an item
[Link]("Red")

# Try adding a duplicate (Nothing happens)


[Link]("Green")

print(colors)

{'Blue', 'Green'}

Set Logic (Venn Diagrams)


Sets are powerful for comparing groups.
group_a = {"Kamau", "Ochieng", "Wanjiku"}
group_b = {"Wanjiku", "Njoroge", "Kamau"}

# Intersection (Who is in BOTH groups?)


print(group_a.intersection(group_b))

# Union (Combine EVERYONE, no duplicates)


print(group_a.union(group_b))

# Difference (Who is in A but NOT in B?)


print(group_a.difference(group_b))

{'Kamau', 'Wanjiku'}
{'Njoroge', 'Kamau', 'Wanjiku', 'Ochieng'}
{'Ochieng'}

Practice Questions

Test your understanding:

1. Which data structure would you use to store a list of students where you need to frequently add
and remove names?
2. How do you add the item "Sugar" to the end of a list named shopping_cart?
3. If you have a tuple coords = (10, 20), what happens if you try to run coords[0] = 50?
4. You have a list with duplicates: [1, 2, 2, 3]. What is the fastest way to remove the
duplicates?
5. In the dictionary car = {"model": "Toyota", "year": 2020}, which code retrieves the value
2020?
Lesson 7: Advanced Operators

Introduction

We've already looked at Arithmetic operators (+, -, *) which perform math. Now we will look at
operators that help us make decisions, compare values, and check relationships between data.
These operators typically answer questions with a Boolean result: True or False.
1. Comparison Operators

Comparison operators compare two values. They act like a question: "Is this equal to that?" or "Is
this bigger than that?"

🤝 REAL LIFE EXAMPLE: MARKET BARGAINING

Imagine you are buying shoes at Gikomba.

Price: 1000 KES.


Your Offer: 800 KES.
You compare the numbers: Is Offer < Price? Yes (True).
Is Offer == Price? No (False), so the deal isn't done yet.

Common Comparison Operators


Operator Meaning Example
== Equal to 5 == 5 (True)
!= Not equal to 5 != 3 (True)
> Greater than 10 > 5 (True)
< Less than 2 < 5 (True)
>= Greater than or equal to 5 >= 5 (True)
<= Less than or equal to 4 <= 5 (True)

💡 Pro Tip: Comparing Strings & Ranges


Strings: Python compares strings alphabetically. "Apple" < "Banana" is True because 'A'
comes before 'B'.
Chained Comparison: You can check ranges in one step! Instead of age >= 18 and age
<= 35, just write 18 <= age <= 35.
# Checking M-Pesa balance
balance = 500
cost_of_lunch = 650

# 1. Numeric Comparison
# Can I afford lunch? (Is balance greater or equal to cost?)
can_afford = balance >= cost_of_lunch
print(f"Can afford lunch: {can_afford}")

# Is the balance exactly zero?


is_broke = balance == 0
print(f"Is balance zero: {is_broke}")

# 2. String Comparison (Alphabetical)


print(f"Is 'Cat' smaller than 'Dog'? {'Cat' < 'Dog'}")

# 3. Chained Comparison
age = 20
# Is age between 18 and 35?
is_youth = 18 <= age <= 35
print(f"Is youth: {is_youth}")

Can afford lunch: False


Is balance zero: False
Is 'Cat' smaller than 'Dog'? True
Is youth: True

2. Logical Operators

Logical operators allow us to combine multiple conditions. They are used when you need to check
more than one thing at a time.
👮 REAL LIFE EXAMPLE: CLUB ENTRY

To enter a club, the bouncer checks two things:

AND: You need an ID AND the Entrance Fee. If you miss one, you don't enter.
OR: You can pay via Cash OR M-Pesa. If you have either one, you are good.
NOT: You must NOT be underage.

The Three Logical Operators


and: Returns True only if BOTH statements are True.
or: Returns True if AT LEAST ONE statement is True.
not: Reverses the result (True becomes False).

has_id = True
has_fee = False

# AND Operator (Need both)


can_enter = has_id and has_fee
print(can_enter)

# OR Operator (Need at least one)


has_cash = False
has_mpesa = True
can_pay = has_cash or has_mpesa
print(can_pay)

# NOT Operator (Reverse)


is_underage = False
is_allowed = not is_underage
print(is_allowed)

False
True
True
3. Identity Operators

Identity operators (is, is not) check if two variables refer to the exact same object in memory,
not just if they have the same value.

👯 REAL LIFE EXAMPLE: TWINS VS. THE SAME PERSON

Imagine two people, Kamau and Njoroge.

Equality (==): They both wear the exact same shirt. Are the shirts equal in appearance?
Yes.
Identity (is): Is Kamau actually Njoroge? No. They are two different people who look
alike.
Identity (is): Does "President of Kenya" refer to the same person as "William Ruto"
(currently)? Yes. They are the same entity.

# Two separate lists with same content


list_a = [1, 2, 3]
list_b = [1, 2, 3]
list_c = list_a # list_c points to the SAME list as list_a

# Comparing Values
print(list_a == list_b) # True, they look the same

# Comparing Identity
print(list_a is list_b) # False, they are two different lists in memory
print(list_a is list_c) # True, they are the exact same list object

True
False
True

4. Membership Operators

Membership operators (in, not in) check if a specific item exists inside a sequence (like a list,
tuple, or string).
🥘 REAL LIFE EXAMPLE: RECIPE CHECK

You are checking a recipe for Pilau.

Is "Rice" in the ingredients list? Yes.


Is "Cement" not in the ingredients list? Yes.

menu = ["Chapati", "Mandazi", "Samosa"]

# Check if item exists


print("Chapati" in menu)

# Check if item does NOT exist


print("Pizza" not in menu)

# Works with Strings too


name = "Kenya"
print("K" in name)

True
True
True

Practice Questions

Test your understanding:

1. What is the result of 10 != 10?


2. If a = True and b = False, what does a and b return?
3. Which operator would you use to check if the name "Alice" is inside a list of students?
4. Explain the difference between == and is.
5. What does the expression not (5 > 3) evaluate to?
Lesson 8: Conditional Statements

Introduction to Conditionals

Computer programs usually read code line-by-line, from top to bottom. But real life isn't a straight
line; we make decisions constantly. Conditional Statements allow our programs to make
decisions too.
They allow the code to "branch" and execute different blocks of code depending on whether a
specific condition is True or False.

🚐 REAL LIFE EXAMPLE: PICKING A MATATU

Imagine you are at the bus station (stage) trying to get home.

Condition: Is the Super Metro bus full?


If YES (True): Wait for the next one.
If NO (False): Board the bus.
This simple decision-making process is exactly how an if statement works.

1. The `if` Statement

This is the simplest form of decision making. It says: "If this condition is true, do this task. If not, just
ignore it and move on."
[Image of Python if statement flowchart]
Syntax
Notice the colon (:) at the end of the line and the Indentation (space) for the block of code
underneath.

⚠️ Important: Indentation
Python relies on whitespace. The code inside the if block MUST be indented (usually 4 spaces
or 1 tab). If you forget the indentation, you will get an error!
age = 20

# Check if old enough to vote


if age >= 18:
print("You are eligible to vote!")
print("Please verify your ID.")

print("This line runs no matter what.")

You are eligible to vote!


Please verify your ID.
This line runs no matter what.

2. The `if...else` Statement

Often, you have two choices. If the condition is true, do Option A. If it is false, do Option B. You
never do both.

🌦️ REAL LIFE EXAMPLE: RAINY DAY

If it is raining, carry an umbrella.


Else (if it's not raining), wear sunglasses.
mpesa_balance = 50
fare = 100

if mpesa_balance >= fare:


print("Payment Successful. Board the matatu.")
else:
print("Insufficient Balance. Please top up.")

Insufficient Balance. Please top up.

3. The `if...elif...else` Chain

Life is rarely just "Yes" or "No". Sometimes we have many options. We use elif (short for "else if")
to check multiple conditions in a sequence.
Python checks them from top to bottom. As soon as it finds ONE true condition, it executes that
block and ignores the rest.

🎓 REAL LIFE EXAMPLE: KCSE GRADING

Grading is a perfect example of multiple conditions:

If score >= 80: Grade A


Elif score >= 70: Grade B
Elif score >= 60: Grade C
Else: Grade D
marks = 72

if marks >= 80:


print("Grade: A")
elif marks >= 70:
print("Grade: B")
elif marks >= 60:
print("Grade: C")
elif marks >= 50:
print("Grade: D")
else:
print("Grade: E")

Grade: B

4. Nested Conditionals

You can put an if statement inside another if statement. This is called "Nesting". It's like having a
decision within a decision.

🏧 REAL LIFE EXAMPLE: USING AN ATM

1. Check 1: Is the PIN correct?


If No: Reject card.
If Yes: Go to Check 2.
2. Check 2 (Inside Check 1): Is the Account Balance sufficient?
If Yes: Dispense Cash.
If No: Show "Insufficient Funds".
correct_pin = 1234
entered_pin = 1234
balance = 2000
withdraw_amount = 5000

if entered_pin == correct_pin:
print("PIN Accepted.")
# Inner Condition (Nested)
if balance >= withdraw_amount:
print("Dispensing Cash...")
else:
print("Insufficient Funds.")
else:
print("Wrong PIN.")

PIN Accepted.
Insufficient Funds.

5. Complex Logic (and, or, not)

You can combine multiple conditions in a single if statement using Logical Operators.
5.1 Using `and`
All conditions must be true.

# Club Entry Requirements


age = 20
has_id = True

if age >= 18 and has_id:


print("Allowed to enter.")
else:
print("Entry denied.")
5.2 Using `or`
Only one condition needs to be true.

# Payment Methods
has_cash = False
has_mpesa = True

if has_cash or has_mpesa:
print("Payment accepted.")
else:
print("You cannot pay.")

Practice Questions

Test your understanding:

1. Which keyword is used to check multiple conditions after the first if fails?
2. What happens if you forget to indent the code under an if statement?
3. In an if...elif...else chain, how many blocks of code will actually run?
4. Write a logic condition for: "If user is over 18 AND has a ticket".
5. What symbol must appear at the end of every if, elif, and else line?
Lesson 9: Loops

Introduction to Loops

In programming, we often need to repeat a specific task multiple times. Instead of copying and
pasting the same code 100 times, we use Loops.
Loops allow a block of code to execute repeatedly until a specific condition is met.

🍽️ REAL LIFE EXAMPLE: CUTTING CHAPATI

Imagine you are cooking Chapati.

Task: Roll the dough into a circle.


Loop: Do this for every ball of dough in the bowl.
Stop Condition: When the bowl is empty, stop rolling.

1. The `while` Loop

A while loop keeps running as long as a certain condition remains True. It checks the condition
before every iteration.
Warning: You must ensure the condition eventually becomes False, otherwise the loop will run
forever (Infinite Loop)!

🚐 REAL LIFE EXAMPLE: FILLING A MATATU

"While the number of empty seats is greater than 0, keep calling for passengers."
Once seats == 0, the loop stops (and the matatu leaves).
Example 1: Basic Countdown

count = 5

while count > 0:


print(f"Countdown: {count}")
count = count - 1 # Important: Decrease count so loop ends!

print("Blast off!")

Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
Blast off!
Example 2: Saving Money

savings = 0
target = 500

while savings < target:


print(f"Current savings: {savings}. Keep saving...")
savings += 100 # Add 100 bob each time

print(f"Target reached! Total: {savings}")

Current savings: 0. Keep saving...


Current savings: 100. Keep saving...
Current savings: 200. Keep saving...
Current savings: 300. Keep saving...
Current savings: 400. Keep saving...
Target reached! Total: 500

2. The `for` Loop

A for loop is used to iterate over a sequence (like a list, tuple, string, or range). It runs once for
each item in the collection.

🥬 REAL LIFE EXAMPLE: CHOPPING SUKUMA WIKI

You have a bunch of kale leaves.


For each leaf in the bunch, wash it, slice it, and put it in the sufuria.
Example 1: Looping through a List

counties = ["Nairobi", "Kisumu", "Mombasa"]

for county in counties:


print(f"I want to visit {county}")

I want to visit Nairobi


I want to visit Kisumu
I want to visit Mombasa

Example 2: Looping through a String

word = "KENYA"

for letter in word:


print(letter)

K
E
N
Y
A

3. The `range()` Function

The range() function allows us to loop a specific number of times. It generates a sequence of
numbers.
range(5): 0, 1, 2, 3, 4 (Stops before 5)
range(2, 6): 2, 3, 4, 5 (Start at 2, stop before 6)
range(0, 10, 2): 0, 2, 4, 6, 8 (Step by 2)

# Print numbers 0 to 4
print("--- Standard Range ---")
for i in range(5):
print(i)

# Print even numbers from 10 to 20


print("--- Stepped Range ---")
for num in range(10, 21, 2):
print(num)

--- Standard Range ---


0
1
2
3
4
--- Stepped Range ---
10
12
14
16
18
20

4. Loop Control Statements

Sometimes you need to interrupt the normal flow of a loop. We use break and continue for this.
4.1 `break` (Stop Immediately)
The break statement terminates the loop entirely.
🛑 REAL LIFE EXAMPLE: SEARCHING FOR KEYS

You are looking through drawers for your keys. Loop: Open drawer, check inside.
Break: Once you find the keys in the 2nd drawer, you stop looking. You don't open the
remaining drawers.

for num in range(1, 10):


if num == 5:
print("Found 5! Stopping loop.")
break
print(f"Checking number {num}...")

Checking number 1...


Checking number 2...
Checking number 3...
Checking number 4...
Found 5! Stopping loop.

4.2 `continue` (Skip This One)


The continue statement skips the rest of the current iteration and jumps to the next one.

🍛 REAL LIFE EXAMPLE: SORTING BEANS

You are sorting beans for Githeri. Loop: Pick up a bean.


Continue: If you pick up a small stone or bad bean, you throw it away (skip it) and pick up
the next bean. You don't stop cooking entirely.
# Skip odd numbers
for num in range(1, 6):
if num % 2 != 0:
continue # Skip the rest of the code for this number
print(f"Even number: {num}")

Even number: 2
Even number: 4

5. Nested Loops

A nested loop is a loop inside another loop. The "inner loop" finishes all of its iterations for every
single iteration of the "outer loop".

🏫 REAL LIFE EXAMPLE: SCHOOL SCHEDULE

Outer Loop (Days): Monday, Tuesday, Wednesday...


Inner Loop (Periods): Math, English, Swahili...
For every Day (outer), you go through all Periods (inner) before moving to the next Day.
days = ["Mon", "Tue"]
meals = ["Breakfast", "Lunch"]

for day in days:


print(f"--- {day} ---")
for meal in meals:
print(f"Eating {meal} on {day}")

--- Mon ---


Eating Breakfast on Mon
Eating Lunch on Mon
--- Tue ---
Eating Breakfast on Tue
Eating Lunch on Tue

Practice Questions

Test your understanding:

1. Which loop is best used when you know exactly how many times you want to iterate (e.g.,
iterating through a list)?
2. What happens if the condition in a while loop never becomes False?
3. Which keyword would you use to exit a loop completely when a specific condition is met?
4. If you have `range(1, 5)`, what is the last number that will be printed?
5. In a nested loop (Loop A inside Loop B), which loop completes its full cycle first?
Lesson 10: Introduction to NumPy

Introduction to NumPy

So far, we have used Python Lists to store groups of data. But when dealing with Data Science, AI,
or Engineering, lists can be too slow and use too much memory.
Enter NumPy (Numerical Python). It is a library (a toolbox of code written by others) that gives us a
new data structure called the Array.
Before we use it, we must install it and "import" it into our code.

# 1. Install (Run this in your terminal once)


# pip install numpy

# 2. Import in Python
import numpy as np

# 'as np' allows us to type 'np' instead of 'numpy' every time

1. Lists vs. NumPy Arrays

Why learn a new thing if we already have Lists? Because NumPy Arrays are faster and smarter for
numbers.

🥚 REAL LIFE EXAMPLE: TRAY OF EGGS VS. BAG OF GROCERIES

Python List (Grocery Bag)


Flexible. You can put bread, milk, and soap in one bag. But if you want to find the 3rd item,
you have to dig through.

NumPy Array (Tray of Eggs)


Fixed. It only carries ONE thing (Eggs). Because every slot is identical, you instantly know
where egg #30 is. It's incredibly fast to count or move them.

Key Differences
Speed: NumPy is up to 50x faster than Lists.
Data Type: Lists can hold anything (Int, String, Bool mixed). Arrays must hold ONE data type
(e.g., all Integers).
2. Creating Arrays

The most common way to create an array is by converting a regular Python list.

# Converting a list to an array


my_list = [1, 2, 3, 4, 5]
arr = [Link](my_list)

print(arr)
print(type(arr))

[1 2 3 4 5]
<class '[Link]'>

Automatic Arrays
NumPy can also create arrays for you automatically, which is useful for generating data.
# 1. Array of Zeros
print([Link](5))

# 2. Array of Ones
print([Link](3))

# 3. Range of numbers (Start, Stop, Step) - Like Python's range()


print([Link](0, 10, 2))

[0. 0. 0. 0. 0.]
[1. 1. 1.]
[0 2 4 6 8]

3. Dimensions (0-D, 1-D, 2-D)

Data in NumPy can have different shapes or dimensions.


0-D Array (Scalar)
Just a single value. Like one person standing alone.
1-D Array (Vector)
A list of values. Like a queue at a Supermarket.
2-D Array (Matrix)
Rows and Columns. Like a spreadsheet or a tray of eggs.
# 1-D Array
arr_1d = [Link]([1, 2, 3])

# 2-D Array (Notice the double brackets)


arr_2d = [Link]([
[1, 2, 3],
[4, 5, 6]
])

print("2D Array shape:", arr_2d.shape) # (Rows, Columns)


print("Number of dimensions:", arr_2d.ndim)

2D Array shape: (2, 3)


Number of dimensions: 2

4. Vectorization (The Superpower)

This is why we love NumPy. If you want to multiply every number in a list by 2, standard Python
requires a loop (slow). NumPy can do it all at once (fast).

📣 REAL LIFE EXAMPLE: CLASSROOM COMMAND

Python Loop: Walking to Student 1 ("Stand up"), then Student 2 ("Stand up"), then
Student 3...
NumPy Vectorization: Shouting to the whole class "EVERYONE STAND UP!"
arr = [Link]([10, 20, 30])

# Multiply everyone by 2
print(arr * 2)

# Add 5 to everyone
print(arr + 5)

[20 40 60]
[15 25 35]

5. Indexing and Slicing

Accessing data in NumPy is similar to Lists, but with extra power for 2D arrays.
1-D Slicing
Works exactly like Python lists: [start:stop].
2-D Slicing
The syntax is [row, column].
matrix = [Link]([
[10, 20, 30], # Row 0
[40, 50, 60] # Row 1
])

# Get 1st Row, 2nd Column (Remember index starts at 0)


# Row 0, Col 1 -> Value is 20
print("Element at [0, 1]:", matrix[0, 1])

# Get the entire 2nd Row


print("Row 1:", matrix[1, :])

Element at [0, 1]: 20


Row 1: [40 50 60]

6. Basic Statistics

NumPy has built-in functions to analyze data instantly.

scores = [Link]([80, 90, 70, 60, 100])

print("Mean (Average):", [Link](scores))


print("Max Score:", [Link](scores))
print("Min Score:", [Link](scores))
print("Sum Total:", [Link](scores))

Mean (Average): 80.0


Max Score: 100
Min Score: 60
Sum Total: 400
Practice Questions

Test your understanding:

1. What is the alias we typically use when importing numpy? (e.g. import numpy as ???)
2. Can a NumPy array hold both Strings and Integers at the same time?
3. If you have a 2D array (matrix), what does [Link] return?
4. In the analogy, is a NumPy array more like a "Shopping Bag" or a "Tray of Eggs"?
5. What NumPy function would you use to create an array of five zeros?
Lesson 11: Introduction to Pandas

Introduction to Pandas

Pandas is the most popular library in Python for Data Analysis. If you have ever worked with
Microsoft Excel or Google Sheets, then Pandas is essentially "Excel for Python".
It allows us to load data, clean it, manipulate it, and analyze it efficiently.
First, we need to install and import it.

# 1. Install (Run in terminal)


# pip install pandas

# 2. Import in Python
import pandas as pd

# 'pd' is the standard alias everyone uses.

1. Core Structures: Series & DataFrame

Pandas is built on two main building blocks.

📊 REAL LIFE EXAMPLE: SPREADSHEET

Series (1D)
Think of a Single Column in Excel. For example, just a list of "Prices" for different items.

DataFrame (2D)
Think of the Whole Sheet. It has rows and multiple columns (e.g., "Item Name", "Price",
"Quantity"). A DataFrame is essentially a collection of Series stuck together.

[Image of Pandas Dataframe Structure Diagram]


1.1 Creating a Series

# A simple list of marks


marks = [80, 90, 75]

# Convert to a Series
s = [Link](marks)
print(s)

0 80
1 90
2 75
dtype: int64

1.2 Creating a DataFrame


We often create DataFrames from a Dictionary.
data = {
"Student": ["Kamau", "Wanjiku", "Otieno"],
"Age": [22, 21, 23],
"Course": ["CS", "IT", "Eng"]
}

df = [Link](data)
print(df)

Student Age Course


0 Kamau 22 CS
1 Wanjiku 21 IT
2 Otieno 23 Eng

2. Reading Data

Usually, you don't type data manually. You load it from a file, like a CSV (Comma Separated Values)
or Excel file.

📂 REAL LIFE EXAMPLE: M-PESA STATEMENT

Imagine you download your M-Pesa statement as a file named [Link]. Pandas can
open this file instantly so you can calculate your total spending.
# Reading a CSV file
# df = pd.read_csv("mpesa_statement.csv")

# Reading an Excel file


# df = pd.read_excel("sales_data.xlsx")

# For this lesson, we will use the 'df' we created above.


print("Data Loaded Successfully.")

Data Loaded Successfully.

3. Inspecting Data

When you load a huge file with 10,000 rows, you can't print the whole thing. You need tools to
"peek" at the data.
[Link](): Shows the first 5 rows (The header).
[Link](): Shows the last 5 rows (The footer).
[Link](): Summarizes the data types (Are they numbers? Text?) and checks for missing
values.
[Link]: Tells you the size (Rows, Columns).
print("--- HEAD (Top 2) ---")
print([Link](2))

print("\n--- INFO ---")


print([Link]())

print("\n--- SHAPE ---")


print([Link])

--- HEAD (Top 2) ---


Student Age Course
0 Kamau 22 CS
1 Wanjiku 21 IT

--- INFO ---

RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Student 3 non-null object
1 Age 3 non-null int64
2 Course 3 non-null object
dtypes: int64(1), object(2)
None

--- SHAPE ---


(3, 3)

4. Selecting and Filtering

Sometimes you only want specific columns or rows that match a condition.
4.1 Selecting a Column
This works like a dictionary key.
# Select only the 'Student' column
print(df["Student"])

0 Kamau
1 Wanjiku
2 Otieno
Name: Student, dtype: object

4.2 Filtering Rows (Boolean Indexing)


This asks: "Show me ONLY the rows where Age is greater than 21".

# Filter students older than 21


older_students = df[df["Age"] > 21]
print(older_students)

Student Age Course


0 Kamau 22 CS
2 Otieno 23 Eng

5. Basic Statistics

Pandas makes math easy. You can calculate the average, sum, or count of a column instantly.
# Average Age
print("Mean Age:", df["Age"].mean())

# Total Age (Sum)


print("Sum of Ages:", df["Age"].sum())

# Describe (Quick summary of all math stats)


print("\n--- DESCRIBE ---")
print([Link]())

Mean Age: 22.0


Sum of Ages: 66

--- DESCRIBE ---


Age
count 3.0
mean 22.0
std 1.0
min 21.0
25% 21.5
50% 22.0
75% 22.5
max 23.0

Practice Questions

Test your understanding:

1. What is the standard alias used when importing Pandas?


2. Which Pandas structure represents a single column of data (1D)?
3. Which function would you use to read a Comma Separated Values file?
4. If you want to see just the first 5 rows of your data, which method do you call?
5. How would you filter a DataFrame df to show only rows where the column "Price" is greater than
1000?
Lesson 12: Data Visualization with
Matplotlib

Introduction to Matplotlib

In Data Science, raw numbers in a table can be boring and hard to understand. Matplotlib is a
library that allows us to turn data into beautiful graphs and charts.
If Pandas is "Excel for Python," then Matplotlib is the tool for drawing charts on a whiteboard.

⚽ REAL LIFE EXAMPLE: FOOTBALL SCORES

Imagine reading a list of every goal scored in the English Premier League. It's just a long list
of text.
Now imagine seeing a Bar Chart showing "Top Scorers." You can instantly see who is
leading without reading every line. That is the power of visualization.

# 1. Install (Run in terminal)


# pip install matplotlib

# 2. Import in Python
# We mostly use the 'pyplot' module
import [Link] as plt

# 'plt' is the standard alias everyone uses.

1. Basic Plotting (The Line Plot)

The simplest plot is a Line Plot. It is perfect for showing trends over time (like temperature or stock
prices).
You essentially tell Python: "Here are the X values (horizontal), and here are the Y values (vertical)."
[Image of simple line plot example]
# Sample Data: Days vs Temperature in Nairobi
days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
temp = [22, 24, 19, 23, 25]

# Create the plot


[Link](days, temp)

# Show the plot


[Link]()

[Graph Window Opens Showing a Line Chart]

2. Decorating Plots

A graph without labels is confusing. Matplotlib allows us to add titles, labels, and legends to make
our chart professional.

days = ["Mon", "Tue", "Wed", "Thu", "Fri"]


temp = [22, 24, 19, 23, 25]

[Link](days, temp, color="green", marker="o", linestyle="--")

# Adding details
[Link]("Weekly Temperature in Nairobi")
[Link]("Day of the Week")
[Link]("Temperature (Celsius)")

[Link]()

[Graph Window Opens with Titles and Green Dashed Line]


3. Bar Charts

Bar charts are best for comparing categories. For example, comparing votes for different
candidates or sales of different fruits.

🗳️ REAL LIFE EXAMPLE: ELECTION RESULTS

You have three candidates: A, B, and C. You want to show who got the most votes. A bar
chart makes the tallest bar (winner) obvious immediately.

candidates = ["Kamau", "Wanjiku", "Otieno"]


votes = [120, 300, 250]

# Create a Bar Chart


[Link](candidates, votes, color="blue")

[Link]("Class Rep Election Results")


[Link]("Number of Votes")

[Link]()

[Graph Window Opens Showing 3 Blue Bars]

4. Scatter Plots

Scatter plots use dots to show the relationship (correlation) between two numerical variables.
They don't connect the dots with lines.

📚 REAL LIFE EXAMPLE: STUDY VS. GRADES

Does studying more actually get you higher marks? If you plot "Hours Studied" on the X-axis
and "Exam Score" on the Y-axis, you might see a pattern (trend) going up.
hours_studied = [1, 2, 3, 4, 5, 6, 7]
exam_score = [50, 55, 65, 70, 85, 90, 95]

# Create a Scatter Plot


[Link](hours_studied, exam_score, color="red")

[Link]("Study Hours vs Exam Score")


[Link]("Hours Studied")
[Link]("Score (%)")

[Link]()

[Graph Window Opens Showing Red Dots going Upwards]

Practice Questions

Test your understanding:

1. Which Matplotlib module do we import as `plt`?


2. Which function is used to display the plot on the screen?
3. If you want to compare sales between 5 different branches, which type of chart is best?
4. Which function adds a label to the horizontal (X) axis?
5. True or False: Scatter plots connect data points with a straight line.

You might also like