Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Module 2: Control Flow and Functions

1. Subtopics:
a. Conditional Statements (if, else, elif)
b. Loops (for, while)
c. Functions (Defining and Calling)
2. Quizzes:
a. Coding challenges to write programs using if statements
for decision-making.
b. Exercises to create functions for repetitive tasks.

Module 2: Control Flow and Functions


This module delves into the world of control flow and functions,
essential building blocks for creating more complex and dynamic
Python programs.

2.a. Conditional Statements (if, else, elif)

Conditional statements allow your program to make decisions based


on certain conditions. Here are the fundamental ones:

 if statement: Executes a block of code if a specified


condition is True.

Python Code :

age = 18
if age >= 18:
print("You are eligible to vote.")

 else statement: Provides an alternative block of code if the


condition in the if statement is False.
Python Code :
age = 15
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote yet.")

 elif statement: Allows for checking multiple conditions


sequentially. You can chain multiple elif statements after an
if statement.

Python Code :
grade = 85
if grade >= 90:
print("Excellent! You earned an A.")
elif grade >= 80:
print("Great job! You earned a B.")
else:
print("Keep practicing! You earned a C or
below.")

2.b. Loops (for, while)

Loops allow you to execute a block of code repeatedly until a


certain condition is met. Here are the common looping constructs:

 for loop: Iterates over a sequence of items (like a list or


string) and executes the code block for each item.
Python Code :
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}.")

 while loop: Continues executing the code block as long as a


specified condition remains True.

Python Code :
count = 1
while count <= 5:
print(f"Current count: {count}")
count += 1 # Increment the counter

2.c. Functions (Defining and Calling)

Functions are reusable blocks of code that perform specific tasks.


You can define functions with a name, parameters (inputs), and a
code block that defines the function's behavior.

Python Code :
def greet(name):
"""This function greets a person by name."""
print(f"Hello, {name}!")
greet("Alice") # Calling the function with an
argument

By using functions, you can modularize your code, making it more


organized and easier to maintain.

You might also like