Chapter 6

Functions

FREE Functions β€” Reusable Code Blocks
Article Β· 15 min
πŸ“ Homework 13

Have you noticed yourself writing the same code over and over? Functions let you package code into reusable blocks. Once defined, you can use them anywhere!


πŸ”§ Defining Your First Function

Syntax:

def function_name():
    # code to run
    # when the function is called

Example:

def greet():
    print("Hello! Welcome to Python πŸŽ‰")

# Call the function
greet()  # Hello! Welcome to Python πŸŽ‰
greet()  # Hello! Welcome to Python πŸŽ‰

πŸ”‘ def keyword β†’ function name β†’ parentheses () β†’ colon : β†’ indented body.

1
Practice 1
✏️ Try it yourself!
1 Code
Write a function called say_hello that prints "Hi there!" three times.
2 Code
Write a function called show_menu that prints a menu with 3 options.

πŸ“₯ Functions with Parameters

Syntax:

def function_name(parameter1, parameter2):
    # use parameter1 and parameter2

Example:

def greet_person(name):
    print(f"Hello, {name}! πŸ‘‹")

greet_person("Alice")   # Hello, Alice! πŸ‘‹
greet_person("Bob")     # Hello, Bob! πŸ‘‹
2
Practice 2
✏️ Try it yourself!
1 Code
Write a function double(n) that prints twice the number passed to it.
2 Code
Write a function welcome(name, subject) that prints "Welcome, [name]! Let's learn [subject]."

πŸ“€ Returning Values

Syntax:

def function_name():
    return value

Examples:

def square(x):
    return x * x

result = square(5)
print(result)  # 25

def is_even(n):
    return n % 2 == 0

print(is_even(10))  # True
print(is_even(7))   # False
πŸ’‘ return vs print: return sends a value back to the caller. print displays something on screen. A function without return returns None.
3
Practice 3
✏️ Try it yourself!
1 Code
Write a function add(a, b) that returns the sum of two numbers.
2 Code
Write a function is_positive(n) that returns True if n is greater than 0.
3 Code
Write a function rectangle_area(length, width) that returns the area.

🎯 Default Parameters

def power(base, exponent=2):
    return base ** exponent

print(power(5))      # 25   (5Β²)
print(power(2, 10))  # 1024 (2¹⁰)
4
Practice 4
✏️ Try it yourself!
1 Code
Write a function multiply(a, b=1) that returns a Γ— b. If b is not given, return a.

πŸ“‹ Procedure vs Function

In IGCSE, a procedure does something but doesn't return a value. A function returns a value.

# PROCEDURE β€” no return
def display_menu():
    print("1. Add student")
    print("2. View scores")
    print("3. Quit")

# FUNCTION β€” has return
def get_average(scores):
    total = 0
    for s in scores:
        total += s
    return total / len(scores)

# Calling them
display_menu()
avg = get_average([70, 80, 90])
print(f"Average: {avg}")
5
Practice 5
✏️ Try it yourself!
1 Code
Write a procedure print_separator() that prints "---".
2 Code
Write a function celsius_to_fahrenheit(c) that returns the converted temperature.

🌍 Local vs Global Variables

score = 10   # GLOBAL
def update_score():
    score = 5   # LOCAL β€” different variable!
    print(f"Inside: {score}")  # 5

update_score()
print(f"Outside: {score}")    # 10 (unchanged!)
6
Practice 6
✏️ Try it yourself!
1 Code
What will this print? x = 10; def change(): x = 20; change(); print(x)

πŸ“š Library Routines: MOD, DIV, ROUND, RANDOM

# MOD (%) β€” remainder
print(17 % 5)   # 2

# DIV (//) β€” integer division
print(17 // 5)  # 3

# ROUND
print(round(3.7))       # 4
print(round(3.14159, 2))  # 3.14

# RANDOM
import random
print(random.randint(1, 10))   # random 1-10
print(random.random())         # random 0.0-1.0
7
Practice 7
✏️ Try it yourself!
1 Code
Check if 37 is even using MOD.
2 Code
Generate a random number between 1 and 6 (like a dice).
3 Code
Round 3.14159 to 2 decimal places.

πŸ“ Writing Maintainable Code

# ❌ BAD β€” what does this do?
def f(a, b):
    c = a
    for d in range(b - 1):
        c = c * a
    return c

# βœ… GOOD β€” meaningful names + docstring!
def calculate_power(base, exponent):
    """Return base raised to the power of exponent."""
    result = base
    for i in range(exponent - 1):
        result = result * base
    return result
8
Practice 8
✏️ Try it yourself!
1 Code
Rewrite this poorly-named function with meaningful names: def x(a,b): return a*b/2
2 Code
Add a docstring to your rectangle_area function.
FREE String Handling
Article Β· 15 min
πŸ“ Homework 12

In IGCSE Computer Science, you need to know four key string operations: length, substring, upper case, and lower case. Let's master them in Python!


πŸ“ Length β€” len()

Syntax:

len(string)

Example:

word = "Hello"
print(len(word))  # 5

sentence = "Hello World"
print(len(sentence))  # 11  (spaces count!)
1
Practice 1
✏️ Try it yourself!
1 Code
Find the length of your full name.
2 Code
Check if the word "Python" has more than 5 characters.

βœ‚οΈ Substring β€” Extracting Part of a String

Syntax β€” slicing:

string[start:end]     # from start to end-1
string[start:]        # from start to end
string[:end]          # from beginning to end-1

Examples:

text = "Python Programming"

print(text[0:6])   # Python  (chars 0 to 5)
print(text[7:])    # Programming  (from char 7)
print(text[-3:])   # ing  (last 3 chars)
print(text[:6])    # Python  (first 6 chars)
πŸ“ IGCSE Note: In Python, strings are 0-indexed (first char = [0]). In pseudocode, MID(str, start, length) is used. Know both!
2
Practice 2
✏️ Try it yourself!
1 Code
Extract the first 5 characters from "International".
2 Code
Extract the last 4 characters from "computerscience@gmail.com".
3 Code
Extract "Science" from "Computer Science".

πŸ”€ Upper and Lower Case

Syntax:

string.upper()    # convert to uppercase
string.lower()    # convert to lowercase

Examples:

msg = "Hello World"
print(msg.upper())   # HELLO WORLD
print(msg.lower())   # hello world

# Case-insensitive comparison
answer = input("Continue? (yes/no): ")
if answer.lower() == "yes":
    print("Let's go! πŸš€")
3
Practice 3
✏️ Try it yourself!
1 Code
Ask the user for a colour and check if it's "red" (ignore case).
2 Code
Convert "i love python" to uppercase and print it.

🎯 Exam-Style String Questions

# 1. Count vowels
word = "education"
vowels = 0
for ch in word:
    if ch.lower() in "aeiou":
        vowels += 1
print(f"Vowels: {vowels}")  # 5

# 2. Check file extension
filename = "report.pdf"
if filename[-4:] == ".pdf":
    print("It's a PDF!")

# 3. Extract first name
full_name = "Alice Smith"
space_pos = full_name.find(" ")
first_name = full_name[:space_pos]
print(f"First name: {first_name}")  # Alice

# 4. Reverse a string
word = "Python"
reversed_word = word[::-1]
print(reversed_word)  # nohtyP
4
Practice 4
✏️ Try it yourself!
1 Code
Count how many times the letter "e" appears in "International Baccalaureate".
2 Code
Extract the domain name from "user@example.com" (everything after @ and before .).
3 Code
Check if a word entered by the user is a palindrome (reads same forwards and backwards).
4 Code
Write a program that capitalises the first letter of each word in a sentence.