Lab Activity: Functions and Code Organisation
Objective
By the end of this lab, you will be able to:
-
Define and call functions.
-
Use different types of function arguments.
-
Return values from functions.
-
Understand local vs global variables.
-
Write and use lambda functions.
-
Organize code into modules.
-
Add documentation using docstrings and type hints.
step-by-step instructions:
Step 1: Defining and Calling Functions
Activity: Write your first function.
# Define a simple function
def greet():
print("Hello, welcome to Python functions!")
# Call the function
greet()
Expected Output:
Hello, welcome to Python functions!
Step 2: Function Arguments
Activity: Practice with positional, keyword, default, and variable-length arguments.
# Positional arguments
def add(a, b):
print("Sum is:", a + b)
add(3, 5) # Positional
# Keyword arguments
def introduce(name, age):
print(f"My name is {name} and I am {age} years old.")
introduce(age=20, name="Sara")
# Default arguments
def greet_user(name="Guest"):
print("Hello", name)
greet_user()
greet_user("Ali")
# Variable-length arguments (*args)
def multiply_all(*numbers):
result = 1
for n in numbers:
result *= n
print("Multiplication result:", result)
multiply_all(2, 3, 4)
Expected Output:
Sum is: 8
My name is Sara and I am 20 years old.
Hello Guest
Hello Ali
Multiplication result: 24
Step 3: Return Values
Activity: Functions that return a value.
def square(number):
return number * number
result = square(6)
print("Square is:", result)
Expected Output:
Square is: 36
Step 4: Variable Scope
Activity: Local vs Global variables.
x = 10 # Global variable
def show_number():
x = 5 # Local variable
print("Inside function:", x)
show_number()
print("Outside function:", x)
Expected Output:
Inside function: 5
Outside function: 10
Step 5: Lambda Functions
Activity: Write short anonymous functions.
# Normal function
def double(n):
return n * 2
# Lambda function
double_lambda = lambda n: n * 2
print(double(4))
print(double_lambda(4))
Expected Output:
8
8
Step 6: Organizing Code into Modules
Activity: Create your own module.
-
Create a file called mymath.py with this code:
def add(a, b): return a + b def subtract(a, b): return a - b -
Create another file main.py:
import mymath print("Addition:", mymath.add(10, 5)) print("Subtraction:", mymath.subtract(10, 5))
Expected Output:
Addition: 15
Subtraction: 5
Step 7: Docstrings and Type Hints
Activity: Document your function.
def greet_user(name: str) -> str:
"""
Function to greet a user.
Parameters:
name (str): The name of the user
Returns:
str: Greeting message
"""
return f"Hello, {name}!"
print(greet_user("Aisha"))
Expected Output:
Hello, Aisha!
Lab Tasks for Students
-
Write a function
is_even(number)that returnsTrueif the number is even, otherwiseFalse. -
Create a function that accepts any number of names (
*args) and prints them one by one. -
Write a module
greetings.pywith a functionsay_goodbye(name)and import it into another script.
