Functions — Practice Questions
50 questions. Try each one yourself before checking the answer.
Write a function greet() that prints "Hello, World!", then call it.
Write a function greet_person(name) that prints "Hello, <name>!", then call it with your name.
Write a function add(a, b) that returns the sum of two numbers, then print the result of calling it.
Write a function is_even(n) that returns True if n is even, False otherwise.
Write a function rectangle_area(length, width) that returns the area of a rectangle, then call it with two values.
Write a function greet(name, greeting="Hello") that prints "<greeting>, <name>!". Call it once with only a name, and once with both arguments.
Write a function describe_pet(name, animal) that prints a sentence describing the pet. Call it once using keyword arguments in reversed order.
Create a global variable counter = 0 and a function that creates its OWN local variable also named counter, set to 100. Print counter before and after calling the function to show the global value is untouched.
Write a lambda that squares a number and assign it to square. Call it with 5.
Write a recursive function countdown(n) that prints numbers from n down to 1.
Write a function min_max(numbers) that returns BOTH the minimum and maximum of a list, using a single return with two values.
Write a function total(*args) that returns the sum of any number of arguments passed to it.
Write a function print_profile(**kwargs) that prints each keyword argument as key: value.
Write a function power(base, exponent=2) that returns base raised to exponent, defaulting to squaring. Call it both ways.
Write a function that modifies a global variable using the global keyword, and demonstrate the value change before and after.
Use sorted() with a lambda as the key to sort words = ["banana", "kiwi", "apple", "fig"] by length.
Write a recursive function factorial(n) that returns the factorial of n.
Write two small functions, celsius_to_fahrenheit(c) and fahrenheit_to_celsius(f), and use each to convert a value and print the result.
Write a function full_name(first, middle="", last="") that builds a full name, gracefully skipping an empty middle name.
Write a function log_call(*args, **kwargs) that prints all positional arguments and all keyword arguments it received, to show how both can be combined in one signature.
Write a function calculate_bmi(weight, height) that returns BMI, then use it to print a formatted report for a given weight and height.
Write a function is_prime(n) that returns True/False, then use it inside a loop to print all primes from 2 to 30.
Write a function apply_discount(price, percent=10) that returns the discounted price, then use it on a list of prices with a loop.
Write a function validate_password(password) that returns True only if the password is at least 8 characters and contains no spaces.
Write a recursive function sum_digits(n) that returns the sum of the digits of n.
Write a function count_vowels(text) that returns the number of vowels in a string, using a loop internally.
Split a "simple interest" calculation into two functions: calculate_interest(principal, rate, time) and calculate_total(principal, interest). Use both together and print the final total.
The following function is supposed to return the square of a number but always prints None when called. Find and fix the bug.
def square(n):
print(n ** 2)
result = square(4)
print(result)The following function has a mutable default argument bug — calling it multiple times accumulates unexpected values. Find and fix it.
def add_item(item, cart=[]):
cart.append(item)
return cart
print(add_item("apple"))
print(add_item("banana"))Given people = [("Alice", 30), ("Bob", 25), ("Carol", 35)], use sorted() with a lambda key to sort by age.
Write a recursive function fibonacci(n) that returns the nth Fibonacci number (0-indexed), then print the first 10 values using a loop.
Write a recursive function is_palindrome(text) that checks if a string is a palindrome by comparing its ends and recursing inward, without using slicing ([::-1]).
Write a function outer() containing a nested function inner() that reads a variable from outer's scope (a closure), and call inner() from inside outer().
Write a function make_counter() that returns a nested function which increments and returns a count each time it's called, using nonlocal.
Write a function flexible_greeting(greeting, *names, **details) that prints the greeting for each name, then prints any extra details passed as keyword arguments.
Write a function apply_operation(a, b, operation) that takes a function as its third argument and applies it to a and b. Call it once with a regular function and once with a lambda.
Write a recursive function gcd(a, b) implementing the Euclidean algorithm.
Write a recursive function power(base, exponent) that computes exponentiation without using **.
Explain (with a comment) and demonstrate what happens when a recursive function has no base case — write a SAFE version that shows the correct base case instead of actually triggering infinite recursion.
Write a function make_multiplier(factor) that returns a new function which multiplies its input by factor — a "function factory" pattern.
Build a small "Calculator Module" with functions add, subtract, multiply, and divide (with divide-by-zero protection), plus a calculate(operation, a, b) dispatcher function that calls the right one.
Build a "Text Analyzer Toolkit" with separate functions: word_count(text), char_count(text), and vowel_count(text), then print a combined report for one input sentence.
Build a "Grade Calculator". Write average(scores) and letter_grade(avg) functions, then combine them to print a student's final grade from a list of scores.
Build a "Number Utilities" module with is_prime(n), is_perfect_square(n), and is_armstrong(n), then run all three checks on a single user-provided number.
Build a "Contact Formatter" with functions format_phone(number) (adds dashes as XXX-XXX-XXXX) and format_name(first, last) (title-cased), then combine them into a single format_contact(first, last, phone) function.
Explain the difference between passing an immutable argument (like an int) versus a mutable one (like a list) into a function. Demonstrate that modifying a list parameter inside a function affects the caller's original list, while reassigning an int parameter does not.
Explain what a "pure function" is (same input always gives same output, no side effects) and demonstrate the difference with one pure and one impure version of a function that doubles a number and logs it.
Explain why recursion has a maximum depth in Python and demonstrate converting a recursive factorial into an equivalent iterative version, comparing both.
Demonstrate the difference between a lambda and a regular def function by rewriting a small def function as a lambda, then explain in a comment one thing a lambda CANNOT do that a def function can.
Build a "Function Toolkit Report" — the most complete demonstration in this module. Write: a function with default + keyword arguments, a function using *args, a function using **kwargs, a recursive function, and a lambda — then call all five and print a labeled summary of their results.
Still stuck on something?
Book a free 1-on-1 session and we'll work through it together.
Book a Free Session