Python · Functions

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.

Q1Defining FunctionsEasyMust Do

Define a function called greet() that prints Hello, World!, then call it.

Q2Defining FunctionsEasy

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.

Q3Defining FunctionsEasy

Define a function banner() that prints these three lines, then call it twice:

==============
   JR CODEX
==============
Q4ParametersEasyMust Do

Define a function greet_person(name) that prints Hello, <name>!. Call it twice with two different names.

Q5ParametersEasy

Define a function show_sum(a, b) that prints the sum of its two parameters. Call it with 4 and 7.

Q6ParametersEasy

Define a function repeat_word(word, times) that prints word on its own line times times.

Q7ReturnEasyMust Do

Define a function add(a, b) that returns the sum instead of printing it. Print the returned value.

Q8ReturnEasy

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.

Q9ReturnEasy

Write square(n) that returns n ** 2, then use the call directly inside an f-string so the output reads 7 squared is 49.

Q10ReturnEasy

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".

Q11ReturnEasy

Write is_even(n) that returns True if n is even and False otherwise. Print the result for 4 and for 7.

Q12ReturnEasyMust Do

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.

Q13ParametersEasy

Write rectangle_area(length, width) that returns the area, and print the area of a 4 by 5 rectangle.

Q14ParametersEasy

Write average_of_three(a, b, c) that returns the average of three numbers, printed to two decimal places.

Q15ReturnEasy

Write celsius_to_fahrenheit(c) that returns the Fahrenheit value. Print the result for 37.

Q16ReturnEasy

Write absolute_value(n) that returns n if it is zero or positive, and -n if it is negative — using two separate return statements.

Q17DocstringsEasyMust Do

Write area_of_square(side) with a one-line docstring describing what it does, then print area_of_square.__doc__.

Q18Default ArgumentsEasyMust Do

Write greet(name, greeting="Hello") that prints <greeting>, <name>!. Call it once with only a name and once with both.

Q19Default ArgumentsEasy

Write power(base, exponent=2) that returns base raised to exponent, defaulting to squaring. Call it both ways.

Q20Default ArgumentsEasy

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.

Q21Keyword ArgumentsEasyMust Do

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.

Q22Keyword ArgumentsEasy

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.

Q23ScopeEasy

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.

Q24ScopeEasy

Create a global variable app_name = "Jr Codex" and a function that reads it and prints a welcome line. Call the function.

Q25ScopeEasyMust Do

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.

Q26ScopeMediumMust Do

Write add_points(points) that increases a global total_score using the global keyword. Print the score before and after two calls.

Q27Modular ProgrammingEasy

Write greet(name) that prints a greeting, and a second function greet_twice(name) that calls greet two times. Call only greet_twice.

Q28Defining FunctionsEasy

Write star_line(count) that prints count stars on one line using a loop and end="".

Q29ReturnMedium

Write sum_to_n(n) that returns 1 + 2 + ... + n using a loop and an accumulator.

Q30ReturnMedium

Write factorial(n) using a loop (not recursion) that returns n!. Print the factorial of 6.

Q31Modular ProgrammingMedium

Write square_block(size, char="*") that prints a filled square of the given size using nested loops.

Q32Modular ProgrammingMedium

Write right_triangle(height) that prints a left-aligned star triangle of the given height, then call it with two different heights.

Q33ReturnMedium

Write letter_grade(score) that returns "A", "B", "C", "D" or "F" using an if / elif chain. Print the grade for three different scores.

Q34ReturnMediumMust Do

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.

Q35ReturnMedium

Write swap(a, b) that returns the two values in the opposite order, and use it to swap two variables in one line.

Q36ParametersMedium

Write count_vowels(text) that returns how many vowels a string contains, ignoring case.

Q37ParametersMedium

Write reverse_text(text) that returns the string reversed, and use it on two different words.

Q38ReturnMedium

Write is_palindrome(text) that returns True if the text reads the same forwards and backwards, ignoring case and spaces.

Q39DocstringsMedium

Write bmi(weight, height) with a docstring that explains both parameters and the returned value across multiple lines. Show the docstring using help(bmi).

Q40RecursionMediumMust Do

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.

Q41RecursionMedium

Write a recursive factorial(n). Compare it mentally with the loop version from Q30.

Q42RecursionMedium

Write a recursive sum_to_n(n) that returns 1 + 2 + ... + n, matching the loop version from Q29.

Q43*argsMedium

Write count_arguments(*args) that returns how many values were passed to it. Call it with zero, two and five arguments.

Q44*argsMediumMust Do

Write total(*args) that returns the sum of any number of arguments, adding them up with a loop and an accumulator.

Q45*argsMedium

Write largest(*args) that returns the biggest value passed in, or the text "nothing passed" if it was called with no arguments.

Q46*argsMedium

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.

Q47**kwargsMediumMust Do

Write print_profile(**kwargs) that prints every keyword argument it received as key: value, one per line.

Q48**kwargsMedium

Write settings_report(app, **kwargs) that prints the app name, how many settings were supplied, and then each setting aligned in a column.

Q49*args & **kwargsMedium

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.

Q50LambdaMediumMust Do

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.

Q51LambdaMedium

Write a two-parameter lambda called area that returns length times width, and print the area of a 6 by 3 rectangle.

Q52LambdaMedium

Write a lambda called bigger that returns the larger of two numbers, using a conditional expression (a if a > b else b).

Q53Higher-Order FunctionsMedium

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.

Q54Higher-Order FunctionsMediumMust Do

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.

Q55Higher-Order FunctionsMedium

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.

Q56ClosuresMedium

Write outer() containing a nested function inner() that reads a variable belonging to outer. Call inner() from inside outer().

Q57ClosuresMediumMust Do

Write make_multiplier(factor) that returns a new function which multiplies its input by factor. Use it to build a double and a triple.

Q58ScopeMedium

Write make_counter() that returns a function which increases and returns a private count every time it is called. Use nonlocal.

Q59Modular ProgrammingMedium

Write two conversion functions, celsius_to_fahrenheit(c) and fahrenheit_to_celsius(f), then print a small two-way conversion table using a loop.

Q60Modular ProgrammingMedium

Split a simple-interest calculation into calculate_interest(principal, rate, time) and calculate_total(principal, interest). Use both together and print the final amount.

Q61Modular ProgrammingMediumMust Do

Write calculate_bmi(weight, height) and bmi_category(value), then combine them to print a full report for one person.

Q62Default ArgumentsMedium

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.

Q63ParametersMediumMust Do

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.

Q64ParametersMedium

Write mask_card(number) that hides everything except the last four characters of a card number, so "9876543210123456" becomes "************3456".

Q65ParametersMedium

Write initials(first, last) that returns the upper-case initials joined by dots, so ("john", "doe") gives "J.D.".

Q66Modular ProgrammingMedium

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.

Q67Default ArgumentsMedium

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.

Q68Modular ProgrammingMedium

Write is_leap(year) returning True/False, then days_in_month(month, year) that uses is_leap to answer correctly for February.

Q69RecursionMedium

Write a recursive fibonacci(n) that returns the nth Fibonacci number (0-indexed), then print the first ten values on one line.

Q70Modular ProgrammingMediumMust Do

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.

Q71DebuggingHard

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)
Q72DebuggingHard

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))
Q73DebuggingHardMust Do

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)
Q74DebuggingHard

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()
Q75Keyword ArgumentsHard

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.

Q76ScopeHard

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.

Q77RecursionHardMust Do

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.

Q78RecursionHard

Write a recursive sum_digits(n) that returns the sum of the digits of a positive whole number.

Q79RecursionHard

Write a recursive gcd(a, b) implementing the Euclidean algorithm, and use it to reduce the fraction 48/18 to its lowest terms.

Q80RecursionHard

Write a recursive power(base, exponent) that computes exponentiation without using the ** operator.

Q81RecursionHard

Write a recursive reverse_text(text) that reverses a string without using [::-1].

Q82RecursionHard

Write a recursive count_char(text, target) that returns how many times a character appears in a string, without any loop.

Q83RecursionHard

Write a recursive to_binary(n) that returns the binary representation of a whole number as a string, without using bin().

Q84RecursionHard

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.

Q85RecursionHardMust Do

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.

Q86Mini-ProjectMini-ProjectMust Do

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.

Q87Mini-ProjectMini-Project

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.

Q88Mini-ProjectMini-Project

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.

Q89Mini-ProjectMini-Project

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).

Q90Mini-ProjectMini-Project

Build a Pattern Generator. Write pyramid(height, char="*"), inverted(height, char="*") and diamond(height, char="*") where diamond reuses pyramid. Show all three.

Q91Mini-ProjectMini-Project

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.

Q92Mini-ProjectMini-Project

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.

Q93Mini-ProjectMini-ProjectMust Do

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.

Q94Mini-ProjectMini-Project

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.

Q95Mini-ProjectMini-Project

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.

Q96InterviewInterview

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.

Q97InterviewInterview

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.

Q98LambdaInterview

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.

Q99ReturnInterview

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.

Q100InterviewInterviewMust Do

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