Control Structures and
functions
Weeks 1-2: Basics of Python
CS4LIBERIA
www.cs4lib.com
Course Overview
Topics covered in Weeks 3-4:
Conditional Statements (if, elif, else)
Loops (for, while)
Functions (defining and calling
functions)
Modules (importing and using built-
in/custom modules)
Learning objectives:
Control the flow of a program with
conditions and loops
Write reusable functions to simplify
code
Work with Python modules to
enhance functionality
Conditional Statements (if, elif,
else)
Used for decision-making in programs
Exercises:
Exercises:
1. Write a program that checks if a
number is positive, negative, or zero.
2. Create a program that asks for a user's
score and prints the grade (A, B, C, etc.).
3. Build a simple login system that asks for
a username and password.
4. Write a program that checks if a year is
a leap year.
Loops (for and while)
for loop: Used to iterate over sequences
(lists, strings, etc.)
while loop: Runs as long as a condition
is True
Exercises:
1. Write a for loop that prints numbers
from 1 to 10.
2. Create a while loop that asks for user
input until they type "exit".
3. Write a program that prints the
multiplication table of a number using a
loop.
4. Build a countdown timer that takes user
input and counts down to 0.
Functions in Python
Functions help organize code and make it reusable
Defining a function:
Calling a function:
Functions can return values:
Exercises:
1. Write a function that takes two
numbers and returns their sum.
2. Create a function that checks if a
number is even or odd.
3. Write a function that converts Celsius to
Fahrenheit.
4. Build a calculator function that takes
three arguments (two numbers and an
operator) and returns the result.
Modules in Python
Modules allow code reusability
Importing modules:
Creating a custom module (my_module.py):
Importing it:
Exercises:
1. Import and use the random module to
generate a random number.
2. Use the datetime module to print
today’s date.
3. Write a program that imports a custom
module with a function to find the
maximum of three numbers.
4. Create a module with functions for basic
math operations and import it into
another script.
Thank You
Questions?
Keep coding and
practicing!
Additional resources:
Python Documentation
W3Schools Python
Codecademy Python
Course
https://realpython.com/