Python Functions in Python | Complete Guide for Students
Learn Python functions with easy examples, parameters, arguments, return values, local and global variables, lambda functions, and practice questions with answers.
Python Functions
Learn how to create reusable blocks of code, pass information into functions, return results, understand variable scope, and write cleaner programs. Study the examples, trace the output, and test yourself with practice questions.
1. What is a function?
A function is a named, reusable block of code that performs a particular task. Instead of writing the same instructions repeatedly, we can place them in a function and call that function whenever needed.
For example, a program may need to greet several students. A function can hold the greeting instructions so they do not have to be repeated.
def greet():
print("Hello, student!")
greet()
Output:
Hello, student!
def greet(): defines the function and greet() calls it.2. Why do we use functions?
- Code reuse: write instructions once and use them many times.
- Less repetition: avoid copying the same block of code throughout a program.
- Readability: meaningful function names help explain what the program does.
- Easy testing and debugging: a task can be checked separately.
- Modularity: a large program can be divided into smaller, manageable tasks.
Without a function
print("Welcome, Mina!")
print("Welcome, Arun!")
print("Welcome, Sita!")
With a function
def welcome(name):
print("Welcome,", name)
welcome("Mina")
welcome("Arun")
welcome("Sita")
Both examples display greetings, but the second version reuses one set of instructions.
3. How to define and call a function
Python uses the keyword def to define a function.
def function_name():
# statements inside the function
statement
| Part | Meaning |
|---|---|
def |
Keyword that begins a function definition. |
function_name |
The name used to refer to and call the function. |
() |
Parentheses hold parameters, if the function needs them. |
: |
Marks the start of the function body. |
| Indented body | The statements that run when the function is called. |
Example: a function without parameters
def show_message():
print("Python is easy to learn.")
show_message()
show_message()
Output:
Python is easy to learn.
Python is easy to learn.
The function is called twice, so its body executes twice. Defining it alone would not print anything.
4. How does function execution work?
When Python reaches a function definition, it records the function. The body does not run until the function is called. When called, Python executes the body and then returns to the point after the call.
def say_hi(): and creates the function.say_hi() and enters the function body.def say_hi():
print("Hi!")
print("Start")
say_hi()
print("End")
Output:
Start
Hi!
End
Notice that Hi! appears between Start and End because the function runs where it is called.
5. Parameters and arguments
A function can receive data so it can work with different values on different calls.
- A parameter is a variable listed in the function definition.
- An argument is the actual value or expression supplied when calling the function.
def greet(name): # name is a parameter
print("Hello,", name)
greet("Mina") # "Mina" is an argument
greet("Arun") # "Arun" is an argument
Output:
Hello, Mina
Hello, Arun
Example with two parameters
def add(a, b):
print(a + b)
add(4, 6)
add(10, 20)
Output:
10
30
In add(4, 6), parameter a receives 4 and parameter b receives 6. The next call supplies different arguments.
6. The return statement: return vs print
The return statement sends a result back to the code that called the function. The returned value can be stored, used in a calculation, or passed to another function. By contrast, print() displays information on the screen.
Using print()
def add_print(a, b):
print(a + b)
result = add_print(3, 4)
print("Result variable:", result)
Output:
7
Result variable: None
The function displays 7, but it does not return that number. Because no value is returned explicitly, Python returns None.
Using return
def add(a, b):
return a + b
result = add(3, 4)
print(result)
print(result * 2)
Output:
7
14
Here, add(3, 4) evaluates to 7, which is stored in result. We can use that value again.
Return ends the current function call
def check_number(number):
if number < 0:
return "Negative"
return "Zero or positive"
print(check_number(-3))
print(check_number(5))
Output:
Negative
Zero or positive
Once a return statement executes, the function call ends. Statements later in that same execution path are not run.
print() |
return |
|---|---|
| Displays output on the screen. | Sends a value back to the caller. |
| Does not, by itself, make that displayed value the function's result. | The returned value can be assigned to a variable or reused. |
| A function can print and still return nothing explicitly. | A function may return a number, string, list, or another object. |
7. Types of arguments
A. Positional arguments
Values are matched to parameters by their position.
def describe(name, age):
print(name, "is", age, "years old.")
describe("Mina", 16)
Here, "Mina" goes to name and 16 goes to age. Changing their order changes which parameter receives each value.
B. Keyword arguments
Keyword arguments specify a parameter by name, so the order can be changed.
def describe(name, age):
print(name, "is", age, "years old.")
describe(age=16, name="Mina")
This produces the same result as the positional call above.
C. Default parameter values
A default value is used when the caller does not provide an argument for that parameter.
def greet(name, message="Welcome"):
print(message, name)
greet("Mina")
greet("Arun", "Good morning")
Output:
Welcome Mina
Good morning Arun
In the first call, message uses its default value. In the second call, the supplied argument replaces the default for that call.
D. Variable-length positional arguments: *args
Use *args when a function should accept any number of positional arguments. Inside the function, args is a tuple.
def add_many(*args):
total = 0
for number in args:
total += number
return total
print(add_many(2, 3))
print(add_many(2, 3, 4, 5))
Output:
5
14
The name args is conventional; the asterisk is what collects extra positional arguments into a tuple.
E. Variable-length keyword arguments: **kwargs
Use **kwargs to collect extra keyword arguments into a dictionary.
def show_details(**kwargs):
for key, value in kwargs.items():
print(key, ":", value)
show_details(name="Mina", age=16)
Output:
name : Mina
age : 16
*args collects extra positional arguments; **kwargs collects extra keyword arguments. These are useful concepts to recognize even if you are just starting out.
8. Local and global variable scope
Scope describes where a variable name can be accessed in a program.
Local variable
A variable created inside a function is usually local to that function. It is not normally available outside the function.
def show_number():
number = 10
print(number)
show_number()
# print(number) # NameError: number is not defined here
Global variable
A variable created outside functions is a global variable. A function can read a global variable if a local name does not shadow it.
school = "Sunrise School"
def show_school():
print(school)
show_school()
print(school)
Output:
Sunrise School
Sunrise School
A local variable can have the same name
number = 5
def display():
number = 20
print("Inside:", number)
display()
print("Outside:", number)
Output:
Inside: 20
Outside: 5
The assignment inside display() creates a local variable, so the global number remains 5.
Changing a global variable with global
count = 0
def increase():
global count
count = count + 1
increase()
print(count)
Output:
1
The global keyword tells Python that assignments to count inside this function refer to the global variable. In well-organized programs, returning a new value is often easier to reason about than changing global state.
9. Passing objects to functions
Python passes object references to functions. This means a function can modify a mutable object, such as a list, and the caller can see that change. Reassigning a parameter name, however, does not reassign the caller's variable.
Modifying a list
def add_item(items):
items.append("pen")
my_items = ["book", "pencil"]
add_item(my_items)
print(my_items)
Output:
['book', 'pencil', 'pen']
The function changes the same list object by appending an item.
Reassigning a parameter
def change_value(number):
number = 100
score = 50
change_value(score)
print(score)
Output:
50
Assigning 100 to the local parameter name does not change the caller's variable score.
10. Built-in functions and lambda functions
Built-in functions
Python already provides many functions. You can use them without defining them yourself.
| Function | Purpose | Example |
|---|---|---|
print() |
Displays information. | print("Hello") |
len() |
Returns the length of a sequence or collection. | len("Python") gives 6. |
max() |
Returns the largest item. | max(3, 8, 2) gives 8. |
min() |
Returns the smallest item. | min(3, 8, 2) gives 2. |
sum() |
Adds the items of an iterable of numbers. | sum([2, 3, 4]) gives 9. |
type() |
Reports an object's type. | type(5) gives int. |
abs() |
Returns the absolute value of a number. | abs(-7) gives 7. |
Lambda functions
A lambda function is a small anonymous function written as a single expression. It can be useful for short operations.
square = lambda number: number * number
print(square(5))
Output:
25
The equivalent ordinary function is often clearer for beginners:
def square(number):
return number * number
Use def for most named functions, especially when the task requires multiple statements or a clear explanation.
11. Common mistakes to avoid
- Forgetting to call the function:
def greet():defines it;greet()runs it. - Missing parentheses in a call: use
greet(), notgreet, when you want to call it. - Incorrect indentation: indent the function body consistently.
- Wrong number of arguments: a function requiring two parameters generally needs two corresponding arguments unless defaults or variable-length arguments apply.
- Confusing parameter and argument: the parameter is in the definition; the argument is supplied in the call.
- Confusing print and return: printing displays a value; returning gives a value back to the caller.
- Using a local variable outside its function: local names are not normally accessible outside their scope.
- Unreachable code after return: a statement after an executed
returnin the same path will not run. - Using a variable before defining it: ensure the name is defined in an accessible scope before it is used.
12. Practice questions
Try each question before opening its answer. Questions include definitions, code tracing, and short programming tasks.
Part A — Short-answer questions
1. What is a function in Python?
Show answer
A named, reusable block of code designed to perform a particular task.
2. Which keyword is used to define a function?
Show answer
The def keyword.
3. What is the difference between a parameter and an argument?
Show answer
A parameter is a variable in the function definition. An argument is a value or expression supplied in a function call.
4. Give three advantages of using functions.
Show answer
Code reuse, reduced repetition, improved readability, easier testing and debugging, and modular program structure. Any three are acceptable.
5. What is the purpose of the return statement?
Show answer
It ends the current function call and sends a result back to the caller.
6. What does a function return if it reaches the end without a return value?
Show answer
It returns None.
7. Explain local and global variables.
Show answer
A local variable is defined within a function and is normally accessible only there. A global variable is defined outside functions and can be read from functions when not shadowed by a local name.
8. What is a default parameter value?
Show answer
A value used for a parameter when the caller does not supply an argument for it.
9. State the difference between positional and keyword arguments.
Show answer
Positional arguments are matched by their order; keyword arguments identify the parameter by name.
10. What is the difference between *args and **kwargs?
Show answer
*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dictionary.
Part B — Read the code and predict the output
11. What is displayed?
def hello():
print("Hello")
hello()
hello()
Show answer
Hello
Hello
12. What is displayed?
def multiply(a, b):
return a * b
print(multiply(3, 4))
Show answer
12
13. What is displayed?
def test():
print("A")
return 10
print("B")
print(test())
Show answer
A
10
print("B") is not executed because the function has already returned.
14. What is displayed?
x = 8
def show():
x = 3
print(x)
show()
print(x)
Show answer
3
8
The local variable inside show() does not change the global variable.
15. What is displayed?
def greet(name, message="Hi"):
return message + " " + name
print(greet("Sita"))
print(greet("Ram", "Hello"))
Show answer
Hi Sita
Hello Ram
16. What is displayed?
def add_item(items):
items.append(4)
values = [1, 2, 3]
add_item(values)
print(values)
Show answer
[1, 2, 3, 4]
Part C — Write the code
17. Define a function named greet that prints Welcome to Python!. Call it once.
Show answer
def greet():
print("Welcome to Python!")
greet()
18. Write a function named square that accepts a number and returns its square. Print the square of 6.
Show answer
def square(number):
return number * number
print(square(6))
19. Write a function named maximum that accepts two numbers and returns the larger number. (You may use an if statement.)
Show answer
def maximum(a, b):
if a > b:
return a
return b
print(maximum(12, 9))
20. Write a function that accepts a student's marks and returns "Pass" if marks are at least 40, otherwise returns "Fail".
Show answer
def result(marks):
if marks >= 40:
return "Pass"
return "Fail"
print(result(72))
print(result(25))
21. Write a function with a default parameter country="Nepal" that prints a person's name and country. Show one call using the default and one call supplying another country.
Show answer
def show_person(name, country="Nepal"):
print(name, "is from", country)
show_person("Mina")
show_person("Alex", "Canada")
22. Write a function that accepts any number of numeric arguments and returns their sum using *args.
Show answer
def total(*args):
return sum(args)
print(total(2, 4, 6))
print(total(1, 2, 3, 4, 5))
Part D — Practical challenges
23. Create a calculator using separate functions for addition, subtraction, multiplication, and division. Ask the user for two numbers, then display the four results. Make sure to handle division by zero.
Show one possible solution
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
return "Cannot divide by zero"
return a / b
first = float(input("Enter first number: "))
second = float(input("Enter second number: "))
print("Addition:", add(first, second))
print("Subtraction:", subtract(first, second))
print("Multiplication:", multiply(first, second))
print("Division:", divide(first, second))
24. Create a function count_vowels(text) that returns the number of vowels in a string. Test it with "Python Programming".
Show one possible solution
def count_vowels(text):
count = 0
for character in text.lower():
if character in "aeiou":
count += 1
return count
print(count_vowels("Python Programming"))
The output is 4.
25. Write a function calculate_average(numbers) that returns the average of a list of numbers. What should happen if the list is empty?
Show one possible solution
def calculate_average(numbers):
if len(numbers) == 0:
return None
return sum(numbers) / len(numbers)
print(calculate_average([70, 80, 90]))
print(calculate_average([]))
The first call returns 80.0; the second returns None to indicate that an average cannot be calculated for an empty list.
print() from return, explain local/global scope, and write a function that solves a small problem?