UG Program in Electronics and Computer Science
Function in Python
Functions are a very essential part of any programming language. They help our
code to make it modular, reusable, and organized. Instead of writing the same code
again and again, we can create a function and call it whenever it is needed.
We will understand everything about functions in Python, including their types,
how to define and use them, and provide various practical examples.
What is a Function?
A function is a block of reusable code that performs a specific task. Instead of
writing the same logic multiple times, you can define a function once and call it
whenever required. Think of a function as a mini-program within your main
program.
How to Define a Function in Python?
To define a function in Python, we use the def keyword, followed by the function
name and parentheses.
Syntax
def function_name():
# Function body
print("Hello, this is a function!")
Example
def greet():
print("Hello, welcome to Python functions!")
greet() # Calling the function
Output
Hello, welcome to Python functions!
Function Parameters and Arguments
● Parameters: Variables defined in the function definition. They act as
placeholders for the data that the function will receive.
● Arguments: The actual values that are passed to the function when it is
called.
Example
def add(x, y): # x and y are parameters
sum_result = x + y
return sum_result
a=5
b = 10
result = add(a, b) # a and b are arguments
print("Sum: ", result)
Output
Sum: 15
In the above program, x and y are parameters. On the other hand, a and b are
arguments.
Types of Arguments
Python allows multiple ways to pass arguments to a function:
Positional Arguments: Arguments are passed in the order they are defined in the
function definition.
def describe_person(name, age, city):
print(f"Name: {name}, Age: {age}, City: {city}")
describe_person("Subhankar", 26, "Kolkata")
Output
Name: Subhankar, Age: 26, City: Kolkata
What does f mean?
The f before the string means formatted string (f-string).
It allows you to insert variables directly inside a string using {}.
Without f-string (old way):
print("Name:", name, "Age:", age, "City:", city)
Using an f-string is cleaner and easier
Keyword Arguments: Arguments are passed using the parameter names. This
technique allows to specify arguments in any order.
def describe_person(name, age, city):
print(f"Name: {name}, Age: {age}, City: {city}")
describe_person(city="Kolkata", name="Subhankar", age=26)
Output
Name: Subhankar, Age: 26, City: Kolkata
Default Arguments: We can specify default values for parameters in the function
definition. If an argument is not provided for that parameter in the function call, the
default value is used.
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Sofia")
greet("Sneha", "Good morning")
Output
Hello, Sofia!
Good morning, Sneha!
Important Note: Default parameter values are evaluated only once when the
function definition is executed. This can cause unexpected behavior with mutable
default arguments like lists.
Variable-Length Arguments
1. *args (Arbitrary Positional Arguments): It allows a variable number of
positional arguments. The arguments are collected into a tuple.
def sum_all(*args):
total = 0
for num in args:
total += num
return total
print(sum_all(1, 2, 3)) # Output: 6
print(sum_all(1, 2, 3, 4, 5)) # Output: 15
2. **kwargs (Arbitrary Keyword Arguments): It allows to pass a variable number
of keyword arguments. The arguments are collected into a dictionary.
def print_info(**kwargs):
"""Prints key-value pairs from the keyword arguments."""
for key, value in [Link]():
print(f"{key}: {value}")
print_info(name="Subhankar", age=26, city="Kolkata")
Output
name: Subhankar
age: 26
city: Kolkata
Return Statement in Functions
A function can send data back to the caller using the return statement. The return
statement ends the function’s execution, and the value specified is returned.
def multiply(x, y):
"""Multiplies two numbers and returns the result."""
result = x * y
return result
product = multiply(5, 4)
print(product) # Output: 20
If a function doesn’t have a return statement, or if the return statement doesn’t
specify a value (just return), the function returns None.
def say_hello(name):
print(f"Hello, {name}!")
# No return statement
result = say_hello("PySeek")
print(result) # Output: None
Function Scope
Variables defined inside a function have local scope, meaning they are only
accessible within that function.
Example
def example():
x = 10 # Local variable
print(x)
example()
print(x) # Error: x is not defined outside the function
Variables defined outside of any function have global scope, meaning they are
accessible from anywhere in the program.
global_var = 10 # Global variable
def my_function():
print(global_var) # Accessing global variable is allowed
my_function()
print(global_var) # Accessing global variable outside the function is allowed
Nested Functions
Python allows to define functions inside other functions. These are called nested
functions or inner functions. Inner functions have access to the variables in the
enclosing function’s scope.
def outer_function(x):
def inner_function(y):
return x + y # inner_function can access x from outer_function
return inner_function(5)
result = outer_function(10)
print(result) # Output: 15
Types of Functions in Python
Python offers different types of function.
Built-in Functions
Python has several built-in functions. For example, print(), len(), type(), max(),
min(), etc.
numbers = [1, 2, 3, 4, 5]
print(len(numbers)) # Output: 5
User-defined Functions
Functions created by us to perform specific tasks are called user-defined functions.
def square(num):
return num * num
print(square(6)) # Output: 36
Lambda Functions
A lambda function is a small anonymous function that can have any number of
arguments but only one expression. This type of function doesn’t have a name.
square = lambda x: x * x
print(square(7)) # Output: 49
Recursive Functions
Recursive function is a function that call itself during the execution.
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
Higher-Order Functions in Python
Functions that take other functions as arguments or return functions.
def apply_operation(operation, a, b):
return operation(a, b)
result = apply_operation(lambda x, y: x + y, 3, 7)
print(result) # Output: 10
Exercises
1. Define a function called greet that takes a name as a parameter and prints a
personalized greeting message (e.g., “Hello, [name]!”).
2. Write a function called calculate_area that takes the length and width of a
rectangle as parameters and returns its area.
3. Create a function named sum_numbers that takes a list of numbers as a
parameter and returns their sum.
4. Define a function called is_even that takes an integer as a parameter and
returns True if the number is even, and False otherwise.
5. Write a function called reverse_string that takes a string as a parameter and
returns its reversed version.
6. Create a function named factorial that takes a non-negative integer as a
parameter and returns its factorial.
7. Define a function called celsius_to_fahrenheit that takes a temperature in
Celsius as a parameter and returns its equivalent in Fahrenheit.
8. Write a function called is_prime that takes an integer as a parameter and
returns True if the number is prime, and False otherwise.
9. Create a function named filter_list that takes a list of values and a data type
(e.g., “int”, “str”) as parameters. The function should return a new list
containing only the elements from the original list that match the given data
type.
10. Define a function named calculator that takes two numbers and an
operator (+, -, *, /) as arguments and performs the corresponding arithmetic
operation. Handle division by zero by returning an appropriate message.