Unit 3 · Functions
Function Practice Programs
Strengthen your understanding of Python functions with hands-on practice problems. Solve real-world challenges involving palindrome checking, prime detection, string reversal, list operations, calculators, and grade calculation—all using user-defined functions.
Introduction
You have now learned how to define functions, pass arguments, return values, use keyword and default arguments, understand variable scope, and write recursive functions. The best way to master these concepts is through practice.
This chapter brings together all the function concepts you have learned into practical, exam-ready programs. Each program includes a problem statement, complete solution code, output, and explanation.
Program 1 — Palindrome Checker Function
Problem: Write a function that checks if a given string is a palindrome (reads the same forward and backward).
def is_palindrome(text):
"""Check if a string is a palindrome."""
text = text.lower().replace(" ", "")
return text == text[::-1]
# Testing
words = ["Madam", "Racecar", "Hello", "Python", "Level"]
for word in words:
if is_palindrome(word):
print(f'"{word}" is a palindrome')
else:
print(f'"{word}" is NOT a palindrome')
Output: "Madam" is a palindrome "Racecar" is a palindrome "Hello" is NOT a palindrome "Python" is NOT a palindrome "Level" is a palindrome
Program 2 — Prime Number Checker
Problem: Write a function that determines whether a given number is prime.
def is_prime(n):
"""Check if a number is prime."""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
# Testing
numbers = [1, 2, 3, 4, 17, 20, 29, 100]
for num in numbers:
status = "Prime" if is_prime(num) else "Not Prime"
print(f"{num} is {status}")
Output: 1 is Not Prime 2 is Prime 3 is Prime 4 is Not Prime 17 is Prime 20 is Not Prime 29 is Prime 100 is Not Prime
Program 3 — String Reversal Function
Problem: Write a function that reverses a string and also counts its length.
def reverse_and_count(text):
"""Return reversed string and its length."""
reversed_text = text[::-1]
length = len(text)
return reversed_text, length
# Testing
original = "Python Programming"
reversed_str, count = reverse_and_count(original)
print(f"Original: {original}")
print(f"Reversed: {reversed_str}")
print(f"Length: {count}")
Output: Original: Python Programming Reversed: gnimmargorP nohtyP Length: 18
Program 4 — Calculator Using Functions
Problem: Create a calculator that uses separate functions for each operation.
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
return "Error: Division by zero"
return a / b
def calculator(a, b, operation):
"""Perform the given operation on a and b."""
if operation == "+":
return add(a, b)
elif operation == "-":
return subtract(a, b)
elif operation == "*":
return multiply(a, b)
elif operation == "/":
return divide(a, b)
else:
return "Invalid operation"
# Testing
print("10 + 5 =", calculator(10, 5, "+"))
print("10 - 5 =", calculator(10, 5, "-"))
print("10 * 5 =", calculator(10, 5, "*"))
print("10 / 5 =", calculator(10, 5, "/"))
print("10 / 0 =", calculator(10, 0, "/"))
print("10 % 5 =", calculator(10, 5, "%"))
Output: 10 + 5 = 15 10 - 5 = 5 10 * 5 = 50 10 / 5 = 2.0 10 / 0 = Error: Division by zero 10 % 5 = Invalid operation
Program 5 — Student Grade Calculator
Problem: Write functions to calculate the average marks of a student and determine the grade based on university grading criteria.
def calculate_average(marks):
"""Calculate average of a list of marks."""
return sum(marks) / len(marks)
def determine_grade(average):
"""Return grade based on average marks."""
if average >= 90:
return "A+"
elif average >= 80:
return "A"
elif average >= 70:
return "B"
elif average >= 60:
return "C"
elif average >= 50:
return "D"
else:
return "F"
def display_report(name, marks):
"""Display the complete student report."""
avg = calculate_average(marks)
grade = determine_grade(avg)
print(f"Student: {name}")
print(f"Marks: {marks}")
print(f"Average: {avg:.2f}")
print(f"Grade: {grade}")
print("-" * 30)
# Testing
display_report("Alice", [92, 88, 95, 90, 85])
display_report("Bob", [75, 68, 72, 80, 70])
display_report("Charlie", [45, 50, 42, 55, 48])
Output: Student: Alice Marks: [92, 88, 95, 90, 85] Average: 90.00 Grade: A+ ------------------------------ Student: Bob Marks: [75, 68, 72, 80, 70] Average: 73.00 Grade: B ------------------------------ Student: Charlie Marks: [45, 50, 42, 55, 48] Average: 48.00 Grade: F ------------------------------
Program 6 — List Operations Using Functions
Problem: Write functions to find the largest, smallest, and average of a list of numbers.
def find_largest(lst):
"""Return the largest element."""
largest = lst[0]
for num in lst:
if num > largest:
largest = num
return largest
def find_smallest(lst):
"""Return the smallest element."""
smallest = lst[0]
for num in lst:
if num < smallest:
smallest = num
return smallest
def find_average(lst):
"""Return the average."""
return sum(lst) / len(lst)
def list_stats(lst):
"""Display statistics of the list."""
print(f"List: {lst}")
print(f"Largest: {find_largest(lst)}")
print(f"Smallest: {find_smallest(lst)}")
print(f"Average: {find_average(lst):.2f}")
print(f"Count: {len(lst)}")
print()
# Testing
list_stats([34, 12, 56, 78, 23, 90])
list_stats([5, 5, 5, 5])
list_stats([100, 200, 50, 300])
Output: List: [34, 12, 56, 78, 23, 90] Largest: 90 Smallest: 12 Average: 48.83 Count: 6 List: [5, 5, 5, 5] Largest: 5 Smallest: 5 Average: 5.00 Count: 4 List: [100, 200, 50, 300] Largest: 300 Smallest: 50 Average: 162.50 Count: 4
Program 7 — Count Vowels and Consonants
Problem: Write a function that counts the number of vowels and consonants in a given string.
def count_vowels_consonants(text):
"""Count vowels and consonants in a string."""
vowels = 0
consonants = 0
for char in text.lower():
if char in "aeiou":
vowels += 1
elif char.isalpha():
consonants += 1
return vowels, consonants
# Testing
strings = ["Hello World", "Python Programming", "AEIOU", "bcdfg"]
for s in strings:
v, c = count_vowels_consonants(s)
print(f'"{s}" → Vowels: {v}, Consonants: {c}')
Output: "Hello World" → Vowels: 3, Consonants: 7 "Python Programming" → Vowels: 4, Consonants: 12 "AEIOU" → Vowels: 5, Consonants: 0 "bcdfg" → Vowels: 0, Consonants: 5
Program 8 — Fibonacci Series Using Function
Problem: Generate the first n Fibonacci numbers using a function.
def fibonacci_series(n):
"""Generate first n Fibonacci numbers."""
series = []
a, b = 0, 1
for _ in range(n):
series.append(a)
a, b = b, a + b
return series
# Testing
for count in [5, 8, 10, 15]:
result = fibonacci_series(count)
print(f"First {count} Fibonacci: {result}")
Output: First 5 Fibonacci: [0, 1, 1, 2, 3] First 8 Fibonacci: [0, 1, 1, 2, 3, 5, 8, 13] First 10 Fibonacci: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] First 15 Fibonacci: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
Key Takeaways
Functions make code modular, reusable, and readable.
Each function should perform one specific task.
Return values allow functions to produce results for further use.
Default arguments make function calls flexible.
Complex problems become simpler when broken into functions.
Practice is the best way to master functions.
University Exam Tip
University exams often ask you to write a function for a specific task (like palindrome check, prime check, or grade calculation). Always include a docstring, handle edge cases, and write clean, well-indented code. Practice these programs so you can write them quickly and correctly during the exam.
Extra Practice Questions
Q1. Write a function to check if a number is an Armstrong number.
def is_armstrong(n):
digits = str(n)
power = len(digits)
total = sum(int(d) ** power for d in digits)
return total == n
print(is_armstrong(153)) # True (1³ + 5³ + 3³ = 153)
print(is_armstrong(370)) # True
print(is_armstrong(123)) # False
Q2. Write a function that accepts a list and returns a new list with only even numbers.
def filter_even(numbers):
return [n for n in numbers if n % 2 == 0]
print(filter_even([1, 2, 3, 4, 5, 6]))
# [2, 4, 6]
Q3. Write a function to convert Celsius to Fahrenheit and vice versa.
def celsius_to_fahrenheit(c):
return (c * 9/5) + 32
def fahrenheit_to_celsius(f):
return (f - 32) * 5/9
print(celsius_to_fahrenheit(100)) # 212.0
print(fahrenheit_to_celsius(212)) # 100.0
Q4. Write a function to count the frequency of each character in a string.
def char_frequency(text):
freq = {}
for char in text:
freq[char] = freq.get(char, 0) + 1
return freq
result = char_frequency("hello")
for char, count in result.items():
print(f"'{char}' : {count}")
Q5. Write a function to check if two strings are anagrams of each other.
def is_anagram(s1, s2):
return sorted(s1.lower()) == sorted(s2.lower())
print(is_anagram("listen", "silent")) # True
print(is_anagram("hello", "world")) # False
print(is_anagram("Dormitory", "Dirty room")) # True
Summary
- Functions are the building blocks of well-organized Python code.
- Palindrome, prime, and string reversal are common function-based problems.
- Calculator and grade calculator demonstrate combining multiple functions.
- Returning multiple values using tuples is useful for list statistics.
- Practice writing clean, well-documented functions for exam success.