Defining and Calling Functions with def in Python
Course: Python Training
Topic: Defining and Calling Functions with def
Course Link: Python Training Course – JustAcademy
Demo Link: Register for a Course Demo
Official Website: JustAcademy
1. Introduction to Functions in Python
A function is a reusable block of code designed to perform a specific task. Instead of writing the same instructions repeatedly, you can define a function once and call it whenever required. Functions help make Python programs organized, readable, reusable, and easier to test and maintain.
For example, if a program needs to display a welcome message in several places, you can create one function that displays the message and call it whenever needed.
Python provides the def keyword to define a function. A function can accept input values called parameters, perform operations, and optionally return a result to the code that called it.
2. Learning Objectives
After completing this topic, you will be able to:
- Understand what functions are and why they are useful.
- Define functions using the
def keyword.
- Call functions to execute their code.
- Understand function names, parameters, arguments, and function bodies.
- Pass values into functions and work with return values.
- Use functions with and without parameters.
- Understand local variables and function scope.
- Identify common function errors and follow best practices.
- Build small programs using reusable functions.
3. What Is the def Keyword?
The def keyword is used to define a function in Python. When Python encounters a function definition, it creates the function object and binds it to the specified name. The function body runs when the function is called, not merely when it is defined.
Basic syntax:
def function_name():
# Statements to execute
pass
Explanation of the syntax:
| Component |
Description |
def |
Keyword used to define a function. |
function_name |
Name used to refer to and call the function. |
() |
Parentheses that contain optional parameters. |
: |
Colon that marks the beginning of the function body. |
| Indented statements |
Instructions executed when the function is called. |
pass |
A placeholder statement that does nothing, useful while developing a function body. |
4. Defining Your First Function
Consider a function that displays a simple message.
def greet():
print("Hello, welcome to Python!")
greet()
Output:
Hello, welcome to Python!
Explanation:
def greet(): defines a function named greet.
- The indented
print() statement forms the function body.
greet() calls the function.
- Python executes the function body and displays the message.
Function definitions and function calls serve different purposes. Defining a function establishes what the function does, while calling it requests that the function execute.
5. Defining and Calling a Function Step by Step
Step 1: Choose a Function Name
Choose a meaningful name that describes the task. For example, display_message() is more descriptive than abc().
Step 2: Write the Function Definition
def display_message():
print("Learning Python functions")
Step 3: Call the Function
display_message()
Complete Program
def display_message():
print("Learning Python functions")
display_message()
display_message()
Output:
Learning Python functions
Learning Python functions
The same function is called twice, so the same message is displayed twice. This demonstrates code reuse.
6. Functions Without Parameters
A function without parameters does not require input values from the caller. It can still perform tasks such as displaying information, printing a menu, or showing instructions.
def show_menu():
print("1. View Profile")
print("2. Update Profile")
print("3. Exit")
show_menu()
Output:
1. View Profile
2. Update Profile
3. Exit
Use a function without parameters when the task can be performed without receiving input from the caller.
7. Functions with Parameters
Parameters are variable names written in a function definition. They allow the function to receive values from the caller and use those values when executing its statements.
Syntax:
def function_name(parameter):
# Use the parameter
pass
Example: Greeting a User
def greet_user(name):
print("Hello,", name)
greet_user("Amit")
greet_user("Priya")
Output:
Hello, Amit
Hello, Priya
Here, name is the parameter. The values "Amit" and "Priya" are arguments supplied in the function calls.
Multiple Parameters
A function can accept multiple parameters separated by commas.
def display_student(name, age, course):
print("Name:", name)
print("Age:", age)
print("Course:", course)
display_student("Neha", 22, "Python")
Output:
Name: Neha
Age: 22
Course: Python
When positional arguments are supplied, they are assigned to parameters according to their order in the function definition.
8. Difference Between Parameters and Arguments
| Parameter |
Argument |
| A name specified in a function definition. |
A value or expression supplied when calling a function. |
| Receives the supplied value during the call. |
Provides the input used by the function. |
Example: name in def greet(name): |
Example: "Amit" in greet("Amit") |
9. Returning Values from Functions
A function can calculate a result and send it back to the caller using the return statement. The returned value can be stored in a variable, displayed, passed to another function, or used in an expression.
Example: Adding Two Numbers
def add(a, b):
return a + b
result = add(10, 20)
print(result)
Output:
30
Explanation: The function calculates a + b and returns the result. The call add(10, 20) produces 30, which is stored in result.
Difference Between print() and return
def add_and_print(a, b):
print(a + b)
def add_and_return(a, b):
return a + b
first = add_and_print(5, 3)
second = add_and_return(5, 3)
print("First:", first)
print("Second:", second)
Output:
8
First: None
Second: 8
The first function displays 8 but does not explicitly return a value, so its result is None. The second function returns 8, making the result available for further use.
10. Functions That Return Multiple Values
Python functions can return multiple values separated by commas. Python packages those values into a tuple, which can be unpacked into separate variables.
def calculate(a, b):
total = a + b
difference = a - b
return total, difference
sum_result, difference_result = calculate(15, 5)
print("Sum:", sum_result)
print("Difference:", difference_result)
Output:
Sum: 20
Difference: 10
11. Using the return Statement
The return statement ends the current function call and sends a value back to the caller. Any statements after an executed return in the same execution path are not run.
def check_number(number):
if number > 0:
return "Positive"
elif number < 0:
return "Negative"
return "Zero"
print(check_number(10))
print(check_number(-5))
print(check_number(0))
Output:
Positive
Negative
Zero
If a function reaches the end without executing a return statement with a value, Python returns None.
12. Default Parameter Values
Default parameters provide a value that Python uses when the caller does not supply an argument for that parameter.
def greet(name="Guest"):
print("Welcome,", name)
greet()
greet("Rahul")
Output:
Welcome, Guest
Welcome, Rahul
Parameters with default values must follow parameters without default values in a function definition. Also, avoid using mutable objects such as lists as default values unless shared state is specifically intended.
13. Calling Functions with Keyword Arguments
Keyword arguments specify values by parameter name. They improve readability and allow arguments to be supplied in a different order from the parameter list.
def describe_person(name, age, city):
print(name, age, city)
describe_person(
city="Mumbai",
name="Priya",
age=25
)
Output:
Priya 25 Mumbai
Keyword argument names must match the function's parameter names. Required parameters must still receive values.
14. Local Variables and Function Scope
A variable created inside a function is usually local to that function. It can be accessed within the relevant function scope but cannot normally be referenced directly from outside the function.
def calculate_square(number):
result = number ** 2
return result
print(calculate_square(4))
# print(result) # NameError: result is not defined here
Output:
16
The variable result is local to calculate_square(). Its value is made available outside the function through the returned result.
15. Function Docstrings and Readability
A docstring is a string placed immediately after a function definition. It explains the function's purpose and can describe its inputs and return value.
def calculate_area(length, width):
"""Return the area of a rectangle."""
return length * width
print(calculate_area(5, 4))
print(calculate_area.__doc__)
Output:
20
Return the area of a rectangle.
Use descriptive names, consistent indentation, and docstrings for functions whose purpose or behavior may not be immediately obvious.
16. Common Errors When Defining and Calling Functions
Understanding common function errors helps you identify problems quickly and write reliable Python programs.
16.1 Forgetting Parentheses When Calling a Function
def greet():
print("Hello!")
greet
Explanation: Writing greet refers to the function object but does not execute it. Use parentheses to call the function.
greet()
Output:
Hello!
16.2 Missing the Colon
# Incorrect
def greet()
print("Hello!")
Problem: A function definition must end with a colon.
# Correct
def greet():
print("Hello!")
16.3 Incorrect Indentation
# Incorrect
def greet():
print("Hello!")
Problem: Python uses indentation to identify the function body.
# Correct
def greet():
print("Hello!")
16.4 Missing a Required Argument
def greet(name):
print("Hello,", name)
# greet() # TypeError: required argument is missing
greet("Amit")
Output:
Hello, Amit
16.5 Expecting a Printed Value to Be Returned
def multiply(a, b):
print(a * b)
result = multiply(4, 5)
print(result)
Output:
20
None
Problem: The function displays the product but does not return it. Use return a * b if the caller needs the result.
16.6 Calling a Function Before It Is Defined
In a normal script, the function definition must have been executed before the function is called. Otherwise, the function name may not yet exist and Python can raise a NameError.
17. Practical Real-World Examples
17.1 Simple Calculator
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
print("Addition:", add(10, 5))
print("Subtraction:", subtract(10, 5))
print("Multiplication:", multiply(10, 5))
print("Division:", divide(10, 5))
print("Division:", divide(10, 0))
Output:
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
Division: Cannot divide by zero
17.2 Calculating the Area of a Rectangle
def calculate_area(length, width):
"""Calculate and return the area of a rectangle."""
return length * width
area = calculate_area(8, 5)
print("Area:", area)
Output:
Area: 40
17.3 Calculating a Student's Average
def calculate_average(mark1, mark2, mark3):
return (mark1 + mark2 + mark3) / 3
average = calculate_average(80, 90, 85)
print("Average marks:", average)
Output:
Average marks: 85.0
17.4 Checking Whether a Number Is Even
def is_even(number):
return number % 2 == 0
print(is_even(8))
print(is_even(7))
Output:
True
False
17.5 Applying a Discount to a Product
def calculate_discounted_price(price, discount_percent):
discount = price * discount_percent / 100
return price - discount
final_price = calculate_discounted_price(2000, 15)
print("Final price:", final_price)
Output:
Final price: 1700.0
18. Best Practices for Writing Functions
- Choose descriptive names such as
calculate_total(), find_average(), and display_menu().
- Follow the common Python naming convention of lowercase words separated by underscores, known as snake_case.
- Keep each function focused on one clear responsibility.
- Use parameters to make functions reusable with different inputs.
- Use
return when the caller needs to work with a calculated result.
- Use
print() when the purpose is to display information, rather than to provide a result for further computation.
- Indent the function body consistently, typically using four spaces.
- Add docstrings to explain the purpose of functions, especially when their behavior is not obvious.
- Handle expected edge cases, such as division by zero or invalid input.
- Avoid unnecessary global variables. Pass required values through parameters and return results when practical.
- Test functions with normal inputs, boundary cases, and unexpected values.
- Avoid overly long functions that perform many unrelated tasks.
19. Practice Exercises
Exercise 1: Welcome Message
Define a function named welcome() that prints a welcome message. Call it three times.
Exercise 2: Personal Greeting
Create a function named greet_person(name) that accepts a person's name and displays a personalized greeting.
Exercise 3: Add Two Numbers
Define a function named add_numbers(a, b) that returns the sum of two numbers. Store the result in a variable and print it.
Exercise 4: Find the Square
Create a function named square(number) that returns the square of a given number.
Exercise 5: Check Eligibility
Write a function named check_age(age) that returns "Eligible" if the age is at least 18 and "Not eligible" otherwise.
Exercise 6: Calculate a Bill
Create a function that accepts a product price and quantity, then returns the total bill.
20. Practice Exercise Solutions
Solution 1: Welcome Message
def welcome():
print("Welcome to Python programming!")
welcome()
welcome()
welcome()
Output:
Welcome to Python programming!
Welcome to Python programming!
Welcome to Python programming!
Solution 2: Personal Greeting
def greet_person(name):
print(f"Hello, {name}! Welcome to Python.")
greet_person("Amit")
Output:
Hello, Amit! Welcome to Python.
Solution 3: Add Two Numbers
def add_numbers(a, b):
return a + b
result = add_numbers(25, 15)
print("Sum:", result)
Output:
Sum: 40
Solution 4: Find the Square
def square(number):
return number ** 2
print(square(6))
Output:
36
Solution 5: Check Eligibility
def check_age(age):
if age >= 18:
return "Eligible"
return "Not eligible"
print(check_age(20))
print(check_age(16))
Output:
Eligible
Not eligible
Solution 6: Calculate a Bill
def calculate_bill(price, quantity):
return price * quantity
total = calculate_bill(250, 4)
print("Total bill:", total)
Output:
Total bill: 1000
21. Interview Questions and Answers
Q1. What is a function in Python?
Answer: A function is a reusable block of code that performs a specific task. It can accept inputs, execute instructions, and optionally return a result.
Q2. Which keyword is used to define a function?
Answer: Python uses the def keyword to define a function.
Q3. What is the difference between defining and calling a function?
Answer: Defining a function establishes its code and behavior. Calling a function executes its body.
Q4. What are parameters and arguments?
Answer: Parameters are names listed in the function definition. Arguments are the values or expressions supplied when calling the function.
Q5. What happens if a function has no return statement?
Answer: If the function finishes without returning a value explicitly, Python returns None.
Q6. What is the difference between print() and return?
Answer: print() displays information, while return sends a value back to the caller so it can be stored or used in another expression.
Q7. Can a function have more than one parameter?
Answer: Yes. Multiple parameters can be specified in the function definition, separated by commas.
Q8. What is a default parameter?
Answer: A default parameter has a predefined value that is used when the caller does not supply an argument for it.
Q9. What is a local variable?
Answer: A local variable is a name assigned within a function's local scope and is normally accessible only within that scope.
Q10. What is a docstring?
Answer: A docstring is a string literal placed at the beginning of a function body to document its purpose and behavior.
Q11. Why are functions important in programming?
Answer: Functions reduce code duplication, improve readability, organize logic, simplify testing, and make programs easier to maintain.
Q12. What error occurs when a required argument is missing?
Answer: Python generally raises a TypeError when a function is called without a required argument.
22. Quick Revision Checklist
- The
def keyword defines a function.
- A function definition includes a name, parentheses, a colon, and an indented body.
- A function call uses the function name followed by parentheses.
- Parameters receive values supplied as arguments.
- Functions can have zero, one, or multiple parameters.
- The
return statement sends a result back to the caller.
- A function without an explicit returned value produces
None.
- Default parameters allow selected arguments to be omitted.
- Keyword arguments identify values by parameter name.
- Local variables belong to their local scope.
- Docstrings document the purpose of a function.
- Descriptive names, consistent indentation, and simple function responsibilities improve code quality.
23. Conclusion
Defining and calling functions with def is a fundamental Python programming skill. Functions help divide a program into manageable tasks, accept different inputs through parameters, and provide results through return values. By practicing function definitions, function calls, scope, default arguments, and error handling, you can develop more reusable, readable, and maintainable Python applications.
Continue learning with these JustAcademy resources: