Python function definition and calling
Table of Contents
Description
A function in Python is a reusable block of code that performs a specific task. Functions help in modular programming, increase code reusability, and reduce redundancy.
You define a function using the def keyword, and you call it by its name followed by parentheses ()
Prerequisites
- Understanding of Python syntax and indentation
- Basics of variables and data types
- Familiarity with expressions and control flow
Examples
Here's a simple program in Python:
# Defining a basic function
def greet():
# This function simply prints a message
print("Hello, welcome to Python!")
# Calling the function
greet() # Output: Hello, welcome to Python!
# Function with parameters
def add(a, b):
# This function adds two numbers
return a + b
# Calling the function with arguments
result = add(10, 5)
print("Sum:", result) # Output: Sum: 15
# Function with default parameter
def greet_user(name="Guest"):
print(f"Hello, {name}!")
greet_user("Basha") # Output: Hello, Basha!
greet_user() # Output: Hello, Guest!
# Function with return type
def square(x):
return x * x
print(square(4)) # Output: 16
Real-World Applications
Code modularization in large projects
Reusable logic like login verification, payment processing
Data analysis functions: clean, transform, and visualize
API creation: each endpoint often maps to a function
Game development: handling controls, physics, and rendering
Where topic Can Be Applied
Web development (Flask/Django): views and routes are functions
Data Science: analysis pipelines use custom-defined functions
Automation scripts: for repeated actions (e.g., file operations)
Machine Learning: feature extraction, training logic in functions
System programming: to handle modules or drivers
Resources
Topic video source
A comprehensive video
Watch
Python pdf
pdf on topic
Visit
Interview Questions
What is a function in Python?
How do you define and call a function?
What is the difference between a parameter and an argument?
Can a function return multiple values? How?
What is the purpose of default and keyword arguments?