The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr.
Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
THE KERICHO NATIONAL POLYTECHNIC
Department of ICT & Business
ARTIFICIAL INTELLIGENCE (AI)
Unit Code: ICT/OS/CS/CR/08/6/A
DETAILED TRAINING NOTES
Week 3 | Session 11
Python Data Types
Unit Code ICT/OS/CS/CR/08/6/A
Level Six (6)
Trainer Justus Koech (Mr.)
Class CSL6/S24(50) & CLS6/J25(40)
Session 11 of 18
Topic Python Data Types
Week 3 — Python Programming
Environment
Date 2026
Learning Outcomes — By the end of this session, trainees will be able to:
• Identify and describe all Python primitive data types: int, float, str, bool, and None
• Identify and use all Python collection data types: list, tuple, dict, and set
• Perform type conversion (casting) between compatible data types
• Apply common built-in operations and methods for each data type
• Identify the correct data type for a given programming situation
• Use the type() function to inspect variable types at runtime
• Understand mutability: which types can change and which cannot
• Write programs that use multiple data types together to solve real problems
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 1
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
TOC \h \o "1-3"
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 2
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
1. Introduction to Data Types
In Python, every piece of data has a type. A data type tells Python what kind of value a
variable holds, what operations can be performed on it, and how it is stored in memory.
Choosing the right data type is one of the most fundamental skills in programming — the
wrong type leads to errors, inefficiency, and unexpected behaviour.
Python is a dynamically typed language, which means you do not need to declare a
variable's type explicitly. Python automatically determines the type based on the value
you assign. You can also check a variable's type at any time using the built-in type()
function.
# Python automatically determines types
name = 'Justus' # str
age = 25 # int
gpa = 3.85 # float
enrolled = True # bool
result = None # NoneType
# Check type with type()
print(type(name)) # <class 'str'>
print(type(age)) # <class 'int'>
print(type(gpa)) # <class 'float'>
print(type(enrolled)) # <class 'bool'>
print(type(result)) # <class 'NoneType'>
1.1 Overview of All Python Data Types
Category Type Keyword Example Mutable?
Primitive Integer int age = 25 No
Primitive Float float pi = 3.14 No
Primitive String str 'Hello AI' No
Primitive Boolean bool True` / `False No
Primitive None Type None result = None No
Collection List list [1, 2, 3] Yes
Collection Tuple tuple (1, 2, 3) No
Collection Dictionary dict {'key': 'val'} Yes
Collection Set set {1, 2, 3} Yes
📌 Mutability Explained
A mutable type can be changed after creation — you can add, remove, or modify
elements. An immutable type cannot be changed once created — any 'modification'
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 3
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
creates a brand-new object. This distinction is critical in AI and data science, where
large datasets must be handled efficiently.
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 4
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
2. Integer — int
An integer is a whole number — positive, negative, or zero — with no decimal point.
Python's int type has unlimited precision, meaning it can hold numbers of any size
(limited only by available memory). This is different from many other languages that have
fixed-size integers.
2.1 Creating Integers
# Standard integers
students = 90
year = 2026
below_zero = -15
zero = 0
# Large integers — Python handles any size
big_num = 1_000_000_000 # underscores improve readability
factoria = 100 * 99 * 98 # result: 970200
# Different number bases
binary = 0b1010 # binary (base 2) = 10
octal = 0o17 # octal (base 8) = 15
hexa = 0xFF # hex (base 16) = 255
print(binary, octal, hexa) # 10 15 255
2.2 Integer Arithmetic Operators
Operator Operation Example Result
+ Addition 7 + 3 10
- Subtraction 7 - 3 4
* Multiplication 7 * 3 21
// Floor Division (integer 7 // 3 2
result)
% Modulus (remainder) 7 % 3 1
** Exponentiation (power) 2 ** 8 256
/ True Division (returns float) 7 / 2 3.5
-x Negation -7 -7
abs(x) Absolute value abs(-9) 9
# Arithmetic examples
a, b = 17, 5
print(a + b) # 22 — addition
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 5
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
print(a - b) # 12 — subtraction
print(a * b) # 85 — multiplication
print(a / b) # 3.4 — true division (gives float!)
print(a // b) # 3 — floor division (drops remainder)
print(a % b) # 2 — modulus (remainder after division)
print(a ** b) # 1419857 — 17 to the power of 5
# Practical use of modulus
number = 28
if number % 2 == 0:
print(f'{number} is even')
else:
print(f'{number} is odd')
# Check divisibility
if 100 % 4 == 0:
print('100 is divisible by 4') # True
2.3 Useful Integer Functions
Function Description Example Output
abs(x) Absolute value (positive) abs(-42) 42
pow(x, y) x to the power of y pow(2, 10) 1024
max(a, b, ...) Returns largest value max(3, 9, 7) 9
min(a, b, ...) Returns smallest value min(3, 9, 7) 3
sum(iterable) Adds all items in a list sum([1,2,3,4]) 10
round(x) Rounds to nearest integer round(3.7) 4
bin(x) Converts to binary string bin(10) '0b1010'
int(x) Converts to integer int('42') 42
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 6
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
3. Float — float
A float (floating-point number) represents a number with a decimal point. Python floats
use 64-bit double-precision IEEE 754 representation — giving approximately 15–17
significant decimal digits of precision. Floats are essential for scientific calculations,
measurements, percentages, and any situation requiring decimal values.
3.1 Creating Floats
# Basic floats
temperature = 36.8
pi = 3.14159265
negative = -0.5
whole = 5.0 # float, not int
# Scientific notation (e = 'times 10 to the power of')
tiny = 1.5e-4 # = 0.00015
huge = 2.3e6 # = 2300000.0
speed = 3.0e8 # speed of light approx (m/s)
print(tiny) # 0.00015
print(huge) # 2300000.0
# type() confirms it is a float
print(type(5.0)) # <class 'float'>
print(type(5)) # <class 'int'> — different!
3.2 Float Precision Warning
⚠ Floating-Point Precision
Floats cannot represent all decimal values exactly — this is a hardware limitation of
binary floating-point arithmetic. This can cause surprising results. For financial
calculations, use Python's decimal module instead.
# Surprising float behaviour
print(0.1 + 0.2) # 0.30000000000000004 (NOT 0.3!)
print(0.1 + 0.2 == 0.3) # False!
# Fix: use round() for comparisons
result = round(0.1 + 0.2, 2)
print(result) # 0.3
print(result == 0.3) # True
# Fix: use [Link]() for floating-point comparison
import math
print([Link](0.1 + 0.2, 0.3)) # True
# For money — use decimal module
from decimal import Decimal
total = Decimal('0.10') + Decimal('0.20')
print(total) # 0.30 (exact!)
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 7
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
3.3 Formatting Floats
value = 3.14159265358979
# Format to 2 decimal places
print(f'{value:.2f}') # 3.14
print(f'{value:.4f}') # 3.1416
# Scientific notation formatting
print(f'{value:.2e}') # 3.14e+00
# Percentage formatting
accuracy = 0.8745
print(f'Model accuracy: {accuracy:.1%}') # Model accuracy: 87.5%
# Padding and alignment
print(f'{value:10.3f}') # 3.142 (10 chars wide)
# Practical: BMI calculator
weight = 70.0 # kg
height = 1.75 # m
bmi = weight / (height ** 2)
print(f'BMI: {bmi:.1f}') # BMI: 22.9
3.4 Useful Float Functions
Function Description Example Output
round(x, n) Round to n decimal round(3.14159, 3.14
places 2)
[Link](x) Round down to nearest [Link](3.9) 3
int
[Link](x) Round up to nearest int [Link](3.1) 4
[Link](x) Square root [Link](144) 12.0
float(x) Convert to float float('3.14') 3.14
[Link](x) Check if Not a Number [Link](float True
('nan'))
[Link](x) Check if infinite [Link](float True
('inf'))
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 8
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
4. String — str
A string is a sequence of characters — letters, digits, symbols, spaces — enclosed in
single quotes, double quotes, or triple quotes. Strings are immutable (cannot be modified
after creation) and are one of the most heavily used types in Python, especially in AI
applications involving Natural Language Processing (NLP).
4.1 Creating Strings
# Single and double quotes — interchangeable
name1 = 'Kericho'
name2 = "National Polytechnic"
# Triple quotes — multi-line strings
address = '''
Kericho National Polytechnic
P.O. Box 2449-20200
Kericho, Kenya
'''
# Escape sequences inside strings
msg1 = 'It\'s raining today' # apostrophe
msg2 = "She said \"Hello!\"" # quote inside string
path = 'C:\\Users\\Justus\\data' # Windows path
tab = 'Name:\tJustus' # tab character
line = 'First line\nSecond line' # newline
# Raw strings — backslash not treated as escape
raw = r'C:\Users\Justus' # useful for file paths
4.2 String Indexing and Slicing
Strings are indexed sequences. Each character has a position (index) starting from 0 at
the left, or -1 at the right end. Slicing extracts a portion of a string using the syntax
string[start:stop:step].
word = 'PYTHON'
# 0 1 2 3 4 5 (positive index)
# -6-5-4-3-2-1 (negative index)
# Indexing — single character
print(word[0]) # 'P' — first character
print(word[-1]) # 'N' — last character
print(word[2]) # 'T' — third character
# Slicing — [start:stop] (stop is excluded)
print(word[0:3]) # 'PYT' — chars 0, 1, 2
print(word[2:]) # 'THON' — from index 2 to end
print(word[:4]) # 'PYTH' — from start to index 3
print(word[::2]) # 'PTO' — every other character
print(word[::-1]) # 'NOHTYP' — reversed!
# Practical reverse
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 9
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
text = 'racecar'
if text == text[::-1]:
print(f'{text} is a palindrome')
4.3 String Methods
Python strings come with a rich library of built-in methods. These are called using the dot
notation: [Link](). None of these methods modify the original string — they
always return a new string.
Method Description Example Output
upper() Convert to 'hello'.upper() 'HELLO'
UPPERCASE
lower() Convert to 'HELLO'.lower() 'hello'
lowercase
strip() Remove ' hi '.strip() 'hi'
leading/trailing
spaces
lstrip() Remove left ' hi'.lstrip() 'hi'
whitespace
rstrip() Remove right 'hi '.rstrip() 'hi'
whitespace
replace(old,n Replace substring 'cat'.replace('c' 'bat'
ew) ,'b')
split(sep) Split into a list 'a,b,c'.split(',' ['a','b','c']
)
join(list) Join list into string '-'.join(['a','b' 'a-b'
])
find(sub) Index of first match 'hello'.find('l') 2
(or -1)
count(sub) Count occurrences 'banana'.count('a 3
')
startswith(s) Check start 'Python'.startswi True
th('Py')
endswith(s) Check end '[Link]'.endswit True
h('.py')
isdigit() All characters are '123'.isdigit() True
digits
isalpha() All characters are 'abc'.isalpha() True
letters
title() Title Case 'hello 'Hello World'
world'.title()
center(n,c) Centre with fill 'AI'.center(10,'* '****AI****'
character ')
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 10
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
zfill(n) Pad with leading '42'.zfill(6) '000042'
zeros
# Practical string processing
raw_input = ' Justus Koech '
# Clean user input
clean = raw_input.strip().title()
print(clean) # 'Justus Koech'
# Parse CSV line
csv_line = 'Alice,25,Nairobi,CS'
fields = csv_line.split(',')
print(fields) # ['Alice', '25', 'Nairobi', 'CS']
name, age, city, course = fields
# Build formatted output
header = '-' * 40
print(header)
print(f'{'Name':<12} {'Age':>5} {'City':<12} Course')
print(f'{name:<12} {int(age):>5} {city:<12} {course}')
# Search in text
email = '[Link]@[Link]'
if '@' in email and [Link]('.ke'):
print('Valid Kenyan email address')
4.4 f-Strings (Formatted String Literals)
f-strings (introduced in Python 3.6) are the modern, preferred way to embed values and
expressions directly inside strings. They are faster and more readable than older
methods.
name = 'Alice'
marks = 87.4567
grade = 'A'
# Basic embedding
print(f'Student: {name}')
print(f'Marks: {marks}')
# Format specifiers inside f-strings
print(f'Marks: {marks:.2f}') # 2 decimal places: 87.46
print(f'Marks: {marks:8.2f}') # padded to 8 chars: 87.46
print(f'Grade: {grade:^10}') # centred in 10: A
# Expressions inside f-strings
price = 1500
vat = 0.16
print(f'Price + VAT = KSh {price * (1 + vat):.2f}')
# Output: Price + VAT = KSh 1740.00
# Calling methods inside f-strings
raw = ' kericho polytechnic '
print(f'Institution: {[Link]().title()}')
# Output: Institution: Kericho Polytechnic
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 11
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 12
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
5. Boolean — bool
A boolean can hold only one of two values: True or False (note the capital first letter —
this is required in Python). Booleans are the result of any comparison or logical operation
and are the foundation of all decision-making (if statements) and loop conditions. In
Python, bool is a subclass of int — True equals 1 and False equals 0.
5.1 Boolean Values and Comparisons
# Boolean values
is_enrolled = True
has_paid = False
# Comparison operators return bool
print(5 > 3) # True
print(5 == 3) # False
print(10 != 7) # True
print(4 >= 4) # True
# Logical operators
age = 20
gpa = 3.6
eligible = age >= 18 and gpa >= 3.0
print(eligible) # True
weekend = True
holiday = False
day_off = weekend or holiday
print(day_off) # True
print(not True) # False
print(not False) # True
5.2 Truthy and Falsy Values
Every Python object has a truth value. When used in a boolean context (such as an if
statement), objects evaluate as either truthy (behave like True) or falsy (behave like
False). Understanding this removes the need for many explicit comparisons.
Falsy Values (evaluate as False) Truthy Values (evaluate as True)
`0` (integer zero) Any non-zero number (`1`, `-5`, `3.14`)
`0.0` (float zero) Any non-empty string (`'a'`, `'0'`)
`''` (empty string) Any non-empty list (`[0]`, `[False]`)
`[]` (empty list) Any non-empty dict (`{'a': 0}`)
`{}` (empty dict or set) Any non-empty set (`{0}`)
`()` (empty tuple) Any non-empty tuple (`(0,)`)
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 13
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
`None` Any object unless it defines `__bool__` as
False
`False` `True`
# Using truthy/falsy — no need for explicit == check
name = input('Enter your name: ')
if name: # truthy if name is non-empty string
print(f'Hello, {name}!')
else:
print('Name cannot be empty.')
# Check if list has items
scores = []
if scores:
average = sum(scores) / len(scores)
else:
print('No scores entered yet.')
# Bool as integers
print(True + True) # 2 (True = 1)
print(False * 100) # 0 (False = 0)
print(sum([True, False, True, True])) # 3 — count of True values
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 14
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
6. NoneType — None
None is Python's way of representing the absence of a value — the equivalent of null in
other languages. There is only ONE None object in Python (it is a singleton). None is
commonly used as a default return value for functions that don't return anything, as a
placeholder for variables not yet assigned, and to signal missing or unknown data.
# None as placeholder
result = None
user_input = None
# Functions return None by default
def greet(name):
print(f'Hello, {name}!') # prints but returns nothing
output = greet('Justus') # prints: Hello, Justus!
print(output) # None
# ALWAYS test for None with 'is' or 'is not' — NOT with ==
if result is None:
print('No result yet')
if result is not None:
print(f'Result: {result}')
# None in data processing — mark missing values
student_data = {'name': 'Bob', 'marks': None, 'grade': None}
if student_data['marks'] is None:
print(f"Marks not yet entered for {student_data['name']}")
💡 Why use `is` and not `==` for None?
None is a singleton — there is only one None object. Using 'is' checks identity (same
object), while '==' checks equality (same value). Although '== None' usually works, 'is
None' is the correct, Pythonic way and avoids edge cases with custom objects that
override ==.
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 15
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
7. List — list
A list is an ordered, mutable collection of items enclosed in square brackets [ ]. Items can
be of any type and can be mixed. Lists are the most versatile and widely used Python
collection — they are the backbone of data science, AI datasets, and almost every real-
world Python program.
7.1 Creating Lists
# Lists of different types
numbers = [10, 20, 30, 40, 50]
names = ['Alice', 'Bob', 'Carol', 'David']
mixed = [1, 'hello', 3.14, True, None]
nested = [[1, 2], [3, 4], [5, 6]] # list of lists
empty = [] # empty list
# Create with list() constructor
chars = list('Python') # ['P', 'y', 't', 'h', 'o', 'n']
nums = list(range(1, 6)) # [1, 2, 3, 4, 5]
print(len(names)) # 4 — number of items
7.2 Indexing and Slicing (same as strings)
fruits = ['mango', 'avocado', 'banana', 'passion', 'guava']
# 0 1 2 3 4
print(fruits[0]) # 'mango' — first item
print(fruits[-1]) # 'guava' — last item
print(fruits[1:4]) # ['avocado', 'banana', 'passion']
print(fruits[::-1]) # reversed list
# Nested list access
matrix = [[1,2,3],[4,5,6],[7,8,9]]
print(matrix[1][2]) # 6 — row 1, col 2
7.3 Modifying Lists
scores = [85, 72, 90, 65, 88]
# Change an item
scores[1] = 75
print(scores) # [85, 75, 90, 65, 88]
# Add items
[Link](95) # add to END: [85, 75, 90, 65, 88, 95]
[Link](0, 100) # insert at position 0: [100, 85, ...]
[Link]([70, 80]) # add multiple: [..., 70, 80]
# Remove items
[Link](65) # removes FIRST occurrence of 65
popped = [Link]() # removes and returns LAST item
popped2 = [Link](0) # removes and returns item at index 0
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 16
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
del scores[0] # deletes item at index 0
# Sorting
[Link]() # sort ascending IN PLACE
[Link](reverse=True) # sort descending IN PLACE
sorted_copy = sorted(scores) # returns NEW sorted list, original unchanged
# Other operations
[Link]() # reverse in place
count_90 = [Link](90) # count occurrences
idx = [Link](90) # find index of value
[Link]() # remove all items
7.4 List Methods Summary
Method What it does Modifies original?
append(x) Add item x to end Yes
insert(i, x) Insert x at position i Yes
extend(iterable) Add all items from iterable to end Yes
remove(x) Remove first occurrence of x Yes
pop(i=-1) Remove & return item at index i Yes
(default: last)
sort() Sort list in ascending order Yes
reverse() Reverse list in place Yes
clear() Remove all items Yes
index(x) Return index of first x No
count(x) Count occurrences of x No
copy() Return a shallow copy No
sorted(list) Return NEW sorted list No (built-in)
len(list) Number of items No (built-in)
7.5 List Comprehension
List comprehension is a concise and fast way to create a new list by applying an
expression to each item in an existing sequence. It is a core Python skill used extensively
in data science.
# Syntax: [expression for item in iterable if condition]
# Basic — squares of 1 to 10
squares = [x**2 for x in range(1, 11)]
print(squares) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# With condition — only even numbers
evens = [x for x in range(1, 21) if x % 2 == 0]
print(evens) # [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 17
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
# Transform strings
names = ['alice', 'bob', 'carol']
upper = [[Link]() for name in names]
print(upper) # ['ALICE', 'BOB', 'CAROL']
# Extract passing students
results = [('Alice',88),('Bob',45),('Carol',72),('David',38)]
passing = [name for name, score in results if score >= 50]
print(passing) # ['Alice', 'Carol']
# Grade each score
scores = [88, 45, 72, 38, 91, 65]
grades = ['A' if s>=80 else 'B' if s>=70 else 'C' if s>=50 else 'F'
for s in scores]
print(grades) # ['A', 'F', 'C', 'F', 'A', 'C']
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 18
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
8. Tuple — tuple
A tuple is an ordered, immutable collection of items enclosed in parentheses ( ). Once
created, a tuple cannot be modified — you cannot add, remove, or change items. Tuples
are used when data should not change: coordinates, RGB colours, database records,
function return values.
8.1 Creating Tuples
# Creating tuples
point = (3, 7) # 2D coordinate
rgb = (255, 128, 0) # orange colour
student = ('Alice', 21, 'CS6') # student record
single = (42,) # ONE-item tuple — comma is REQUIRED!
not_tuple = (42) # This is just int 42 — NOT a tuple!
# Parentheses are optional
coords = 10, 20, 30 # valid tuple
# From list
t = tuple([1, 2, 3]) # (1, 2, 3)
print(type((42,))) # <class 'tuple'>
print(type((42))) # <class 'int'> — not tuple!
8.2 Tuple Operations
student = ('Alice', 21, 'Computer Science', 3.85)
# Indexing (same as list)
print(student[0]) # 'Alice'
print(student[-1]) # 3.85
# Slicing
print(student[1:3]) # (21, 'Computer Science')
# Unpacking — assign each element to a variable
name, age, course, gpa = student
print(f'{name} is {age} studying {course} (GPA: {gpa})')
# Unpacking with * for remaining items
first, *rest = (1, 2, 3, 4, 5)
print(first) # 1
print(rest) # [2, 3, 4, 5]
# Swap variables using tuple unpacking
a, b = 10, 20
a, b = b, a # elegant swap — no temp variable!
print(a, b) # 20 10
# Functions returning multiple values (returns a tuple)
def min_max(numbers):
return min(numbers), max(numbers) # returns tuple
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 19
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
lo, hi = min_max([3, 1, 8, 5, 2])
print(f'Min: {lo}, Max: {hi}') # Min: 1, Max: 8
💡 Tuple vs List — When to Use Which
Use a tuple when the data represents a fixed, unchangeable record (e.g., a coordinate,
a date, a student ID + name pair). Use a list when the collection may need to grow,
shrink, or be reordered. Tuples are slightly faster and can be used as dictionary keys
(lists cannot).
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 20
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
9. Dictionary — dict
A dictionary stores data as key-value pairs enclosed in curly braces { }. Each key maps to
a value — like a real-world dictionary where a word (key) maps to its definition (value).
Keys must be unique and immutable (strings, numbers, or tuples). Values can be any
type. Dictionaries are the most important collection type for AI and data science — they
are used to represent data records, model parameters, JSON data, and feature vectors.
9.1 Creating Dictionaries
# Basic dictionary
student = {
'name': 'Alice Wanjiru',
'age': 21,
'course': 'Computer Science',
'level': 6,
'gpa': 3.85,
}
# One-liner
config = {'host': 'localhost', 'port': 5432, 'db': 'knp_ai'}
# From dict() constructor
person = dict(name='Bob', age=25, city='Kericho')
# Empty dictionary
empty = {}
empty2 = dict()
print(len(student)) # 5 — number of key-value pairs
9.2 Accessing and Modifying
student = {'name': 'Alice', 'age': 21, 'gpa': 3.85}
# Access by key
print(student['name']) # 'Alice'
print(student['gpa']) # 3.85
# Safe access with .get() — avoids KeyError
print([Link]('marks')) # None (key doesn't exist)
print([Link]('marks', 0)) # 0 (default value)
# Modify existing key
student['age'] = 22
# Add new key
student['email'] = 'alice@[Link]'
# Delete a key
del student['gpa']
removed = [Link]('age') # removes & returns value
# Check if key exists
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 21
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
if 'name' in student:
print(student['name'])
# Update multiple keys at once
[Link]({'level': 6, 'course': 'CS'})
9.3 Iterating Over Dictionaries
scores = {'Alice': 88, 'Bob': 72, 'Carol': 91, 'David': 45}
# Iterate keys (default)
for name in scores:
print(name)
# Iterate values
for score in [Link]():
print(score)
# Iterate key-value pairs (MOST USEFUL)
for name, score in [Link]():
grade = 'A' if score >= 80 else 'B' if score >= 70 else 'F'
print(f'{name:<10}: {score} ({grade})')
# Dictionary comprehension
grades = {name: 'PASS' if score >= 50 else 'FAIL'
for name, score in [Link]()}
print(grades)
# {'Alice': 'PASS', 'Bob': 'PASS', 'Carol': 'PASS', 'David': 'FAIL'}
9.4 Dictionary Methods
Method Description Returns
keys() View of all keys dict_keys object
values() View of all values dict_values object
items() View of all (key, value) pairs dict_items object
get(key, default) Get value safely (no KeyError) value or default
pop(key) Remove & return value for key removed value
update(dict2) Merge dict2 into this dict None (modifies in place)
copy() Return a shallow copy new dict
clear() Remove all items None
setdefault(key, Get key; set to val if missing value
val)
9.5 Nested Dictionaries
# Real-world: class register
class_register = {
'CS001': {'name': 'Alice', 'marks': 88, 'paid': True},
'CS002': {'name': 'Bob', 'marks': 75, 'paid': True},
'CS003': {'name': 'Carol', 'marks': 92, 'paid': False},
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 22
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
# Access nested data
print(class_register['CS001']['name']) # 'Alice'
print(class_register['CS003']['marks']) # 92
# Process nested dict
for reg_no, info in class_register.items():
status = 'PAID' if info['paid'] else 'UNPAID'
print(f"{reg_no}: {info['name']:<10} {info['marks']} [{status}]")
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 23
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
10. Set — set
A set is an unordered collection of unique elements enclosed in curly braces { }. Sets
automatically remove duplicates and are highly optimised for membership testing
(checking if an item exists). They support mathematical set operations: union,
intersection, difference, and symmetric difference — making them ideal for data
deduplication and comparison tasks in AI.
10.1 Creating Sets
# Basic sets
primes = {2, 3, 5, 7, 11, 13}
vowels = {'a', 'e', 'i', 'o', 'u'}
# Duplicates are automatically removed!
tags = {'python', 'AI', 'ML', 'python', 'AI', 'data'}
print(tags) # {'python', 'AI', 'ML', 'data'} — 3 unique items
# From list (useful for deduplication!)
scores = [85, 72, 90, 85, 72, 91, 85]
unique_scores = set(scores)
print(unique_scores) # {72, 85, 90, 91}
# Empty set — MUST use set(), not {} (that creates empty dict!)
empty_set = set()
empty_dict = {} # this is a dict, NOT a set
print(type(set())) # <class 'set'>
print(type({})) # <class 'dict'> — careful!
10.2 Set Operations
# Set operations — using operator symbols
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A | B) # Union — all items from both: {1,2,3,4,5,6,7,8}
print(A & B) # Intersection — items in BOTH: {4, 5}
print(A - B) # Difference — in A but NOT in B: {1, 2, 3}
print(A ^ B) # Sym. diff. — in either but NOT both: {1,2,3,6,7,8}
# Using methods (equivalent)
print([Link](B))
print([Link](B))
print([Link](B))
print(A.symmetric_difference(B))
# Subset / superset checks
print({2, 3} <= A) # True — {2,3} is subset of A
print(A >= {1, 2}) # True — A is superset of {1,2}
# Real example: find students in both morning and afternoon class
morning = {'Alice', 'Bob', 'Carol', 'David', 'Emma'}
afternoon = {'Carol', 'David', 'Frank', 'Grace'}
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 24
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
both = morning & afternoon
either = morning | afternoon
only_am = morning - afternoon
print(f'In both: {both}')
print(f'In either class: {either}')
print(f'Morning only: {only_am}')
10.3 Set Methods
Method Description Example
add(x) Add element x [Link](10)
remove(x) Remove x — raises KeyError if [Link](5)
missing
discard(x) Remove x — no error if missing [Link](5)
pop() Remove and return an arbitrary [Link]()
element
clear() Remove all elements [Link]()
copy() Return shallow copy t = [Link]()
update(s2) Add all items from s2 [Link]({6,7})
issubset(s2) True if all items in s2 {1,2}.issubset({1,2,3})
issuperset(s2) True if contains all of s2 {1,2,3}.issuperset({1,2})
isdisjoint(s2) True if no common elements {1,2}.isdisjoint({3,4})
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 25
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
11. Type Conversion (Type Casting)
Type conversion (also called casting) is the process of converting a value from one data
type to another. Python supports both implicit conversion (done automatically) and
explicit conversion (done manually using built-in functions).
11.1 Implicit Conversion (Automatic)
Python automatically converts types when mixing compatible types in an expression —
usually promoting to the 'wider' type to avoid data loss:
# int + float → float (Python widens automatically)
result = 5 + 2.0
print(result) # 7.0 (float, not int)
print(type(result)) # <class 'float'>
# int + bool → int (True=1, False=0)
total = 10 + True
print(total) # 11
11.2 Explicit Conversion (Manual Casting)
Function Converts to Valid Input Examples Raises Error If
int(x) Integer int('42')`, `int(3.9)`, `int('3.14')` — has decimal
`int(True)
float(x) Float float('3.14')`, `float('hello')` — not
`float(7)`, numeric
`float('1e3')
str(x) String str(42)`, `str(3.14)`, Almost never fails
`str(True)
bool(x) Boolean bool(0)`, `bool('')`, Almost never fails
`bool([1])
list(x) List list('abc')`, Non-iterable
`list((1,2,3))
tuple(x) Tuple tuple([1,2,3])`, Non-iterable
`tuple('abc')
set(x) Set set([1,2,2,3]) Non-iterable
dict(x) Dict dict([('a',1),('b',2)]) Non key-value pairs
# Common conversion patterns
# String → int (user input is always a string)
age_str = input('Enter your age: ') # '25'
age_int = int(age_str)
print(age_int + 1) # 26
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 26
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
# String → float
price = float('1499.99')
# int → string (for concatenation or formatting)
level = 6
message = 'You are in Level ' + str(level)
print(message) # 'You are in Level 6'
# float → int (truncates — does NOT round)
print(int(3.9)) # 3 — decimal part is dropped, not rounded!
print(int(-3.9)) # -3 — truncates toward zero
# Safe conversion with error handling
def safe_int(value, default=0):
try:
return int(value)
except (ValueError, TypeError):
return default
print(safe_int('42')) # 42
print(safe_int('hello')) # 0 (default)
print(safe_int(None)) # 0 (default)
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 27
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
12. Mutability — A Critical Concept
Mutability is one of the most important concepts in Python. It determines whether an
object's value can be changed after it is created. Getting this wrong causes some of the
most subtle and hard-to-find bugs in Python programs.
Immutable Types (cannot change) Mutable Types (can change)
int, float, bool, str, None list, dict, set
tuple (custom objects by default)
Any 'change' creates a NEW object Same object is modified in place
Safe to use as dictionary keys Cannot be used as dictionary keys
Can be used in sets Cannot be stored in sets
Thread-safe by default Requires care in concurrent code
# IMMUTABLE — strings cannot be changed
name = 'alice'
name[0] = 'A' # TypeError: 'str' object does not support item
assignment
# Instead, create a new string
name = 'A' + name[1:]
print(name) # 'alice' — wait... original?
# Actually name now points to new string 'alice' — let's fix:
name = 'alice'
name = [Link]()
print(name) # 'Alice'
# MUTABLE — lists can be changed
scores = [85, 72, 90]
scores[1] = 75 # OK — changes in place
print(scores) # [85, 75, 90]
# Dangerous: multiple variables pointing to same list
a = [1, 2, 3]
b = a # b is NOT a copy — it points to the SAME list!
[Link](4)
print(a) # [1, 2, 3, 4] — a changed too!
# Fix: make a copy
a = [1, 2, 3]
b = [Link]() # or: b = a[:] or: b = list(a)
[Link](4)
print(a) # [1, 2, 3] — a unchanged
print(b) # [1, 2, 3, 4]
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 28
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
13. Common Data Type Errors
Error Cause Fix
TypeError: can only Mixing str + int without 'Age: ' + str(age)
concatenate str, not int conversion
ValueError: invalid Passing non-numeric string Use `try/except` or validate
literal for int() to `int()` first
KeyError: 'key' Accessing dict key that Use `.get()` instead of `[]`
doesn't exist
IndexError: list index Index beyond list length Check `len()` or use
out of range `try/except`
TypeError: 'int' not Trying to index a non- Check type before indexing
subscriptable sequence
TypeError: unhashable Using list as a dict key or in Convert to tuple first
type: 'list' a set
AttributeError: 'int' has Calling string method on Convert: `str(x).upper()`
no attribute 'upper' non-string
SyntaxError: can't Using `=` inside `if`: `if x = Use `==` for comparison
assign to literal 5`
Unexpected float result: Float precision limitation Use `round()` or
`0.1+0.2 != 0.3` `[Link]()`
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 29
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
14. Comprehensive Program — Student Database
The following program demonstrates all Python data types working together in a realistic
student management scenario:
# Student Database — Demonstrates all Python data types
# Kericho National Polytechnic — AI Training Session 11
# ── Data store using all collection types ──────────────
# dict: student records (key=reg no, value=student info dict)
students = {
'CS001': {'name': 'Alice Wanjiru', 'age': 21, 'marks': [88, 75, 92],
'paid': True},
'CS002': {'name': 'Bob Otieno', 'age': 23, 'marks': [65, 72, 58],
'paid': True},
'CS003': {'name': 'Carol Mwangi', 'age': 20, 'marks': [91, 88, 95],
'paid': False},
'CS004': {'name': 'David Kipchoge', 'age': 22, 'marks': [45, 52, 38],
'paid': True},
'CS005': {'name': 'Emma Cherono', 'age': 21, 'marks': [78, 84, 80],
'paid': True},
}
# set: subjects taught
subjects = {'Mathematics', 'English', 'Computer Science'}
# tuple: grade boundaries (immutable)
BOUNDARIES = ((80,'A','Distinction'),(70,'B','Credit'),
(60,'C','Merit'),(50,'D','Pass'),(0,'F','Fail'))
# ── Helper functions ───────────────────────────────────
def get_grade(average: float) -> tuple:
for boundary, grade, remark in BOUNDARIES:
if average >= boundary:
return grade, remark
return 'F', 'Fail'
def student_average(marks: list) -> float:
return sum(marks) / len(marks) if marks else 0.0
# ── Generate report ────────────────────────────────────
print('=' * 65)
print(' KERICHO NATIONAL POLYTECHNIC — STUDENT REPORT')
print('=' * 65)
print(f"{'Reg No':<8} {'Name':<20} {'Avg':>6} {'Grade':>5} {'Status':<12}
Fee")
print('-' * 65)
grade_counts = {} # dict: count per grade
all_averages = [] # list: all averages
unpaid_students = set() # set: reg nos of unpaid
for reg_no, info in [Link]():
avg = student_average(info['marks'])
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 30
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
grade, remark = get_grade(avg)
paid = 'PAID' if info['paid'] else 'UNPAID'
status = 'PASS' if grade != 'F' else 'FAIL'
print(f"{reg_no:<8} {info['name']:<20} {avg:>6.1f} {grade:>5}
{status:<12} {paid}")
# Accumulate statistics
all_averages.append(avg)
grade_counts[grade] = grade_counts.get(grade, 0) + 1
if not info['paid']:
unpaid_students.add(reg_no)
# ── Summary statistics ─────────────────────────────────
print('=' * 65)
print(f'CLASS AVERAGE: {sum(all_averages)/len(all_averages):.1f}')
print(f'HIGHEST: {max(all_averages):.1f}')
print(f'LOWEST: {min(all_averages):.1f}')
print(f'GRADE DIST: {grade_counts}')
print(f'UNPAID: {unpaid_students if unpaid_students else "None"}')
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 31
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
15. Activities and Assessment
15.1 Short Answer Questions
1. What is the difference between a mutable and an immutable data type? Give one
example of each.
1. Why does 0.1 + 0.2 not equal 0.3 in Python? How can you work around this?
2. What is the difference between a list and a tuple? When would you choose one over
the other?
2. What is the difference between a dictionary and a set? What do they have in
common?
3. Explain the difference between dict['key'] and [Link]('key'). When would you use
each?
3. What happens when you do b = a where a is a list? How do you make a proper
independent copy?
4. Why can you not use {} to create an empty set? What must you use instead?
4. Explain truthy and falsy values. Give three examples of falsy values in Python.
15.2 Practical Exercises
Exercise 1 — Type Explorer
• Create one variable of each Python primitive type: int, float, str, bool, None.
• Print each variable, its value, and its type using the type() function.
• Perform at least two arithmetic operations on the int and float values.
• Demonstrate implicit type conversion by adding an int and a float together.
• Convert the float to an int and explain what happens to the decimal part.
Exercise 2 — String Processor
• Ask the user to enter a full sentence.
• Count and print: total characters, total words (split by space), number of vowels.
• Print the sentence in: UPPERCASE, lowercase, Title Case, and reversed.
• Check if the sentence is a palindrome (ignoring spaces and case).
• Replace all occurrences of a word the user specifies with another word.
Exercise 3 — List Data Analysis
• Create a list of 10 student marks entered by the user (use a for loop and input()).
• Calculate and print: mean, median, minimum, maximum, and range.
• Sort the list and print it in both ascending and descending order.
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 32
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
• Use list comprehension to create a second list of only marks >= 50 (passes).
• Count how many students passed and how many failed.
Exercise 4 — Dictionary Contact Book
• Build a contact book using a dictionary where keys are names and values are
phone numbers.
• Write a menu-driven program (use while loop) with options: Add, Search, Delete,
Display All, Quit.
• On Add: check if the name already exists before adding.
• On Search: use .get() to safely look up a contact.
• On Display All: sort contacts alphabetically by name and print them formatted.
Exercise 5 — Set Operations Analyser
• Read two lists of student names from the user (keep asking until they enter
'done').
• Convert each list to a set.
• Print: students in BOTH groups, students in EITHER group, students ONLY in
group 1, students ONLY in group 2.
• Check if group 1 is a subset of group 2 or vice versa.
• Use these results to explain the set operation that was performed in each case.
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 33
The Kericho National Polytechnic — Artificial Intelligence (AI) | Mr. Justus Koech | Level 6ICT/OS/CS/CR/08/6/A
16. Quick Reference — All Python Data Types
Type Syntax Mutable Ordered Duplicates Key Use
int x = 42 No — — Counting,
indexing, loops
float x = 3.14 No — — Measurements,
calculations
str x = 'text' No Yes Yes Text, NLP, display
bool x = True No — — Conditions, flags
None x = None No — — Missing values,
placeholders
list x = [1,2] Yes Yes Yes Dynamic
sequences,
datasets
tuple x = (1,2) No Yes Yes Fixed records,
return values
dict x = {k:v} Yes Yes* Keys Labelled data,
unique JSON, features
set x = {1,2} Yes No No Uniqueness,
membership, set
math
— End of Training Notes: Python Data Types —
ICT/OS/CS/CR/08/6/A | Kericho National Polytechnic | Mr. Justus Koech | Term One, 2026
Python Data Types | Session 11 | CSL6/S24 & CLS6/J25 Page 34