Python Functions Problems and Solutions: Building Reusable Logic

In the previous article we discussed the basics of functions, now let us go through some practice problems.

 

1. Write a function that returns the square of a number.

				
					def square(n):
    return n * n

result = square(5)
print("Square =", result)

# Square = 25

				
			

2. Write a function that checks whether a number is even.

				
					def is_even(num):
    if num % 2 == 0:
        return True
    else:
        return False
user_val = int(input("Enter a number: "))
print(is_even(user_val))

# Enter a number: 6
# True

				
			

3. Write a function using keyword arguments to display student details.

				
					def student(name, age, course):
    print("Name:", name)
    print("Age:", age)
    print("Course:", course)

student(age=20, name="Johnson", course="AI")

# Name: Johnson
# Age: 20
# Course: AI

				
			

4. Show that lists behave like Call by Reference.

				
					def modify_list(lst):
    lst.append(100)
    print("Inside function:", lst)

numbers = [1, 2, 3]
modify_list(numbers)
print("Outside function:", numbers)

# Inside function: [1, 2, 3, 100]
# Outside function: [1, 2, 3, 100]

				
			

In Python, lists are passed by reference, meaning the function works on the actual original list rather than a copy. Because .append() modifies the list in-place, any changes made inside the function persist even after the function finishes. Consequently, both the “inside” and “outside” print statements reflect the updated list containing 100.

5. Write a program to swap two numbers using a function.

				
					def swap(a, b):
    temp = a
    a = b
    b = temp
    print("Inside swap:", a, b)

x = 10
y = 20

swap(x, y)
print("Outside swap:", x, y)

# Inside swap: 20 10
# Outside swap: 10 20

				
			

6. Write a function to return sum and average.

				
					def calc(a, b):
    s = a + b
    avg = s / 2
    return s, avg

sum_val, avg_val = calc(10, 20)
print("Sum =", sum_val)
print("Average =", avg_val)

# Sum = 30
# Average = 15.0

				
			

7. Shopping Bill Calculator

Generate a Shopping Bill Calculator to calculate the bill based on the following conditions.

  • Calculate subtotal

  • Apply discount of 10% if amount > 2000

  • Add GST (18%)

  • Generate final bill

				
					def calculate_subtotal(prices):
    return sum(prices)

def apply_discount(amount):
    if amount > 2000:
        amount *= 0.9   # 10% discount
    return amount

def add_gst(amount):
    return amount * 1.18

# Function Calls
cart = [500, 1200, 700]
subtotal = calculate_subtotal(cart)
discounted = apply_discount(subtotal)
final_amount = add_gst(discounted)

print("Final Bill:", final_amount)

# Final Bill: 2548.7999999999997

				
			

8. Banking System (Deposit & Withdraw)

Write a Python program for a Banking Deposit to check

  • current balance
  • deposit amount
  • withdraw amount
				
					def deposit(balance, amount):
    balance += amount
    print("Deposited:", amount)
    return balance

def withdraw(balance, amount):
    if amount > balance:
        print("Insufficient Balance!")
    else:
        balance -= amount
        print("Withdrawn:", amount)
    return balance

def check_balance(balance):
    print("Current Balance:", balance)
balance = 1000

while True:
    print("\n1. Deposit  2. Withdraw  3. Check Balance  4. Exit")
    choice = input("Enter choice (1-4): ")
    if choice == '1':
        amt = float(input("Enter deposit amount: "))
        balance = deposit(balance, amt)
    elif choice == '2':
        amt = float(input("Enter withdrawal amount: "))
        balance = withdraw(balance, amt)
    elif choice == '3':
        check_balance(balance)
    elif choice == '4':
        print("Thank you for using our ATM!")
        break
    else:
        print("Invalid Choice!")
        
        
# 1. Deposit  2. Withdraw  3. Check Balance  4. Exit
# Enter choice (1-4): 3
# Current Balance: 1000

# 1. Deposit  2. Withdraw  3. Check Balance  4. Exit
# Enter choice (1-4): 1
# Enter deposit amount: 200
# Deposited: 200.0

# 1. Deposit  2. Withdraw  3. Check Balance  4. Exit
# Enter choice (1-4): 2
# Enter withdrawal amount: 650
# Withdrawn: 650.0

# 1. Deposit  2. Withdraw  3. Check Balance  4. Exit
# Enter choice (1-4): 3
# Current Balance: 550.0

				
			

9. Library Fine Calculator

Create a function to calculate the fine for the delay in resubmitting the books.

  • First 5 days → ₹2/day

  • Next 5 days → ₹5/day

  • After 10 days → ₹10/day

				
					def calculate_fine(days):
    fine = 0
    if days <= 5:
        fine = days * 2
    elif days <= 10:
        fine = (5 * 2) + (days - 5) * 5
    else:
        fine = (5 * 2) + (5 * 5) + (days - 10) * 10
    return fine

try:
    user_days = int(input("Enter the number of days the book is late: "))
    
    if user_days < 0:
        print("Days cannot be negative!")
    else:
        total_fine = calculate_fine(user_days)
        print(f"Library Fine for {user_days} days: ₹{total_fine}")

except ValueError:
    print("Invalid input! Please enter a whole number for days.")
    
# Enter the number of days the book is late: 8
# Library Fine for 8 days: ₹25