0% found this document useful (0 votes)
29 views89 pages

Funmilayo T. Learn Python Programming in 9 Weeks. A Beginner's Guide... 2025

This document is a comprehensive guide designed to teach Python programming over a 9-week period, targeting beginners, career changers, and enthusiasts. It covers essential topics such as Python syntax, variables, data types, control flow, functions, and error handling, along with practical exercises and projects. The book emphasizes hands-on learning and provides resources for further assistance and practice.

Uploaded by

Young Mochi
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)
29 views89 pages

Funmilayo T. Learn Python Programming in 9 Weeks. A Beginner's Guide... 2025

This document is a comprehensive guide designed to teach Python programming over a 9-week period, targeting beginners, career changers, and enthusiasts. It covers essential topics such as Python syntax, variables, data types, control flow, functions, and error handling, along with practical exercises and projects. The book emphasizes hands-on learning and provides resources for further assistance and practice.

Uploaded by

Young Mochi
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
You are on page 1/ 89

LEARN PYTHON

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:

• Easy to Learn and Use: Python's syntax is


straightforward and similar to everyday English.
• Versatile: Python is used in many domains,
including web development, data science, artificial
intelligence, and more.
• Strong Community Support: There’s a vast
community of Python developers, so help is always
just a search away.

By learning Python, you're opening the door to countless


opportunities in tech and beyond.
WHO IS THIS BOOK
FOR?
This book is designed for:

1. Beginners: People with no prior programming


experience who want to learn Python from scratch.
2. Career Changers: Individuals looking to transition
into tech or data-driven roles.
3. Students and Enthusiasts: Learners who want to
deepen their understanding of programming.
4. Aspiring Developers: Those looking to build real-
world applications and develop problem-solving
skills.

No matter your background, this book is structured to guide


you step-by-step toward mastering Python in 9 weeks.
HOW TO USE THIS
BOOK
This book is designed to be hands-on and practical. Here’s
how to make the most of it:

1. Follow the Weekly Schedule: Each week focuses


on specific topics. Dedicate time each day to read,
practice, and complete exercises.
2. Complete the Challenges: Every week includes
practice problems and projects to reinforce what
you’ve learned.
3. Watch the videos: Refer to videos and additional
resources for quick revisions.
4. Ask Questions: If you’re stuck, don’t hesitate to
seek help from Python communities like Stack
Overflow or Reddit or reach out to me on any of my
social media accounts.
TOOLS YOU NEED
Before you dive in, ensure you have the following:

1. Python Installed: Download Python from the


official website. Instructions for installation are
covered in Get started with Python section.
2. An IDE or Code Editor: We recommend starting
with Visual Studio Code, PyCharm, or Jupyter
Notebook.
3. A Computer: Any computer with basic
specifications will do.
LEARNING TIPS
1. Start Small: Focus on understanding the basics
before tackling advanced topics.
2. Practice Daily: Consistent practice is key to
mastering Python.
3. Experiment: Try writing your own code based on
what you’ve learned.
4. Debugging is Learning: Mistakes are part of the
process. Debugging helps you learn and improve.
5. Stay Curious: Explore how Python is applied in the
real world to keep yourself motivated.
TABLE OF CONTENTS
Introduction
Who Is This Book For?
How to Use This Book
Tools You Need
Learning Tips
Getting Started with Python
Week 1: Understanding the Basics: Syntax, Variables, and
Data Types
Python Syntax
Variables in Python
Data Types in Python
Type Conversion (Casting)
Weekly Coding Exercises
Week 2: Control Flow (Conditionals & Loops)
Conditional Statements (Decision Making)
if Statement
if-else Statement
if-elif-else Statement
Logical Operators in Conditionals
Looping Statements in Programming.
For Loop
While Loop
Practice Question:
Week 3: Introduction to Functions
Basic Structure of a Function in Python
Why Use Functions?
Programming Questions (Beginner to Advanced)
Week 4: Python Built-In Functions
Common Built-In Functions
Practice Questions
Week 5: Error Handling in Python
Types of Errors in Python
Error Handling Method
Practice Questions
Week 6: Introduction to Classes
Attributes and Methods
Special Methods in Classes
Encapsulation, Inheritance, and Polymorphism
Practice Questions
Week 7: Project Week
Week 8: Working with Files in Python
Week 9: Graphical User Interface with Tkinter
Introduction to Tkinter
Tkinter Widgets
Tkinter Layout Management
Summary and Resources
Practice Questions (Tkinter GUI)
Conclusion
GETTING STARTED WITH
PYTHON
Introduction: Welcome to the World of Python!

Welcome to the beginning of your Python journey! If you’ve


ever wanted to learn how computers follow instructions and
make decisions, you’re in the right place. Python is a
beginner-friendly programming language that’s used in
everything from web development to data science and
automation. It’s like learning how to speak the language of
computers.
We’ll start by setting up Python on your computer and then
dive into the building blocks of Python programming. Think
of it as setting up your kitchen and learning how to chop
ingredients and mix them, everything you need to cook up
awesome programs later!

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.

In this section, we’ll break down the key components that


form the foundation of Python programming starting with
syntax.

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.

One of the most important aspects of Python’s syntax is


indentation (spaces at the beginning of a line). In many
other languages, indentation is optional and used just for
readability. But in Python, indentation is required—it tells
the interpreter what code belongs together.
Example:

print ("Nel cotie to Python!"}


print("Let's learn the basics."}

Welcome to Python!
Let's learn the basics.

Basic Syntax Rules

1. Indentation Matters

• Unlike languages like C or Java, where {} are


used to define code blocks, Python uses
indentation.
• The standard practice is 4 spaces per
indentation level.
• Not following indentation rules will cause an
IndentationError.

2. Case Sensitivity

• Python treats myVariable, MyVariable, and


MYVARIABLE as different variables.
• Be consistent in your naming.

3. Using Comments

• Comments are ignored by Python but help


explain your code.
• Single-line comments start with #, while multi­
line comments use """ or '''.
VARIABLES IN PYTHON
A variable is a name that stores a value. Python is
dynamically typed, meaning you don’t need to declare the
type of a variable explicitly.
Analogy: Imagine you have a coffee cup labeled "My
Favorite Coffee". The cup represents a variable, and the
coffee inside it represents the stored value. You can pour in
new coffee (reassign a new value), but the label stays the
same.

Declaring Variables in Python

1. You don’t need to specify the type of a variable.


2. Variables are dynamically typed, meaning Python
automatically assigns the type based on the value.

Variable Naming Rules

1. Can contain letters, numbers, and underscores (_).


2. Cannot start with a number.
3. Case-sensitive (name and Name are different
variables).

Examples: Declaring and Using Variables


name = "Alice" # String variabLe
age =25 # Integer variabLe
height =5.7 # FLoat variabLe
is_student = True # BooLean variabLe

print(name, age, height, is_student)

Alice 25 5.7 True


DATA TYPES IN PYTHON
Every piece of information in Python has a specific data
type. These data types tell Python what kind of value you’re
working with whether it's a number, a word, a list of items,
or something else entirely.

Understanding data types is crucial because it determines:

1. How Python stores the data in memory


2. What operations you can perform on that data
3. How data interacts with other variables and
functions

Python has several built-in data types. Here are some


common ones:
Data Type Example Description
int 10 Whole Numbers
float 3.14 Decimal Numbers
str “Hello” Text (string)
bool True/False Boolean Values
list [1, 2, 3] Ordered, mutable
collection
tuple (1, 2, 3) Ordered, immutable
collection
diet {“key”: Key-value pairs
“value”}
set {1, 2, 3} Unordered unique
values
Python needs to know what type of data it’s working with so
it can process your instructions correctly.
Think of data types like containers. Some hold numbers,
some hold text, and others hold collections of values. Each
# List (Mutablej Ordered Collection)
fruits = ["apple”, "banana", "cherry"]
type comes with its own set of rules.
print(type(fruits))

ExamplesofDifferentDataTypes:
: # Integer (Whole number)
age = 30|
print(type(age))

# FLoat (Decimal number)


price = 99.99
print(type{price))

# 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().

This is helpful when:

1. You get input from a user (which is always a string)


and want to convert it to a number
2. You want to display a number as part of a sentence
3. You need to do calculations with data that is stored
in a different format

Example: Converting Between Types


# Converting int to string
age = 25
age_str = str(age)
print("Age: " + age_str)

# Converting ftoat to int


pi = 3.14
pi_int = int(pi)
print(piint)

# Converting string to int


num_str — "5
*
3"
num_int = int(num_str)
print(num_int)

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.

Make it a habit to practice consistently. Try experimenting


with different data types, combine them in creative ways,
and don't be afraid to break things. Debugging is one of the
best ways to learn.

It's completely normal to make mistakes while learning.


What matters most is that you keep coding, keep exploring,
and stay curious. You’ve just taken your first step into the
world of Python, and there’s a lot more exciting stuff ahead.
WEEKLY CODING
EXERCISES
1. Calculating a Sum
□ Create two variables, a and b, assign any
integer values, and print their sum.
2. String Concatenation
□ Create two string variables, first_name and
last_name, then print their combined value
with a space in between.
3. Type Conversion Practice
o Prompt the user for a number (as a string),
convert it to int, and print the result of
squaring that number.
4. Boolean Check
o Assign a variable is_python_fun the value
True. Print a statement that says “It is
[value] that Python is fun!”
5. Mixed Data Types
□ Create one variable for each data type: int,
float, string, and boolean. Print them all in a
single formatted string (e.g., using an f-
string).
WEEK 2: CONTROL
FLOW (CONDITIONALS
& LOOPS)
Introduction
Control flow determines the direction in which a program
executes. Without control flow, a program would simply run
line by line from top to bottom, doing the same thing every
time with no variation.
But real programs often need to make decisions or repeat
tasks, like checking if a user is old enough to sign up, or
running a block of code multiple times to process a list.

Python provides powerful tools to manage control flow,


including:

1. Conditionals: if, if-else, and if-elif-else statements


let your program choose what to do based on
different conditions.
2. Loops: for and while loops let your program repeat
code efficiently.

By mastering conditionals and loops, you'll be able to write


programs that are smarter, more flexible, and interactive.
CONDITIONAL
STATEMENTS (DECISION
MAKING)
These statements execute code blocks based on specific
conditions.

• if: Executes a block if the condition is true.


• if-else: Executes one block if true, another if false.
• if-elif-else: Checks multiple conditions in sequence.
IF STATEMENT
The if statement allows you to execute a block of code only
whenaspecificconditionisTrue.

if condition:
# Code to execute if the condition is true

• if: Keyword to start the conditional statement.


• condition: An expression that evaluates to True or
False.
• Indentation: Code inside the if block must be
indented (typically 4 spaces).

Example:
age = 18
if age >= 18:
print("¥ou are eligible to vote.”)

You are eligible to vote.


IF-ELSE STATEMENT
Provides two possible paths: one if the condition is true, and
another if it's false.

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)

Key Points to Remember:

• Conditions are usually expressions that evaluate to


True or False.
• Use logical operators (and, or, not) to combine
multiple conditions.
• Indentation is crucial in Python for defining code
blocks under each statement.
• Conditional statements are essential for decision­
making in programs and are often combined with
loops for more complex logic.

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

Example 2: Using range() to generate a sequence of


numbers
The range() function is used to generate a sequence of
numbers, which is commonly used with loops.
Basic syntax:
range(start, stop, step)

1. start (optional): The number to start from (default is


0)
2. stop: The number to stop before
3. step (optional): How much to increase each time
(default is 1)

for i in range(l, 6): # Generates numbers 1 to 5


print(f"Number: {i}")

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

Example: Printing numbers until a condition is met

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

Key Points to Remember:


• Always ensure the loop condition will eventually
become false to avoid infinite loops.
• You can use break to exit a loop prematurely or
continue to skip to the next iteration.
• Loops can be nested (a loop inside another loop) for
more complex tasks.

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:

• Child: 0-12 years


• Teenager: 13-19 years
• Adult: 20-59 years
• Senior: 60+ years

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

Additionally, print a message if the score is invalid (less than


0 or greater than 100).
Hint:
Use nested conditional statements or combine logical
operators.
Expected Output Example:
For score = 85, the output should be:
Your grade is B.
For score = -5, the output should be:
Invalid score.

Question 4:
Write a Python program that simulates a simple guessing
game:

1. Use a while loop to ask the user to guess a number


between 1 and 20.
2. If the guess is correct, print “Congratulations! You
guessed it!” and exit the loop.
3. If the guess is too high or too low, provide feedback
and let them guess again.
4. The program should stop after 5 incorrect attempts
and print “Game Over.”

Hint:

Use a random number generator (random.randint())


to set the correct number.
Use a counter to track the number of attempts.
Question 5:
Create a Python program that calculates the sum of all even
numbers between 1 and 50 using a for loop.
Hint:

• Use the range() function with steps of 2 to iterate


over even numbers.
• Use a variable to accumulate the sum.

Expected Output Example:


For numbers from 1 to 50, the output should be:
The sum of even numbers from 1 to 50 is 650.
WEEK 3:
INTRODUCTION TO
FUNCTIONS
What is a Function?
A function in Python is like a reusable recipe or set of
instructions that tells the computer what to do. Instead of
writing the same code over and over again, you can put it
inside a function and "call" it whenever needed.

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.

Why Use Functions?


Functions help you:

1. Organize your code into smaller, manageable


chunks
2. Avoid repetition
3. Make your program easier to read, debug, and
update
4. Reuse code across different parts of your program
Syntax of a Function
Every function in Python has a basic structure. It includes a
definition, optional parameters, and sometimes a return
value.

Parts of a Function

1. Function Definition: This is where you define the


function using the def keyword.
2. Parameters: Inputs to the function (optional).
3. Return Statement: Outputs from the function
(optional).

# 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")

# Co LLing the function


inake_coffee()

Grinding coffee beans...


Boiling water...
Pouring coffee into the cup...
Your coffee is ready! o

How it Works:

1. def make_coffee(): ^ This defines the function.


2. Inside { } (Python uses indentation instead of {}),
we put the instructions.
3. make_coffee() ^ This calls the function, just like
pressing the coffee machine button.

Functions with Inputs (Parameters)


Now, let’s say your coffee machine lets you choose what
kind of coffee you want—Espresso, Cappuccino, Latte, etc.
When you press the button, you also select an option, and
the machine makes your coffee based on your choice.
In Python, this is like a function that takes an input and
gives different results based on what you provide.
Example in real life:

i If you order Espresso, you get a small, strong


coffee.
• If you order Latte, you get coffee with lots of milk.

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")

# CaLLing the function with different inputs


make_coffee("Espresso")
make_coffee("Latte")

Making a Espresso coffee...


Grinding coffee beans...
Boiling water...
Pouring coffee into the cup...
Your Espresso coffee is ready! Q
Making a Latte coffee...
Grinding coffee beans...
Boiling water...
Pouring coffee into the cup...
Your Latte coffee is ready! Q

How it Works:

• type_of_coffee is a parameter that allows us to


make different kinds of coffee.
• make_coffee("Latte") passes "Latte" as an input.

Functions that Return Values


Sometimes, you don’t just want to press a button and have
something happen—you want something to be given back
to you.
For example, imagine you use a calculator to add two
numbers. You enter 5 + 3, and the calculator shows 8 on
the screen.
Here, the calculator is like a function. It takes in your inputs
(5 and 3), does the work (addition), and then returns a
result (8).
Imagine asking a pizza shop how much a pizza costs. You
tell them the size and toppings, and they give you a price.

• Your request (size + toppings) ^ Function


processes it ^ Gives you the total cost

def add_numbers(a, b):


return a + b

def subtract_numbers(a, b):


return a - b

# Perform operations
sum_result = add_numbers(10, 5)
difference_result = subtract_numbers(10, 5)

print(f"The sum is {sum_result .")


print(f"The difference is {difference_result .")

The sum is 15.


The difference is 5.
WHY USE FUNCTIONS?
Functions make life easier! Here’s why:

1. Reusability - You don’t have to write the same code


again and again. Just call the function when
needed.
2. Organized Code - Instead of writing a long list of
instructions, you can group related steps inside a
function, making your code easier to understand.
3. Avoid Repetition - Imagine having to write the same
steps every time you make coffee or a pizza. That
would be frustrating! Functions help avoid this by
storing the instructions in one place.
More Resources:

• 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:

Define a basic function using def


• Pass information into functions using parameters
• Use the return statement to get results back from a
function
As you continue building more complex programs, functions
will allow you to break tasks into smaller parts, making your
code more flexible and easier to understand.
Keep practicing by creating your own functions with
different types of inputs and return values. The more you
use them, the more natural it will feel.
Functions are like building blocks and now you know how to
create your own.
WEEKLY CODING
EXERCISES
Beginner Level
1. The Greeting Machine:
Write a function greet(name) that takes a person's name as
input and prints a
personalized greeting:
"Hello, <name>! Welcome to the world of Python!".
Test the function by calling it with your name.

2. The Recipe Helper:


Create a function make_pancake(flour, eggs, milk) that
takes in the amount of flour,
eggs, and milk, and returns the total number of pancakes
you can make (based on the
formula: 1 cup flour, 1 egg, 1 cup milk makes 4 pancakes).
Call the function and print
the result.

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.

5. The Personalized Welcome:


Write a function personalized_welcome(name) that takes a
name and prints out:
"Welcome, <name>! You are doing amazing!". Try calling
the function with different
names.

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.

3. Superhero Power Check:


Write a function can_fly(power_level) that takes the power
level of a superhero as
input and returns "You can fly!" if the power level is greater
than 100, or "Try again,
keep training!" if the power level is 100 or less.

4. Shape Area Calculator:


Create a function calculate_area(shape, dimension1,
dimension2=0) that calculates the
area of a rectangle (length x width) or square (side x side).
The second dimension
should default to 0 for squares. Test your function with both
shapes.

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. Fibonacci Sequence Generator:


Write a function generate_fibonacci(n) that returns the first
n numbers of the
Fibonacci sequence. For example, for n = 5, the output
should be [0, 1, 1, 2, 3].

4. Word Frequency Counter:


Create a function count_word_frequency(text, word) that
takes a string and a word,
then counts how many times the word appears in the string.
Call it with the sentence
"Python is fun, Python is powerful" and the word "Python".
WEEK 4: PYTHON BUILT-
IN FUNCTIONS
Python provides a rich set of built-in functions that can
perform a wide range of tasks, all without needing to install
any extra libraries. These functions make your code more
efficient and help you get things done faster.
You can use built-in functions for:

• Type conversions (like changing a string to an


integer)
• Mathematical calculations
• Working with strings, lists, and other sequences
• Interacting with users through input and output
Below is a breakdown of some of the most commonly used
built-in functions in Python, along with examples to help you
understand how and when to use them.
COMMON BUILT-IN
FUNCTIONS
1. Input and Output Functions
These functions help interact with users by displaying
messages or accepting input.
print() - Display Output
The print() function is used to display messages or variables
on the screen.
input() - Get User Input
The input() function allows the user to enter a value, which
is always stored as a string.

2. Type Conversion Functions


These functions allow conversion of data between different
types, such as strings, numbers, and Boolean values.

• int(): Converts to an integer.


• float(): Converts to a floating-point number.
• str(): Converts to a string.
b bool(): Converts to a boolean (True or False).

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

4. Working with Sequences


These functions help manipulate sequences like strings,
lists, and tuples.
len() - Length of a Sequence
Counts the number of elements in a string, list, or tuple.
print(len("Python")) # Output: 6
min() and max() - Smallest and Largest Values
Finds the smallest and largest values in an iterable.
numbers = [5, 1, 8, 3]
print(min(numbers)) # Output: 1
print(max(numbers)) # Output: 8
sum() - Add All Elements
Calculates the total sum of elements in a list.
print(sum([1, 2, 3, 4])) # Output: 105

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.

for i in range(l, 5):


print(i)

1
2
3
4

enumerate() - Track Index in Loops


Adds an index to elements in a list.

names = ["Alice”, '"Bob”]


for index, name in enumerate(names)
print(index, name)

0 Alice
1 Bob

zip() - Combine Two Lists


Pairs elements from multiple lists.

names = ["Alice”, "Bob”]


age = [25, 30]
for pair in zip(names, age)
print(pair)

("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

7. Evaluating and Executing Code


These functions dynamically evaluate and execute Python
code.
eval() - Evaluate Expressions
Runs a string as a Python expression.
print(eval("5 + 10")) # Output: 15
exec() - Execute Python Code
Runs a block of Python code stored as a string.
code = "print('Hello, World!')"
exec(code) # Output: Hello, World!

8. Filtering and Transforming Data


These functions modify and filter data elements in lists or
other iterables.
filter() - Keep Matching Items
Filters elements based on a condition.
def is_even(n):
return n % 2 == B
numbers = [1, 2, 3, 4, 5]
evens = list(filter(is_even, numbers))
print(evens)

P. 4]

map() - Apply Function to Each Element


Applies a function to every item in a list.

def square(n):
return n * n

numbers = [1, 2, 3]
squares = list(map(square, numbers))
print(squares)

[1, 4, 9]

sorted() - Sort Elements


Returns a sorted list.

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")

Cell In[7]> line 1


if True

SyntaxError: expected ':’

• NameError: Raised when a local or global name is


not found (i.e., you’re referring to a variable that
does not exist)
def greet():
printf"HellOj " + username)
greet()

NameError Traceback (most recent call Iasi


Cell In[8], line 3
1 def greet():
2 print("HellOj " + username)
------ > 3 greet()

Cell In[8], line 2, in greet()


1 def greet{):
------ > 2 print("HellOj " + username)

NameError: name 'user_name*1 2is not defined

Since user_name was never declared or passed as a


parameter, trying to use it results in a NameError.

• TypeError: Occurs when an operation or function is


applied to an object of an inappropriate type.
value = 42
result = value + " is the answer

TypeError Traceback (most recent call last)


Cell In[9], line 2
1 value ■ 42
--- > 2 result - value + " is the answer."

TypeError: unsupported operand type(s) for +: ’int' and ‘str’

Python cannot concatenate an integer (42) with a string (" is


the answer.") directly, resulting in a TypeError. You’d have to
convert the integer to a string first (e.g., str(value)).

• KeyError: Raised when a dictionary key is not found


in the set of existing keys.
person = {"name”: “Alice", "age": 30}
print(person["address"])

KeyError Traceback (most recent call last)


Cell In[10], line 2
1 person = {"name”: "Alice”, "age": 30}
- — > 2 print(person["address"])

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!”)

Error: Cannot divide by zero!

Handling Multiple Exceptions: Handling multiple


exceptions in Python involves using multiple except blocks
to catch and manage different types of errors that might
occur within a single try block. This allows you to provide
specific responses or recovery actions for each distinct
exception, enhancing the robustness and clarity of your
error handling strategy.

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."}

Error: The file was not found.

else Clause: The else clause in Python's error handling is


executed only if the try block does not raise any exceptions.
It allows you to run code that should occur whenno errors
are encountered, keeping the normal execution flow
separate from the error handling logic.

try:
x = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero."}
else:
print("Division successful. Result:”, x}

Division successful. Result: 5.6

finally Clause: The finally clause in Python's error handling


is executed regardless of whether an exception was raised
or not in the preceding try block. It is typically used to
perform clean-up actions, such as closing files or releasing
resources, ensuring that certain code runs no matter what
happens in the try and except blocks.
try:
file = open("test.txt", "r")
content = file.read()
except FileNotFoundError:
printf'File not found.")
finally:
file.close{)

Raising Exceptions: Raising exceptions in Python is done


using the raise statement to intentionally trigger an error
when a specific condition occurs, allowing you to enforce
rules and handle unexpected situations gracefully. This
mechanism enables you to create custom error messages or
exception types, enhancing the robustness and readability
of your code.
def check_3ge(age):
if age ■< Q:
raise ValueError("Age cannot be negative!")
else:
print("Valid age:", agp)

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?

• Organize code in a structured manner.


• Reusability: Once a class is defined, you can create
multiple objects from it.
• Encapsulation: Group related data and functions
together.
• Makes large programs easier to manage.

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}")

1. self refers to the current object being created.


2. brand, model, and year are parameters passed in
when creating a new car.
3. display_info() is a method that prints out the car's
details.
Creating an Object (Instance of a Class)
Once a class is defined, you can create objects, also called
instances, based on that class. Each object has its own set
of data stored in its attributes.
my_car = Car("Toyota", "Camry", 2022)
my_car.display_info() # Output: Car: Toyota Camry, Year: 2022

• Car is the class we defined earlier.


• We pass in "Toyota", "Camry", and 2022 as
arguments.
• These values are sent to the_ init_ () method
and assigned to the object's attributes
(self.brand, self.model, self.year).
• The variable my_car now holds an object that
represents a specific car.
ATTRIBUTES AND
METHODS
Instance Attributes
Instance attributes are variables that belong to a
specific object (or instance) of a class. They store the
unique data for each object created from the class.
You define instance attributes inside the __init__() method
using self, which refers to the current object being created.
class Dog:
def __init__(self, name, breed):
self.name = name # Instance attribute
self.breed = breed # Instance attribute

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!")

Calling an Instance Method


my_dog = Dog("Buddy", "Labrador")
my_dog.bark() # Output: Buddy is barking!
SPECIAL METHODS IN
CLASSES
Python provides special methods (also called dunder
methods) to modify class behavior.
The __init__ Constructor
This method initializes an object's attributes when an
instance is created.
The __str__ Method
Used to define how an object should be represented as a
string.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} is {self.age} years old."

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

1. The __balance attribute is private (indicated by


double underscores).
2. The user can’t access it directly but can interact
with it using methods like deposit() and
get_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!

1. Dog inherits from Animal.


2. It overrides the speak() method to provide its own
version.

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"

animals = [Cat(), Dog()]

for animal in animals:


print(animal.speak()) # Output: Meow \n Bark

1. Both Cat and Dog have a speak() method.


2. The correct version is called depending on the
object type
More Resources:
• https://youtu.be/oJfIBVhSpHM
• https://youtu.be/CPL-h30Ei6k
Conclusion
Classes are the foundation of object-oriented programming
in Python. They allow you to create your own data types by
combining attributes (data) and methods (functions) into
one structured unit called an object.
By learning how to define classes, create objects, and use
features like encapsulation, inheritance, and
polymorphism, you can write code that is more organized,
reusable, and easier to manage especially as your programs
grow larger.
Understanding classes gives you the tools to model real-
world things in code and build more advanced applications,
such as games, user management systems, and more.
Keep experimenting by creating your own classes and
objects. Try combining what you've learned with loops,
conditionals, and functions to build small projects this is
where it really starts to come together.
You're now one step closer to thinking like a true Python
developer.
WEEKLY CODING
EXERCISES
Beginner Questions

• Define a class called Person with attributes name


and age. Create an instance and print the details.
• Create a class Rectangle with attributes length and
width and a method to calculate area.
• Define a class Student with name and marks.
Create multiple instances and display their details.
• Write a class Book with attributes title and author.
Add a method to display details.
• Create a Laptop class with attributes brand,
processor, and RAM. Write a method to print
specifications.
Intermediate Questions

• Create a BankAccount class with deposit and


withdrawal methods and a private balance
attribute.
• Write a Shape class with a method area(). Derive
Circle and Rectangle classes and override the
method.
• Define a Vehicle class. Inherit Car and Bike from it
and add specific attributes to each.
• Implement a ShoppingCart class with methods to
add and remove items.
• Create a class Employee with methods for salary
calculations based on experience level.
WEEK 7: PROJECT WEEK
Introduction
Welcome to week 7! The goal of this week is to provide you
with hands-on coding challenges that will reinforce the
fundamental concepts you’ve learned in Python.
Each project has been carefully designed to help you apply
key programming principles in a practical and engaging way.
Throughout your learning journey, you have explored data
types, loops, functions, exception handling, and
object-oriented programming. Now, it’s time to bring all
these concepts together by building real-world applications.
These projects will help you:

1. Improve your problem-solving skills by working


through real-world scenarios.
2. Gain practical experience in structuring and
organizing Python programs.
3. Understand how to use classes and functions
effectively.
4. Learn how to handle user input and errors
gracefully.
By the end of these projects, you’ll have a solid foundation
in Python programming and the confidence to build more
complex applications. Let’s get started!
1. Student Management System
Objective:
Create a system that helps manage student records by
adding, updating, and deleting student information.
Requirements:
1. Allow users to add new students (name, age, grade,
student ID).
2. Enable updating a student’s details.
3. Provide an option to delete a student record.
4. Display the list of all students.
5. Implement exception handling to prevent errors (e.g.,
invalid inputs).
How It Works:

1. The program runs a menu system where users


choose options like Add Student, Update Student,
Delete Student, or View All Students.
2. Students are stored as objects with attributes like
name, age, and grade.
3. Users can input a student’s ID to modify or remove
them from the system.
2. Library Catalog System
Objective:
Develop a digital library system that tracks available books
and manages borrowing and returning.
Requirements:

1. Users can add books to the catalog (title, author).


2. Allow users to borrow books, changing their status
to unavailable.
3. Enable users to return borrowed books.
4. Display all available books in the catalog.
5. Prevent borrowing of already borrowed books using
exception handling.
How It Works:
1. Books are stored as objects with attributes like title,
author, and availability status.
2. A user can borrow a book by entering its title. If
available, it gets marked as borrowed.
3. When a book is returned, its status changes back to
available.
3. Expense Tracker
Objective:
Build a program that helps users track their expenses by
categorizing and displaying them.
Requirements:

1. Users can add expenses (amount, category, date).


2. View total expenses by category.
3. Display monthly expense summaries.
4. Ensure proper exception handling for invalid
entries.
How It Works:

1. The program asks users to enter expenses under


categories like food, transport, rent, entertainment,
etc.
2. Users can later view total spending per category
and a breakdown of monthly expenses.
3. The system prevents negative values or invalid
data entries.
4. Inventory Management System
Objective:
Create a program to track inventory in a store by managing
stock levels.
Requirements:
1. Users can add new products (name, quantity,
price).
2. Users can update stock (increase or decrease
quantity).
3. Allow viewing of all products and their available
quantities.
4. Notify when a product is out of stock.
5. Implement exception handling for invalid operations
(e.g., removing more stock than available).
How It Works:

1. The program maintains a list of products with


details like name, quantity, and price.
2. Users can update stock levels whenever new
inventory arrives or when items are sold.
3. If an item is out of stock, the system prevents
further sales until it is restocked.
5. Mini Calculator App
Objective:
Develop a calculator that performs basic arithmetic
operations.
Requirements:

1. Support addition, subtraction, multiplication, and


division.
2. Users can enter two numbers and select an
operation.
3. Prevent division by zero using exception handling.
4. Allow users to perform multiple calculations until
they choose to exit.
How It Works:

1. The user is prompted to enter two numbers and


select an operation (+, -, *, /).
2. The program performs the calculation and displays
the result.
3. If the user enters an invalid input (e.g., dividing by
zero), an error message appears.
6. Hangman Game
Objective:
Create a word-guessing game where the player tries to
guess a hidden word letter by letter before running out of
attempts.
Requirements:

1. Select a random word from a predefined list.


2. Display the word as underscores (______ ) where
each underscore represents a letter.
3. Allow the player to guess one letter at a time.
4. If the letter is in the word, reveal its position(s).
5. If the letter is incorrect, decrease the number of
attempts.
6. The game ends when the player either:
o Guesses the word correctly
o Runs out of attempts X
How It Works:

1. The program selects a random word (e.g.,


"PYTHON" ^_____ ).
2. The player enters letters one by one.
3. If "O" is guessed, the display updates (_ _ _ O _ _).
4. If the player guesses wrong, they lose an attempt.
5. The game continues until they win or run out of
guesses.
Conclusion
As we move forward, we will take these projects to the next
level by exploring more
advanced features. In the coming lessons, we will learn how
to:

1. Create Graphical User Interfaces (GUI): We will


make our projects more interactive by designing
user-friendly interfaces using libraries like Tkinter
or PyQt.
2. Store and Retrieve Data: Instead of losing
information when the program closes, we will
implement file storage using CSV, JSON, or
databases to save and manage data efficiently.
By applying these concepts, we will transform our projects
into more dynamic and
real-world applications. Get ready to enhance your
Python skills even further
WEEK 8: WORKING
WITH FILES IN PYTHON
File handling is an essential skill in Python, allowing you to
read, write, and manipulate files efficiently. Python provides
built-in functions to work with files using the open()
function.

File handling is commonly used in real-world projects like:

• Saving user data or logs


• Reading configuration files
• Working with CSV, JSON, or text files in data
analysis
• Storing game scores or settings

Opening and Closing Files


In Python, you can open a file using:
file = open("example.txt", "r") # Opens file in read mode
file.close()
Always close a file after use to free up system resources.

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.

Reading Line by Line


with open("example.txt", "r") as file:
for line in file:
print(line.strip())

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")

Working with Binary Files


Binary files store data in raw format, such as images or
executable files.
with open("image.jpg", "rb") as file:
binary_data = file.read()

Writing Binary Data


with open("copy.jpg", "wb") as file:
file.write(binary_data)

Common Mistakes to Watch Out For

• Forgetting to close a file (unless using with open())


• Overwriting a file by using "w" instead of "a"
• Trying to read a file that doesn't exist
• Not handling file paths properly, especially on
Windows vs. Mac/Linux

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:

• Open and close files safely


• Read from and write to text files
• Append data without deleting existing content
• Work with binary files like images
• Use file modes to control how files are accessed

Always remember to use the with open() pattern to manage


files automatically and avoid resource issues. As you move
forward, you'll use these skills in projects like data
processing, automation scripts, and user-driven
applications.
Keep practicing by creating, reading, and modifying your
own files. The more you work with file I/O, the more natural
it will become.
More Resources:

• https://youtu.be/Sd4Q Hi0mAU
• https://youtu.be/W320WncBVdg.

Beginner Practice Questions

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".

Advanced Practice Questions


1. Write a program to read a large file line by line and count the
occurrences of each word.
2. Create a script that removes all blank lines from a file.
3. Write a program that reads a CSV file and converts it into a JSON file.
4. Implement a log system where errors are appended to an error log
file with timestamps.
5. Write a Python program to merge multiple text files into a single file.
WEEK 9: GRAPHICAL
USER INTERFACE WITH
TKINTER
A Graphical User Interface (GUI) is a visual way of
interacting with a computer program using components like
windows, buttons, text boxes, and images instead of text­
based commands. Most programs you've used calculators,
text editors, games have a GUI. Instead of typing
commands, users click buttons, enter text, and interact
visually. Learning how to build GUIs in Python opens up a
whole new world of possibilities for creating user-friendly
tools and applications.
Tkinter is Python's standard library for building GUI
applications.
Importance of GUIs:
GUIs make applications more user-friendly and accessible.
They allow users to interact with your program through
visuals instead of code, which is helpful in real-world tools
like forms, dashboards, or games.
INTRODUCTION TO
TKINTER
Tkinter is Python’s built-in library for building desktop
applications. It includes a variety of widgets (GUI
components like buttons and text fields) and layout tools
to create windows and user interfaces.

Setting Up Tkinter (Including Jupyter Notebook)


1. Import the tkinter module: Import the tkinter module,
which is necessary for creating the GUI components.
2. Create the main window (container): Initialize the
main application window using the Tk() class.
3. Set Window Properties: We can set properties like the
title and size of the window.
4. Add widgets to the main window: We can add any
number of widgets like buttons, labels, entry fields, etc., to
the main window to design the interface.
5. Pack Widgets: Use geometry managers like pack(),
grid() or place() to arrange the widgets within the window.
6. Apply event triggers to the widgets: We can attach
event triggers to the widgets to define how they respond to
user interactions.
TKINTER WIDGETS
- Labels: Display text or images.
- Buttons: Perform actions when clicked.
- Entry: Single-line text input.
- Text: Multi-line text input.
- Frames: Container to organize widgets.
- Checkbuttons: Toggle between True/False.
- Radiobuttons: Select one option from a group.
- Listbox: Display a list of options.
- Message Box: Display messages to the user.
- Canvas: For drawing shapes, graphs, etc.
- ComboBox: Drop-down menu.
TKINTER LAYOUT
MANAGEMENT
Tkinter provides three ways to organize widgets:
- pack(): Packs widgets vertically or horizontally.
- grid(): Places widgets in a table-like structure.
- place(): Positions widgets using x and y coordinates.

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)

Styling and Customization


You can customize widgets using options like 'bg', 'fg', 'font',
etc. Example:
label = tk.Label(root, text='Hello', bg='blue', fg='white',
font=('Arial', 12))

Creating Menus

Tkinter allows you to add menus to your applications.


Example:
menu = tk.Menu(root)
root.config(menu=menu)
file_menu = tk.Menu(menu)
menu.add_cascade(label='File', menu=file_menu)

Organizing Your Code


It's best to use classes when building complex applications
to make your code more manageable
and reusables

Deploying Your Application


Once your app is complete, you can turn it into an
executable file so others can use it — even if they don’t
have Python installed:
To turn your Tkinter application into an executable (.exe)
file, use pyinstaller:
pip install pyinstaller
pyinstaller --onefile your_app.py
SUMMARY AND
RESOURCES
Tkinter is a powerful library for building GUIs in Python. For
more resources, check out the official python
documentation.

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!

You might also like