Functions: Practice Questions
100 questions. Try each one yourself before checking the answer.
Short on time? Filter by Must Do for the 25 questions that cover this topic on their own.
Define a function called greet() that prints Hello, World!, then call it.
Define a function welcome() that prints Welcome to Jr Codex!, then call it three times. This is the whole point of a function: write once, use many times.
Define a function banner() that prints these three lines, then call it twice:
==============
JR CODEX
==============
Define a function greet_person(name) that prints Hello, <name>!. Call it twice with two different names.
Define a function show_sum(a, b) that prints the sum of its two parameters. Call it with 4 and 7.
Define a function repeat_word(word, times) that prints word on its own line times times.
Define a function add(a, b) that returns the sum instead of printing it. Print the returned value.
Write double(n) that returns n * 2. Store the result in a variable called answer, then print it. Notice that a returned value can be saved, while a printed one cannot.
Write square(n) that returns n ** 2, then use the call directly inside an f-string so the output reads 7 squared is 49.
Write a function shout(text) that returns the text in uppercase with an exclamation mark added. Print the result of calling it with "good morning".
Write is_even(n) that returns True if n is even and False otherwise. Print the result for 4 and for 7.
Write a function print_sum(a, b) that only prints the sum, and store its result in a variable. Print that variable and explain in a comment why it shows None.
Write rectangle_area(length, width) that returns the area, and print the area of a 4 by 5 rectangle.
Write average_of_three(a, b, c) that returns the average of three numbers, printed to two decimal places.
Write celsius_to_fahrenheit(c) that returns the Fahrenheit value. Print the result for 37.
Write absolute_value(n) that returns n if it is zero or positive, and -n if it is negative — using two separate return statements.
Write area_of_square(side) with a one-line docstring describing what it does, then print area_of_square.__doc__.
Write greet(name, greeting="Hello") that prints <greeting>, <name>!. Call it once with only a name and once with both.
Write power(base, exponent=2) that returns base raised to exponent, defaulting to squaring. Call it both ways.
Write divider(char="-", width=30) that prints a divider line, with both parameters defaulted. Call it three ways: with nothing, with only a character, and with both.
Write describe_pet(name, animal) that prints <name> is a <animal>. Call it once using keyword arguments in reversed order to show that names beat position.
Write book_ticket(city, seats, meal) that prints a one-line summary. Call it once with everything positional, and once mixing positional and keyword arguments.
Write a function that creates a local variable message and prints it. Then, after the call, add a comment explaining why printing message outside the function would raise NameError.
Create a global variable app_name = "Jr Codex" and a function that reads it and prints a welcome line. Call the function.
Create a global counter = 0 and a function that creates its own local variable also called counter, set to 100. Print the global before and after the call to prove it was never touched.
Write add_points(points) that increases a global total_score using the global keyword. Print the score before and after two calls.
Write greet(name) that prints a greeting, and a second function greet_twice(name) that calls greet two times. Call only greet_twice.
Write star_line(count) that prints count stars on one line using a loop and end="".
Write sum_to_n(n) that returns 1 + 2 + ... + n using a loop and an accumulator.
Write factorial(n) using a loop (not recursion) that returns n!. Print the factorial of 6.
Write square_block(size, char="*") that prints a filled square of the given size using nested loops.
Write right_triangle(height) that prints a left-aligned star triangle of the given height, then call it with two different heights.
Write letter_grade(score) that returns "A", "B", "C", "D" or "F" using an if / elif chain. Print the grade for three different scores.
Write min_max(a, b, c) that returns both the smallest and the largest of three numbers in a single return. Unpack the two values on the calling line.
Write swap(a, b) that returns the two values in the opposite order, and use it to swap two variables in one line.
Write count_vowels(text) that returns how many vowels a string contains, ignoring case.
Write reverse_text(text) that returns the string reversed, and use it on two different words.
Write is_palindrome(text) that returns True if the text reads the same forwards and backwards, ignoring case and spaces.
Write bmi(weight, height) with a docstring that explains both parameters and the returned value across multiple lines. Show the docstring using help(bmi).
Write a recursive function countdown(n) that prints n down to 1 and then prints Liftoff!. A recursive function is simply one that calls itself.
Write a recursive factorial(n). Compare it mentally with the loop version from Q30.
Write a recursive sum_to_n(n) that returns 1 + 2 + ... + n, matching the loop version from Q29.
Write count_arguments(*args) that returns how many values were passed to it. Call it with zero, two and five arguments.
Write total(*args) that returns the sum of any number of arguments, adding them up with a loop and an accumulator.
Write largest(*args) that returns the biggest value passed in, or the text "nothing passed" if it was called with no arguments.
Write announce(title, *names) that prints the title with an underline, then one line per name. A required parameter can sit in front of *args.
Write print_profile(**kwargs) that prints every keyword argument it received as key: value, one per line.
Write settings_report(app, **kwargs) that prints the app name, how many settings were supplied, and then each setting aligned in a column.
Write log_call(action, *args, **kwargs) that prints the action, then each extra positional value, then each named value. Call it with a mix of both.
Write a lambda that squares a number, assign it to square, and call it with 5. Then write the same thing as a normal def and confirm both give the same answer.
Write a two-parameter lambda called area that returns length times width, and print the area of a 6 by 3 rectangle.
Write a lambda called bigger that returns the larger of two numbers, using a conditional expression (a if a > b else b).
Define shout(text) that returns uppercase text. Then assign the function itself (no parentheses) to a second name loud, and call loud. This shows a function is just a value.
Write apply_operation(a, b, operation) whose third parameter is a function. Call it once with a normal def function and once with a lambda.
Write repeat_apply(value, times, transform) that applies the transform function to value the given number of times and returns the result. Test it with a doubling lambda.
Write outer() containing a nested function inner() that reads a variable belonging to outer. Call inner() from inside outer().
Write make_multiplier(factor) that returns a new function which multiplies its input by factor. Use it to build a double and a triple.
Write make_counter() that returns a function which increases and returns a private count every time it is called. Use nonlocal.
Write two conversion functions, celsius_to_fahrenheit(c) and fahrenheit_to_celsius(f), then print a small two-way conversion table using a loop.
Split a simple-interest calculation into calculate_interest(principal, rate, time) and calculate_total(principal, interest). Use both together and print the final amount.
Write calculate_bmi(weight, height) and bmi_category(value), then combine them to print a full report for one person.
Write apply_discount(price, percent=10) that returns the discounted price. Print a table of discounted prices for 100, 200, 300, 400 and 500 using the default, then show one price at 25 percent.
Write validate_password(password) that returns True only if the password is at least 8 characters long, has no spaces, and contains at least one digit.
Write mask_card(number) that hides everything except the last four characters of a card number, so "9876543210123456" becomes "************3456".
Write initials(first, last) that returns the upper-case initials joined by dots, so ("john", "doe") gives "J.D.".
Write unit_charge(units) that returns the electricity bill using slabs — first 100 units at 3 per unit, next 100 at 5, anything beyond at 8 — and print the bill for three different readings.
Write tip_amount(bill, percent=10) and bill_total(bill, percent=10) where the second calls the first. Print the total for a 850 bill at the default rate and at 18 percent.
Write is_leap(year) returning True/False, then days_in_month(month, year) that uses is_leap to answer correctly for February.
Write a recursive fibonacci(n) that returns the nth Fibonacci number (0-indexed), then print the first ten values on one line.
Build a menu-driven calculator: write add, subtract, multiply and divide (guarding against division by zero), then a while loop that reads a choice and two numbers and calls the right function until the user chooses to quit.
This function is supposed to give back the square of a number, but the printed result is always None. Find and fix the bug.
def square(n):
print(n ** 2)
result = square(4)
print(result)check_number(-5) prints None instead of a description. Find the missing piece and fix it.
def check_number(n):
if n > 0:
return "positive"
elif n == 0:
return "zero"
print(check_number(7))
print(check_number(0))
print(check_number(-5))This raises UnboundLocalError: cannot access local variable 'balance' where it is not associated with a value. Explain why and fix it two different ways.
balance = 1000
def withdraw(amount):
balance = balance - amount
print(balance)
withdraw(200)This prints 10, not 99. Explain when a default value is actually calculated, and fix the function so it always uses the current limit.
limit = 10
def show_limit(value=limit):
print(value)
limit = 99
show_limit()A student writes book("Delhi", seats=2, "veg") and Python refuses to even start the program with SyntaxError: positional argument follows keyword argument. Explain the rule and show three call styles that are legal.
Use the same variable name label at three levels — module, enclosing function, and inner function — and print it at each level to show which one wins.
Explain what happens to a recursive function with no base case, and write a safe version that shows the correct base case instead of actually crashing.
Write a recursive sum_digits(n) that returns the sum of the digits of a positive whole number.
Write a recursive gcd(a, b) implementing the Euclidean algorithm, and use it to reduce the fraction 48/18 to its lowest terms.
Write a recursive power(base, exponent) that computes exponentiation without using the ** operator.
Write a recursive reverse_text(text) that reverses a string without using [::-1].
Write a recursive count_char(text, target) that returns how many times a character appears in a string, without any loop.
Write a recursive to_binary(n) that returns the binary representation of a whole number as a string, without using bin().
Solve the Tower of Hanoi. Write hanoi(n, source, target, helper) that prints every move needed to shift n disks, and count how many moves it took for 3 disks.
Write both a recursive and an iterative factorial, print the same value from each, and explain in a comment why the recursive one has a limit that the loop does not.
Build a Text Analyzer Toolkit. Write word_count(text), char_count(text) (letters only, no spaces), vowel_count(text) and longest_word(text), then print a combined report for one sentence the user types.
Build a Grade Calculator. Ask how many subjects, read that many scores in a loop, then use average(total, count), letter_grade(avg) and pass_or_fail(avg) to print a report card.
Build a Number Utilities toolkit with is_prime(n), is_perfect_square(n), is_armstrong(n) and digit_sum(n), then run all four checks on one number the user enters.
Build a Contact Formatter. Write format_phone(number) (as XXX-XXX-XXXX), format_name(first, last) (title cased), mask_email(email) (show only the first character before the @), and combine all three in format_contact(first, last, phone, email).
Build a Pattern Generator. Write pyramid(height, char="*"), inverted(height, char="*") and diamond(height, char="*") where diamond reuses pyramid. Show all three.
Build a Unit Converter Hub: one function per conversion (km_to_miles, kg_to_pounds, celsius_to_fahrenheit), plus a menu loop that keeps converting until the user quits.
Build a Password Strength Meter. Write one small check function for each rule (long_enough, has_upper, has_digit, has_symbol), a score(password) that counts how many passed, and a verdict(points) that turns the score into Weak / Medium / Strong.
Build a Bank Account Session. Keep the balance in a global, and write deposit(amount), withdraw(amount) and show_balance() that use global. Drive them from a menu loop that runs until the user exits.
Build a Quiz Runner. Write ask(question, correct) that returns 1 for a right answer and 0 otherwise, and report(score, total) that prints the score, the percentage and a comment. Run a three-question quiz.
Build a Shopping Bill. Keep reading an item name and price until the user types done, then use apply_discount(amount, percent=5) and add_tax(amount, percent=18) to print a receipt showing every line plus the final total.
Explain the difference between a parameter and an argument, and between positional, keyword and default arguments. Write one function that demonstrates all of them, and call it four different ways.
Explain what a pure function is, and demonstrate the difference by writing a pure and an impure version of the same "double a number" operation. Say which one is easier to test and why.
Rewrite a small def function as a lambda, then explain two things a lambda cannot do that a def can — and say when each one is the right choice.
Explain the three ways a function can end: no return at all, a bare return, and return <value>. Write one function of each kind and print what each hands back.
Capstone. Build a "Function Toolkit Report" that demonstrates everything in this topic at once: a function with default and keyword arguments, one using *args, one using **kwargs, a recursive function, a closure, and a lambda. Call all six and print a single labelled summary table.
Still stuck on something?
Book a free 1-on-1 session and we'll work through it together.
Book a Free Session