Funmilayo T. Learn Python Programming in 9 Weeks. A Beginner's Guide... 2025
Funmilayo T. Learn Python Programming in 9 Weeks. A Beginner's Guide... 2025
PROGRAMMING IN 9 WEEKS
TJ
<
H
I
0
z
Everything You Need to Kickstart Your Python
Learning Journey
Tobun Funmilayo
INTRODUCTION
About Python: Why Learn Python?
Python is one of the most popular programming languages
in the world, known for its simplicity and versatility. Whether
you're a complete beginner or transitioning from another
programming language, Python provides a gentle learning
curve and is used in a variety of fields such as web
development, data analysis, machine learning, automation,
and more.
Here are some reasons why Python is the ideal language to
start your coding journey:
Setting Up Python
Before you start cooking, you need to set up your kitchen
(or in this case, your computer). Let’s make sure Python is
installed and ready to go!
1. Install Python:
Head over to the official Python website and
download the latest version of Python for your
operating system (Windows, macOS, or Linux).
During installation, make sure to check the box that
says "Add Python to PATH". This step is essential
to running Python from the terminal.
2. Choose an IDE (Integrated Development
Environment):
Think of your IDE as your workspace. It’s where
you’ll write your Python code, test it, and see the
results. You can use a simple text editor or a
dedicated Python IDE. Here are some great options:
v VS Code: Lightweight and highly
customizable.
p PyCharm: A more robust, feature-packed
IDE great for beginners and professionals
alike.
j Jupyter Notebook: Ideal for data scientists
and those who want to combine code with
visualizations. To learn more watch
installation video here:
https://www.youtube.com/watch?
v=LZE81pQn48M
WEEK 1:
UNDERSTANDING THE
BASICS: SYNTAX,
VARIABLES, AND DATA
TYPES
Python is known for its clean and simple syntax, making it a
favorite for beginners and professionals alike. Unlike many
other programming languages that use curly braces {} or
semicolons, Python emphasizes readability and simplicity.
Python Syntax
Syntax refers to the rules that define how Python code is
written and understood. Fortunately, Python’s syntax is very
readable—it’s almost like writing English! This makes it
easier to learn and understand what your code is doing at a
glance.
Welcome to Python!
Let's learn the basics.
1. Indentation Matters
2. Case Sensitivity
3. Using Comments
ExamplesofDifferentDataTypes:
: # Integer (Whole number)
age = 30|
print(type(age))
# String (Text)
greeting = "Hello., World!"
print(type{greeting))
(
# Boolean (True/Fatse)
is_python_fun = True
print(type(is_python_fun) )
cclass 'int's
<class 'float's
Cclass 'str'>
cclass 'bool's
cclass 'list's
<class 'tuple's
Cclass 'diet's
cclass 'set's
TYPE CONVERSION
(CASTING)
Sometimes, we need to convert one data type to another.
This is called type conversion or casting.
Python makes it easy to change data types using built-in
functions like int(), float(), str(), and bool().
Age: 25
50
More Resources:
• https://youtu.be/0Klynunhvks
• https://youtu.be/6g7AQ 7qyRQ,
• https://youtu.be/LZE81pQn48M
• https://youtu.be/xi6US7kC-ko
• https://youtu.be/x1jPlAGaHeo
• https://youtu.be/whSOOi MNoY
• https://youtu.be/2Z4Hl 2NeBM
• https://youtu.be/udN0FO-j2qs
Conclusion
Understanding syntax, variables, and data types is essential
before moving to more complex topics. These are the core
building blocks of Python, and getting comfortable with
them will make everything else easier to learn.
if condition:
# Code to execute if the condition is true
Example:
age = 18
if age >= 18:
print("¥ou are eligible to vote.”)
Syntax:
if condition:
# Code to execute if the condition is true
else:
# Code to execute if the condition is faise
Example:
num = I®
if num % 2 == 0:
print("Even number”)
else:
print("Odd number")
Even number
IF-ELIF-ELSE
STATEMENT
Used when multiple conditions need to be checked in
sequence. The first condition that evaluates to true is
executed.
Syntax:
if condition!:
# Code for condition!
elif condition?:
# Code for condition2
else:
# Code if none of the conditions are true
Example:
marks = 85
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: 8")
else:
print("Grade: C")
Grade: B
LOGICAL OPERATORS IN
CONDITIONALS
Logical operators let you combine multiple conditions inside
an if statement. This helps you build more flexible and
powerful decision-making logic.
Python provides three main logical operators:
Operat Meaning Example
or
and True if both conditions are true x > 5 and x <
10
or True if at least one condition is x > 5 or x < 3
true
not Reverses the Boolean value not (x > 5)
More Resources:
• https://www.youtube.com/watch?v=Vb 4OHiMv8I
• https://www.youtube.com/watch?v=ejJIIHmXLWs&t=51s
LOOPING STATEMENTS
IN PROGRAMMING
Looping statements allow a program to execute a block of
code multiple times. This is especially useful when you want
to repeat a task or go through items in a collection like a list
or a string.
Instead of writing the same line of code again and again,
you can use a loop to do it for you. This makes your
programs shorter, cleaner, and more efficient.
FOR LOOP
The for loop is used to iterate over a sequence (like a list,
tuple, string, or range) and execute a block of code for each
item in the sequence. Think of it like a checklist. For every
item on the list, you do something with it.
Syntax:
for variable in sequence;
# Code to execute for each item
Examplel: Iteratingoveralist
fruits = ["apple”, "banana", "cherry"]
for fruit in fruits:
I
print(fruit)
apple
banana
cherry
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
More Resources:
• httPs://youtu.be/A9XKQGvZv44?si=OlkDqXkh-
XX88rXO
WHILE LOOP
The while loop executes a block of code as long as the
given condition is true. The moment the condition
becomes false, the loop stops running.
This type of loop is useful when you don’t know in
advance how many times something needs to happen — it
just keeps going until a certain condition is no longer met
Syntax:
while condition:
# Code to execute as Long as condition is true
counter = 1
while counter <= 5:
print(f"Counter: {counter}”)
counter += 1 # Increment the counter
Counter: 1
Counter: 2
Counter: 3
Counter: 4
Counter: 5
More Resources:
• https://www.youtube.com/watch?v=Ut LzKeSaIo
Conclusion
Control flow is a fundamental concept in Python that allows
programs to make decisions and repeat tasks efficiently.
Without it, your code would always run in a straight line,
with no flexibility.
By mastering conditionals (if, if-else, if-elif-else) and loops
(for, while), you unlock the ability to build programs that
respond to different inputs, repeat actions, and solve real-
world problems.
These tools are the backbone of almost every Python
project, from simple calculators to complex games and
apps.
Keep practicing with different combinations of conditions
and loops. Try writing your own mini programs like a number
guessing game, a basic menu system, or even a simple
quiz. The more you use control flow, the more confident
you’ll become in writing flexible and powerful Python code.
WEEKLY CODING
EXERCISES
Question 1:
Write a Python program to check if a number is positive,
negative, or zero.
Hint:
Use an if-elif-else statement to compare the number with 0.
Expected Output Example:
For number = -5, the output should be:
The number is negative.
Question 2:
Create a Python program that takes a person's age as input
and categorizes them into the following age groups:
Hint:
Use if-elif-else conditions to define the categories.
Expected Output Example:
For age = 25, the output should be:
You are an Adult.
Question 3:
Write a Python program that calculates the grade of a
student based on their score using the following conditions:
• 90 and above: Grade A
8 80-89: Grade B
7 70-79: Grade C
6 60-69: Grade D
• Below 60: Grade F
Question 4:
Write a Python program that simulates a simple guessing
game:
Hint:
Real-World Analogy
Think of a coffee machine. You press a button, and it
makes coffee for you. Inside the machine, there are steps
happening (grinding beans, boiling water, pouring coffee),
but you don't need to repeat those steps manually each
time—you just press the button!
A Python function works the same way. You write the
function once and use it whenever needed.
Parts of a Function
# Defining a function
def function_name():
# Code bLock
print("This is a function")
# CaLLing a function
function_name()
This is a function
BASIC STRUCTURE OF A
FUNCTION IN PYTHON
Here’swhatasimplefunctionlookslike:
def make_coffee():
print("Grinding coffee beans...")
print("Boiling water...")
print ("Pouring coffee into the cup.,..")
print("Yciur coffee is ready! 0")
How it Works:
The machine (or the function) follows the same process, but
the input (your choice of coffee) affects the result.
def make_coffee(type_of_coffee) :
print(f"Making a {type_of_coffee} coffee...")
print("Grinding coffee beans...")
print("Boiling water...")
print("Pouring coffee into the cup...")
print(f"Your ’type_of_coffee} coffee is ready! o")
How it Works:
# Perform operations
sum_result = add_numbers(10, 5)
difference_result = subtract_numbers(10, 5)
• https://youtu.be/ZwZMtvzBwJQ
• https://youtu.be/PtHPXoQEpFY
Conclusion
Functions are one of the most powerful tools in Python. They
help you write cleaner, more organized, and reusable code.
By grouping related instructions into functions, you avoid
repetition and make your programs easier to manage.
You’ve now learned how to:
3. Temperature Converter:
Write a function convert_to_fahrenheit(celsius) that converts
a temperature from
Celsius to Fahrenheit.
Formula: (Celsius * 9/5) + 32 = Fahrenheit. Call the function
with a temperature of
20°C.
4. Number Cruncher:
Create a function add_two_numbers(num1, num2) that
takes two numbers as
arguments and returns their sum. Test the function by
adding 3 and 7.
Intermediate Level
1. Math Quiz:
Write a function math_quiz(num1, num2) that accepts two
numbers and returns the
sum, difference, product, and quotient of these two
numbers in a tuple. For example:
(sum, difference, product, quotient). Call the function with 5
and 3.
2. Magic Box:
Create a function magic_box(item1, item2) that returns a
sentence like: "You have
placed <item1> and <item2> in the magic box!". Make the
items "a book" and "a
pen". Test the function with different items.
5. Discount Finder:
Write a function calculate_discount(price,
discount_percentage) that takes the price of
an item and a discount percentage and returns the price
after discount. For example, a
price of 100 with a discount of 20% should return 80.
Advanced Level
1. Palindrome Checker:
Write a function is_palindrome(word) that takes a string and
checks if it is a
palindrome. If it is, return "It’s a palindrome!"; otherwise,
return "Not a palindrome!".
Try it with words like "level" and "hello".
2. Mystery Calculator:
Create a function mystery_calculation(a, b, c) that accepts
three numbers and returns
the result of the following formula:
((a + b) * c) / 2. Call the function with 5, 7, and 10.
3. Mathematical Functions
These functions perform mathematical operations like
absolute values, power calculations, and rounding numbers.
abs() - Absolute Value
Returns the absolute (positive) value of a number.
print(abs(-7)) # Output: 7
pow() - Power Function
Calculates the result of raising a number to a power.
print(pow(2, 3)) # Output: 8 (23)
round() - Rounding Numbers
Rounds a floating-point number to the specified decimal
places.
print(round(5.678, 2)) # Output: 5.68
5. Looping Functions
These functions help in iterating through data structures
efficiently.
range() - Generate Number Sequences
Creates a sequence of numbers that can be used in loops.
1
2
3
4
0 Alice
1 Bob
("Alice1, 25}
('Bob', 30)6
6. Identifying Data
These functions help inspect the type and identity of objects
in memory.
type() - Find Data Type
Returns the data type of a value.
print(type(42)) # Output: <class 'int'>
id() - Get Memory Address
Returns the unique ID of a variable in memory.
x = 10
print(id(x)) # Output: Unique memory address
P. 4]
def square(n):
return n * n
numbers = [1, 2, 3]
squares = list(map(square, numbers))
print(squares)
[1, 4, 9]
numbers = [3, 1, 4, 2]
print(sorted(numbers))
[1, 2, 3J 4]
Conclusion
Python's built-in functions make coding easier and more
efficient. These functions cover a wide range of tasks, from
handling numbers and sequences to evaluating code
dynamically. Mastering these functions will help you write
clean and effective Python programs.
More Resources:
• https://youtu.be/Ymgep512PPE
WEEKLY CODING
EXERCISES
Beginner-Level
1. Write a program to find the length of the string 'Hello
World!' using a built-in function.
2. Use the type() function to check the data type of the
variable my_var = 3.14.
3. Calculate the sum of all numbers in the list [5, 10, 15]
using a built-in function.
4. Use the min() function to find the smallest number in [8,
3, 12, 7].
5. Write a program that takes user input and prints it in
uppercase using a built-in function.
Intermediate-Level
1. Sort the list [10, 5, 8, 3] in ascending and descending
order using a built-in function.
2. Write a program that accepts a list of numbers and filters
out the odd numbers using the filter() function.
3. Use the zip() function to merge two lists: ['John', 'Jane']
and [80, 90].
4. Write a program that rounds a floating-point number
(e.g., 3.7654) to 2 decimal places using a built-in function.
5. Write a program that maps a function to square each
number in the list [2, 4, 6, 8].
Advanced-Level
1. Write a program to evaluate a mathematical expression
entered by the user using eval().
2. Create a program that combines two lists (e.g., names
and marks) into a dictionary using the zip() function.
3. Write a program that generates the Fibonacci sequence
up to 10 terms using range() and list().
4. Use the map() function to apply a function that capitalizes
each string in ['python', 'java', 'c++'].
5. Write a program to filter out words shorter than 4 letters
from the list ['cat', 'dog', 'elephant', 'tiger'] using filter().
WEEK 5: ERROR
HANDLING IN PYTHON
Error handling in Python allows you to manage runtime
errors (also known as exceptions) gracefully. If not handled,
these exceptions can cause the program to crash. By using
specific syntax and structures, such as try, except, else, and
finally, you can detect and handle errors, keeping your
program robust and user-friendly. In Python, the try block
encloses code that may raise an exception, except catches
and handles specific exceptions that occur, else executes if
no exception arises, and finally executes code regardless of
whether an exception was raised.
In Python, the try block encloses code that may raise an
exception, except catches and handles specific exceptions
that occur, else executes if no exception arises, and finally
executes code regardless of whether an exception was
raised.
TYPES OF ERRORS IN
PYTHON
• Syntax Errors: Occur when the parser detects an
incorrect statement. Example:
if True
print("Hello")
KeyError: ‘address’
ERROR HANDLING
METHOD
Basic Error Handling with try-except: Basic error
handling in Python uses a try block to wrap code that might
raise an exception, and an except block to catch and handle
those exceptions gracefully. This approach prevents the
program from crashing by allowing you to manage errors
and provide meaningful responses when unexpected issues
occur.
try:
# Code that might raise an error
except SomeSpecificError:
# HandLe that specific error
Example:
try:
numerator = 10
denominator = 0
result = numerator / denominator
print("Result, result)
except ZeroDivisionError:
print("Error: Cannot divide by zero!”)
try:
-file = open("test.txt", "r")
data = file.read()
result = int(data)
except FileNotFoundError:
print("Error: The file was not found."}
except ValueError:
print("Error: Could not convert data to an integer."}
try:
x = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero."}
else:
print("Division successful. Result:”, x}
More Resources:
https://www.youtube.com/watch?
v=ewrYPdOmhLk
WEEKLY CODING
EXERCISES
Beginner
1. Write a function divide_numbers(a, b) that returns the
result of a / b. Handle the case where b is zero by returning
"Cannot divide by zero".
2. Write a program that reads an integer input from the
user. Use a try-except block to handle Value Error if the user
enters invalid data (e.g., a string like "abc").
3. Write a small program that prompts the user for their age
(as an integer) and uses a try-except block to handle
ValueError in case the user inputs a non-integer (e.g.,
"twenty").
4. Create a function convert_to_int_list(str_list) that takes a
list of strings (e.g., ["1", "2", "abc", "4"]) and returns a new
list of integers. Use a try-except block inside a loop to
handle any ValueError when a string can’t be converted, and
print an error message without stopping the entire process.
5. Create a function access_list_item(my_list, index) that
attempts to return the element at index. Handle IndexError
by printing a message like "Index out of range" if the
requested index is invalid.
Intermediate
6. Write a function get_key_value(dictionary, key) that
returns the value of a given key from a dictionary. Use
KeyError handling to print a friendly message if the key does
not exist.
7. Create a function calculate_bmi(weight, height) that
raises a custom exception InvalidHeightError if height is 0 or
negative.
8. Use the raise keyword to force a TypeError if a function
add_numbers(a, b) is called with non-integer arguments.
WEEK 6:
INTRODUCTION TO
CLASSES
In Python, a class is a blueprint for creating objects. An
object is an instance of a class that contains both data
(called attributes) and functions (called methods) that
work with that data.
Think of a class like a recipe, and each object you create
from it is a dish made using that recipe. You can use the
same class to create multiple objects with different values.
Classes are a key part of object-oriented programming
(OOP) — a programming style that helps you write cleaner,
more reusable, and better-organized code.
Why Use Classes?
Defining a Class
A class is defined using the class keyword. Inside the class,
we use functions (called methods) to describe the behavior
of the objects created from the class.
One special method is __init__(). It’s a constructor that
runs automatically when a new object is created. It’s used to
initialize the object’s attributes (its data).
class Car:
def __init__(self, brand, model, year):
self.brand = brand # Attribute
self.model = model # Attribute
self.year = year # Attribute
def display_info(self):
print(f"Car: {self.brand} {self.model}, Year: {self.year}")
Instance Methods
Methods define the behavior of an object. Just like
functions, methods are blocks of code that do something
but they are tied to a specific object.
In Python, instance methods are defined inside a class and
take self as the first parameter. The self-keyword allows the
method to access the object’s attributes and other methods.
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print(f"{self.name} is barking!")
p = Person("Alice", 30)
print(p) # Output: Alice is 30 years old.
ENCAPSULATION,
INHERITANCE, AND
POLYMORPHISM
These are three core concepts of Object-Oriented
Programming (OOP) that help make your code more
reusable, organized, and scalable.
Encapsulation
Encapsulation means hiding the internal details of how
something works and only exposing what’s necessary. This
helps protect data and keep the code modular.
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute
def deposit(self, amount):
self.__balance += amount
print("Deposit successful.")
def get_balance(self):
return self.__balance
Inheritance
Inheritance allows one class to reuse the code of another
class. This helps reduce repetition and create relationships
between classes.
class Animal:
def speak(self):
print("Animal sound")
class Dog(Animal):
def speak(self):
print("Bark!")
my_dog = Dog()
my_dog.speak() # Output: Bark!
Polymorphism
Polymorphism means "many forms" different classes can
define the same method in different ways. This allows you
to write flexible code that works with objects of different
types.
class Cat:
def speak(self):
return "Meow"
class Dog:
def speak(self):
return "Bark"
File Modes
Mod
Description
e
r Read mode (default)
Write mode (creates a new file or overwrites existing
w
content)
a Append mode (adds content to an existing file)
x Exclusive mode (creates a new file, errors if it exists)
b Binary mode (use with rb, wb, etc.)
t Text mode (default mode)
Reading from a File
with open("example.txt", "r") as file:
content = file.read()
print(content)
The with statement ensures the file is properly closed after
reading.
Writing to a File
with open("example.txt", "w") as file:
file.write("Hello, Python!\n")
Using "w" mode will overwrite the existing content.
Appending to a File
with open("example.txt", "a") as file:
file.write("Appending new content.\n")
Conclusion
File handling is a key skill in Python that allows your
programs to store and manage data in the real world.
Whether you're reading from a configuration file, writing
logs, or processing user input, knowing how to work with
files gives your programs memory — they can save data
between runs.
You’ve now learned how to:
• https://youtu.be/Sd4Q Hi0mAU
• https://youtu.be/W320WncBVdg.
1. Write a Python script to create a file named data.txt and write "Hello,
Python!" into it.
2. Read and display the contents of data.txt.
3. Modify the script to append "Welcome to file handling." to data.txt.
4. Write a function that counts the number of lines in a text file.
5. Write a script that reads a file and prints only lines that contain the
word "Python".
Event Handling
Events in Tkinter are actions like button clicks, key presses,
etc. You can bind events to functions
using:
button.bind('<Button-1>', function_name)
Creating Menus
More Resources:
• https://youtu.be/d-UQpWya-E4
WEEKLY CODING
EXERCISES
1. Simple Login Form
Create a simple login form using Tkinter with two labels
(Username and Password), two entry widgets, and a button
(Login).
When the Login button is clicked, display a message box
saying “Login Successful” if the username is “user” and
the password is “pass”. Otherwise, display “Invalid
Credentials”.
2. Temperature Converter
Build a temperature converter that converts Celsius to
Fahrenheit and Fahrenheit to Celsius.
o Use Entry widgets to accept user input.
o Provide Buttons for conversion and Labels to display the
results.
o Use the formula:
■ Fahrenheit = (Celsius x 9/5) + 32
■ Celsius = (Fahrenheit - 32) x 5/9
3. Simple Calculator
Create a basic calculator that can perform addition,
subtraction, multiplication, and division.
o Use Entry widgets for displaying the input/output.
o Use Buttons for digits (0-9) and operators (+, -, *, /).
o Include a Clear button to reset the calculator.
4. To-Do List App
Build a simple To-Do List application with the following
functionalities:
o Entry widget to add new tasks.
o Button to add tasks to the list.
o Listbox to display tasks.
o Button to delete selected tasks from the list.
5. Quiz Application
Design a basic quiz application that asks 5 multiple-choice
questions.
o Use Labels for questions and Radiobuttons for options.
o Provide a Submit button that shows the score after
completing all questions.
o Display the score using a message box.
CONCLUSION
Congratulations on completing this 9-week journey into
Python programming! Over the past weeks, you've built a
solid foundation, explored essential concepts, and worked
on practical projects that mirror real-world applications.
Whether you're aiming to become a software developer,
data analyst, or automation expert, you now have the tools
to continue your learning journey with confidence.
But learning doesn’t stop here. The best way to truly master
Python is through practice. Keep experimenting with new
projects, participate in coding challenges, and explore
advanced topics like web development, machine learning, or
automation.
If you ever feel stuck, remember every great programmer
started as a beginner. Stay curious, keep building, and don’t
hesitate to join coding communities where you can learn
from others.
Stay Connected f
For more Python tutorials, coding tips, and project ideas,
check out my YouTube channel:
https://www.youtube.eom/@bethmediaagency
You can also find coding projects, sample scripts, and more
on my GitHub: https://github.com/Funmilayo24
Python is a powerful language that opens doors to countless
opportunities. Keep coding, keep improving, and most
importantly—enjoy the process!
Happy coding!