26. Python Functions

In programming, a function is a reusable block of code designed to perform a specific task.
Instead of writing the same code multiple times throughout a program, you can write it once inside a function and execute it whenever needed.
Using functions helps make your code organized, easier to read, and simpler to debug.
# Defining a simple function
def greet():
    print("Hello, welcome to Python!")

# Calling (executing) the function
greet()

26.1. Defining and Calling Functions

To create and use a function in Python, you follow two main steps:

  • Defining a Function: Use the def keyword, followed by the function name, parentheses (), and a colon :.

  • Function Body: The block of code inside the function must be indented (usually 4 spaces).

  • Calling a Function: To run the function’s code, write its name followed by parentheses ().

  • Code Execution: Defining a function does not execute its code immediately; it only runs when the function is explicitly called.

# Function definition
def show_menu():
    print("--- Main Menu ---")
    print("1. Start Game")
    print("2. Exit")

# Function call
show_menu()

26.1.1. Quiz: Defining and Calling Functions

26.1.1.1. Fill-in-the-Blanks (Cloze)

Complete the following sentences by filling in the blanks.
Word Bank (Drag items below):
called
colon
def
indented
parentheses

1. Python functions are defined using the Drop here keyword.
2. To execute a function, you write its name followed by Drop here.
3. The code statements belonging inside a function body must be Drop here.
4. Defining a function creates the code, but it will not run until the function is Drop here.
5. A function name must be followed by parentheses and a Drop here at the end of the header line.

26.1.1.2. Code Ordering Examples

Example 1: Define and call a basic function that prints a greeting.

Drag and drop lines into the correct order and click to adjust indentation:
☰
 
☰
def say_hello():
☰
say_hello()
☰
print("Hello, World!")

Example 2: Define a function that displays a cheer, then call it twice.

Drag and drop lines into the correct order and click to adjust indentation:
☰
cheer()
☰
cheer()
☰
print("Go Team!")
☰
def cheer():
☰
 

Example 3: Define a function that prints a line separator and call it.

Drag and drop lines into the correct order and click to adjust indentation:
☰
print("--------------------")
☰
draw_line()
☰
 
☰
def draw_line():

26.1.1.3. Multiple Choice Questions

Progress: 0
Score: 0 / 0
Question 1 of 0

Which keyword is used to define a function in Python?

Correct! The def keyword tells Python you are defining a new custom function.

Incorrect. function is used in other languages like JavaScript, but not Python.

Incorrect. create is not a valid Python keyword for functions.

Incorrect. Python uses the abbreviated keyword def.

What happens when you define a function without calling it?

Correct! Function bodies only run when explicitly called.

Incorrect. Defining only registers the function for later use.

Incorrect. Defining a function without calling it is completely valid.

Incorrect. The function stays in memory ready to be called.

How do you correctly call a function named display_score?

Correct! Calling a function requires its name followed by parentheses.

Incorrect. Python does not use the keyword call.

Incorrect. Including def defines a function rather than calling it.

Incorrect. Missing parentheses references the function object without executing it.

What must be placed at the end of a function definition header line (e.g. def my_func())?

Correct! Block headers in Python must end with a colon.

Incorrect. Python does not require semicolons at line endings.

Incorrect. Periods are used for attribute access, not block headers.

Incorrect. Equals signs are used for variable assignment.

Why are functions useful in computer programming?

Correct! Functions modularize code for clarity and maintainability.

Incorrect. Functions organize code structure rather than increasing raw hardware speed.

Incorrect. Casting functions perform type conversions.

Incorrect. Input validation logic handles user input checks.

How many times can a defined function be called in a program?

Correct! Functions can be invoked repeatedly across a script.

Incorrect. Functions are designed to be reused multiple times.

Incorrect. There is no arbitrary low limit on function calls.

Incorrect. Functions can be called from anywhere in your code.

What error occurs if you attempt to call a function before defining it?

Correct! Python executes sequentially, so calling an undefined function raises a NameError.

Incorrect. TypeErrors occur with mismatched data types.

Incorrect. IndentationErrors relate to improper code alignment.

Incorrect. ValueErrors occur when functions receive invalid argument values.

How does Python identify which statements belong inside a function body?

Correct! Python uses indentation levels to group code blocks.

Incorrect. Languages like C++ and Java use curly braces, but Python uses indentation.

Incorrect. Languages like Ruby use end statements; Python relies on indentation.

Incorrect. Square brackets define list literals and indexing.

Which of the following is a valid function name in Python?

Correct! Function names follow variable naming rules (lowercase with underscores).

Incorrect. Function names cannot start with a digit.

Incorrect. Hyphens are interpreted as subtraction operators.

Incorrect. Reserved keywords cannot be used as function names.

Given def test(): print("A"); print("B"), what happens when test() is called?

Correct! Calling a function executes all statements inside its body sequentially.

Incorrect. All statements in the function body execute.

Incorrect. Execution starts at the top of the function body.

Incorrect. Calling the function triggers execution.

Question 1 of 0

26.2. Function Parameters and Arguments

Functions can accept input values to perform dynamic operations:

  • Parameters: Variables listed inside the parentheses of a function’s definition header.

  • Arguments: The actual values passed into the function when it is called.

  • Multiple Inputs: Functions can take multiple parameters separated by commas.

  • Positional Matching: Arguments are assigned to parameters based on their order in the function call.

# Function with one parameter
def greet_user(name):
    print("Hello, " + name + "!")

greet_user("Alex")  # Argument "Alex" passed to parameter name

# Function with multiple parameters
def add_numbers(a, b):
    print("Sum:", a + b)

add_numbers(5, 10)  # Output: Sum: 15

26.2.1. Quiz: Parameters and Arguments

26.2.1.1. Fill-in-the-Blanks (Cloze)

Complete the following sentences by filling in the blanks.
Word Bank (Drag items below):
2
arguments
commas
parameters
positional

1. Variables defined in a function header to receive input values are called Drop here.
2. The actual values passed to a function during a call are known as Drop here.
3. Multiple parameters in a function definition must be separated by Drop here.
4. Arguments are matched to parameters based on their Drop here order.
5. If a function expects two parameters, you must provide Drop here arguments when calling it.

26.2.1.2. Code Ordering Examples

Example 1: Define a function that accepts a person’s name and prints a personalized welcome.

Drag and drop lines into the correct order and click to adjust indentation:
☰
def welcome(person_name):
☰
welcome("Sam")
☰
 
☰
print("Welcome,", person_name)

Example 2: Define a function that calculates and displays the area of a rectangle.

Drag and drop lines into the correct order and click to adjust indentation:
☰
def calculate_area(width, height):
☰
 
☰
area = width * height
☰
print("Area:", area)
☰
calculate_area(4, 5)

Example 3: Define a function that repeats a word a specified number of times.

Drag and drop lines into the correct order and click to adjust indentation:
☰
def repeat_word(word, count):
☰
for i in range(count):
☰
print(word)
☰
repeat_word("Python", 3)
☰
 

26.2.1.3. Multiple Choice Questions

Progress: 0
Score: 0 / 0
Question 1 of 0

What is the difference between a parameter and an argument?

Correct! Parameters hold incoming argument data inside the function context.

Incorrect. Roles are reversed.

Incorrect. Parameters define placeholders; arguments supply runtime values.

Incorrect. Both can be any valid data type.

What happens if you call a function requiring 2 parameters with only 1 argument (e.g. def add(x, y): called with add(5))?

Correct! Argument counts must match expected parameter counts.

Incorrect. Unless default values are specified, missing arguments trigger errors.

Incorrect. Python requires explicit arguments for non-default parameters.

Incorrect. Parameter mismatch prevents execution.

Given def multiply(a, b): print(a * b), what is output by multiply(3, 4)?

Correct! Parameter a receives 3, b receives 4; $3 times 4 = 12$.

Incorrect. Multiplication occurs, not addition.

Incorrect. Numeric multiplication evaluates math results rather than string concatenation.

Incorrect. The calculation prints 12.

What value is assigned to city in def trip(city, days): when called as trip("Paris", 5)?

Correct! First positional argument “Paris” maps to first parameter city.

Incorrect. 5 is the second argument, mapping to days.

Incorrect. Arguments map individually to positional parameters.

Incorrect. “Paris” is assigned to city.

How are multiple parameters separated in a function header definition?

Correct! Commas separate multiple parameters.

Incorrect. Colons mark header endings.

Incorrect. Semicolons are not used for parameter separation.

Incorrect. Plus signs denote mathematical addition or concatenation.

What will def show(x): print(x * 2) output when called with show("A")?

Correct! Multiplying string “A” by integer 2 duplicates the string.

Incorrect. String multiplication repeats string characters rather than appending numbers.

Incorrect. String multiplication by integers is syntactically valid in Python.

Incorrect. String content “A” is repeated.

Given def print_full_name(first, last): print(first + " " + last), what outputs for print_full_name("Jane", "Doe")?

Correct! “Jane” maps to first, “Doe” maps to last; concatenation outputs “Jane Doe”.

Incorrect. Positional arguments preserve order: “Jane” first, then “Doe”.

Incorrect. The space string “ “ creates separation.

Incorrect. Valid string concatenation.

Can a function be defined with ZERO parameters?

Correct! Functions like def menu(): require no inputs.

Incorrect. Parameters are optional depending on function design.

Incorrect. Parameter requirements are independent of control statements inside.

Incorrect. Functions accept any number of parameters, including zero.

What parameter values are received in def check(a, b): when calling check(10, 20)?

Correct! Arguments pass positionally from left to right.

Incorrect. Order of parameters is preserved.

Incorrect. Values map directly to variables.

Incorrect. Second argument 20 maps to b.

Given def square(n): print(n ** 2), what call produces an output of 25?

Correct! $5^2 = 25$.

Incorrect. $25^2 = 625$.

Incorrect. $10^2 = 100$.

Incorrect. $2^2 = 4$.

Question 1 of 0

26.3. Return Values

Functions can compute results and send values back to the main program using the return statement:

  • The return Keyword: Ends function execution immediately and hands a specified value back to the caller.

  • Capturing Return Values: The returned value can be stored in a variable or printed directly.

  • Print vs. Return: print() displays output on the console, whereas return passes data back for further computation.

  • Early Exit: Code inside a function after a return statement will never execute.

# Function with return value
def double_value(num):
    return num * 2

# Capturing returned value in a variable
result = double_value(7)
print("Result:", result)  # Output: Result: 14

# Using return value directly in calculations
total = double_value(5) + 10  # (5 * 2) + 10 = 20
print("Total:", total)

26.3.1. Quiz: Return Values

26.3.1.1. Fill-in-the-Blanks (Cloze)

Complete the following sentences by filling in the blanks.
Word Bank (Drag items below):
None
caller
immediately
return
unreachable

1. The Drop here statement sends a calculated result back to where the function was called.
2. A function exits Drop here when a return statement is executed.
3. While `print()` displays text on the screen, `return` hands data back to the Drop here.
4. If a Python function reaches its end without a return statement, it returns Drop here.
5. Code placed directly below a return statement inside the same block is Drop here.

26.3.1.2. Code Ordering Examples

Example 1: Define a function that returns the cube of a number and store its result.

Drag and drop lines into the correct order and click to adjust indentation:
☰
 
☰
return x ** 3
☰
def cube(x):
☰
print(ans)
☰
ans = cube(3)

Example 2: Define a function that checks if a number is even and returns True or False.

Drag and drop lines into the correct order and click to adjust indentation:
☰
 
☰
def is_even(number):
☰
return number % 2 == 0
☰
print(check)
☰
check = is_even(4)

Example 3: Define a function that returns the maximum of two numbers.

Drag and drop lines into the correct order and click to adjust indentation:
☰
return b
☰
def get_max(a, b):
☰
if a > b:
☰
return a
☰
print(highest)
☰
highest = get_max(12, 8)
☰
 

26.3.1.3. Multiple Choice Questions

Progress: 0
Score: 0 / 0
Question 1 of 0

What is the primary difference between print() and return inside a function?

Correct! print showing text differs from return supplying reusable program values.

Incorrect. return exits functions; print does not.

Incorrect. return handles any Python data type.

Incorrect. Displaying output is distinct from returning data values.

What happens to code placed inside a function directly AFTER a return statement?

Correct! Executing return terminates function execution instantly.

Incorrect. Execution stops immediately upon hitting return.

Incorrect. Unreachable code is valid syntax, though useless.

Incorrect. Execution flows sequentially until hitting return.

Given def add(x, y): return x + y, what is stored in val after val = add(10, 20)?

Correct! add(10, 20) evaluates to $10 + 20 = 30$, which is returned and stored in val.

Incorrect. Function explicitly returns x + y.

Incorrect. Integer addition adds numeric values.

Incorrect. Sum result 30 is returned.

What is the return value of a Python function that has NO return statement?

Correct! Functions without return statements implicitly return the special value None.

Incorrect. None is returned rather than integer zero.

Incorrect. None is returned rather than Boolean False.

Incorrect. Executing functions without return statements is completely valid.

Given def Mystery(): return 5; return 10, what value is returned when called?

Correct! Function terminates on the first return statement, returning 5.

Incorrect. Second return statement is unreachable.

Incorrect. Values are not added together.

Incorrect. First return statement returns integer 5.

How can you use the result of a function with a return value in a mathematical calculation?

Correct! Function calls with returns evaluate to their returned values in place.

Incorrect. Printing displays output rather than returning values.

Incorrect. Returned data functions as normal values.

Incorrect. input() captures keyboard input from users.

What does def convert(celsius): return (celsius * 9/5) + 32 compute?

Correct! Evaluates conversion formula and hands back calculation.

Incorrect. Formula represents Celsius to Fahrenheit.

Incorrect. Function returns calculated data rather than printing.

Incorrect. Mathematical calculation is valid.

Given def calc(n): print(n * 2), what is stored in result after result = calc(5)?

Correct! calc prints 10 but lacks a return statement, so result stores None.

Incorrect. 10 is printed, but not returned.

Incorrect. 5 was passed as parameter n.

Incorrect. Valid Python code; assignment receives None.

Can a function return a Boolean value (True or False)?

Correct! Functions return integers, floats, strings, booleans, lists, etc.

Incorrect. Data types are unrestricted.

Incorrect. Functions return any data type.

Incorrect. Return data types are independent of internal loops.

What is output by def check(): return "Pass"; print("Done"); print(check())?

Correct! check() returns “Pass” (skipping print(“Done”)), which is then printed by the outer call.

Incorrect. print(“Done”) is unreachable code after return.

Incorrect. Function exits before reaching print(“Done”).

Incorrect. Explicit return value is “Pass”.

Question 1 of 0

26.4. Variable Scope (Local vs. Global)

Scope determines where variables can be accessed or modified within a Python program:

  • Local Variables: Defined inside a function. They exist only while the function is running and cannot be accessed outside it.

  • Global Variables: Defined outside all functions in the main body of the script. They can be read from anywhere in the file.

  • Scope Isolation: Local variables protect functions from accidentally modifying variables in other parts of your code.

global_var = "I am global"  # Global scope

def my_function():
    local_var = "I am local"  # Local scope
    print(local_var)          # Accessible here
    print(global_var)         # Accessible here

my_function()

# print(local_var)  # NameError! local_var does not exist outside the function!

26.4.1. Quiz: Variable Scope

26.4.1.1. Fill-in-the-Blanks (Cloze)

Complete the following sentences by filling in the blanks.
Word Bank (Drag items below):
NameError
global
local
name
outside

1. A variable defined inside a function has Drop here scope.
2. A variable defined outside all functions in a file has Drop here scope.
3. Local variables cannot be accessed Drop here the function where they were created.
4. Attempting to print an uncreated or out-of-scope local variable raises a Drop here.
5. Local variable scope isolates functions to prevent unintentional variable Drop here conflicts.

26.4.1.2. Code Ordering Examples

Example 1: Demonstrate local variable scope inside a function.

Drag and drop lines into the correct order and click to adjust indentation:
☰
print(msg)
☰
create_message()
☰
def create_message():
☰
 
☰
msg = "Inside local scope"

Example 2: Access a global variable from inside a function block.

Drag and drop lines into the correct order and click to adjust indentation:
☰
 
☰
app_name = "MathQuiz"
☰
display_app()
☰
def display_app():
☰
print("Welcome to", app_name)
☰
 

Example 3: Show local variable isolation with same variable name as global variable.

Drag and drop lines into the correct order and click to adjust indentation:
☰
 
☰
x = 100
☰
print("Local x:", x)
☰
override()
☰
print("Global x:", x)
☰
x = 5
☰
def override():
☰
 

26.4.1.3. Multiple Choice Questions

Progress: 0
Score: 0 / 0
Question 1 of 0

Where can a local variable defined inside a function be accessed?

Correct! Local scope restricts variable existence to the enclosing function.

Incorrect. Global variables are accessible anywhere, not local ones.

Incorrect. Scope remains bound to function definition.

Incorrect. Local scope is restricted to the declaring function.

What happens if you try to print a local variable outside its function?

Correct! The variable name is undefined in global scope.

Incorrect. The variable does not exist in outer scope.

Incorrect. Out-of-scope variables raise errors.

Incorrect. Execution crashes with a NameError.

Given score = 100 defined at the top of a script outside functions, what scope does score have?

Correct! Variables defined at module root level hold global scope.

Incorrect. Local variables are defined inside function bodies.

Incorrect. “Universal scope” is not standard Python terminology.

Incorrect. Python manages local and global scopes for functions.

What output is produced by x = 10; def run(): x = 20; run(); print(x)?

Correct! x = 20 inside run() creates a local variable x, leaving global x as 10.

Incorrect. Modifying local x does not alter global x.

Incorrect. Values are kept in isolated scopes.

Incorrect. Global x exists and holds 10.

Why is local scope useful when building large programming projects?

Correct! Scope isolation protects variable state.

Incorrect. Scope management relates to variable visibility rather than performance speed.

Incorrect. Scope manages memory references for active execution.

Incorrect. Local variables remain mutable within their scope.

Can a function read the value of a global variable without special keywords?

Correct! Functions can read global variable values directly.

Incorrect. Global values can be read within functions.

Incorrect. Any global data type can be read.

Incorrect. Reading globals is syntactically valid.

Given def set_val(): a = 50; set_val(); print(a), what occurs when running this code?

Correct! Variable a is local to set_val() and cannot be printed globally.

Incorrect. Variable a is inaccessible outside set_val().

Incorrect. Variable a does not exist in global scope.

Incorrect. Undefined global variables trigger NameError.

What is variable shadowing in Python?

Correct! Local variables shadow global variables of identical name.

Incorrect. Shadowing hides global names locally rather than deleting them.

Incorrect. Shadowing occurs within local function boundaries.

Incorrect. Shadowing refers to variable name collisions across scopes.

When is a local variable created and destroyed?

Correct! Local variable lifetimes match function call execution.

Incorrect. That describes global variable lifetimes.

Incorrect. Memory is cleaned up after function execution ends.

Incorrect. Exists throughout function execution.

What output is produced by val = "A"; def test(): print(val); test()?

Correct! test() reads global variable val and prints “A”.

Incorrect. Global val is accessible for reading inside test().

Incorrect. val holds string “A”.

Incorrect. Valid global variable access.

Question 1 of 0