Python Coding Day 13 | Functions, Loops, and Control Flow
Functions, Loops, and Control Flow
Watch the lesson tutorial 🔻
1. Python Functions: Building Reusable Code Blocks
A function is a self-contained block of organized, reusable code that performs a single, related action. Functions are defined using the def keyword and are essential for giving your code modularity and preventing repetition.
1.1 Defining and Calling a Function
The function definition starts with the
defkeyword.It is followed by the function name and parentheses
(), which may contain input parameters.The code block inside the function must be indented.
Example Code:
def greet_user(name):
"""This function greets the person passed in as a parameter."""
print(f"Hello, {name}!")
# Calling the function to execute the code inside it
greet_user("Alice")
greet_user("Bob")
Output:
Hello, Alice!
Hello, Bob!
1.2 The Importance of Indentation
Indentation (usually 4 spaces) defines the function's scope—which lines of code belong to the function.
Example A: Code within the function (Indented)
def print_greetings():
print("hello")
print("world") # Both lines are indented and belong to the function
# Calling the function
print_greetings()
Output:
hello
world
Example B: Code outside the function (Not Indented)
def print_hello():
print("hello") # Indented, part of the function
print("world") # NOT indented, executes immediately when read
# Calling the function
print_hello()
Output (The un-indented line runs first):
world
hello
1.3 Returning Values from Functions
The return keyword is used to send a value back from the function to the point where it was called. This allows functions to calculate results and pass them to other parts of the program.
Example Code (Returning a single value):
def add_numbers(a, b):
"""Calculates and returns the sum of two numbers."""
result = a + b
return result # Returns the value of 'result'
# Store the returned value in the variable 'sum1'
sum1 = add_numbers(10, 5)
print(f"The calculated sum is: {sum1}")
Output:
The calculated sum is: 15
Example Code (Returning multiple values):
def calculate_rectangle_stats(length, width):
area = length * width
perimeter = 2 * (length + width)
return area, perimeter # Returns a tuple (area, perimeter)
# Unpack the returned tuple
rect_area, rect_perimeter = calculate_rectangle_stats(8, 4)
print(f"Area: {rect_area}, Perimeter: {rect_perimeter}")
Output:
Area: 32, Perimeter: 24
2. Looping in Python: while and for
Loops allow a block of code to be executed repeatedly. Python provides two primary types of loops: while and for.
2.1 The while Loop (Condition-Based Repetition)
A while loop executes its body of code as long as a specified condition remains True. You must ensure that the condition eventually becomes False to avoid an infinite loop.
Example A: Infinite Loop (Condition never changes)
x = 6
while x > 0:
print("won")
# x is never changed, so x > 0 is always True
Output:
won
won
won
... (repeats indefinitely)
Example B: Practical Finite Loop (Counting down)
countdown_timer = 5
print("Starting countdown:")
while countdown_timer > 0:
print(countdown_timer)
# Crucial step: decrease the counter to eventually end the loop
countdown_timer = countdown_timer - 1
print("Lift off!")
Output:
Starting countdown:
5
4
3
2
1
Lift off!
2.2 The for Loop (Iteration Over Sequences)
A for loop is used to iterate over the items of any sequence (like a list or string) or other iterable objects.
Example A: Iterating Over a List
fruits = ["apple", "banana", "cherry", "date"]
print("Available fruits:")
# The variable 'fruit' takes the value of each item in 'fruits'
for fruit in fruits:
print(f"- {fruit}")
Output:
Available fruits:
- apple
- banana
- cherry
- date
Example B: Using range() for Fixed Repetitions
The range() function generates a sequence of numbers, perfect for running a loop a specific number of times.
# range(5) generates numbers 0, 1, 2, 3, 4
for i in range(5):
print(f"Loop count: {i}")
print("---")
# range(10, 13) generates numbers 10, 11, 12
for num in range(10, 13):
print(num)
Output:
Loop count: 0
Loop count: 1
Loop count: 2
Loop count: 3
Loop count: 4
---
10
11
12
- by Chirana Nimnaka

Comments
Post a Comment