Functions in Python
Presented By:
Mr. Kiran Kishor Awale
Introduction to Functions
• A function is a reusable block of code designed to perform a
specific task.
• Functions improve code organization and reduce redundancy.
• Types of functions:
1. Built-in functions (e.g., print(), len(), type())
2. User-defined functions (created by the programmer)
Defining and Calling Functions
• ### Syntax:
def function_name():
# Function body
print('Hello from function!')
# Calling the function
function_name()
• Functions must be defined before they are called.
• Parentheses `()` are required to invoke a function.
Function Parameters and
Arguments
• Parameters are placeholders in the function definition.
• Arguments are actual values passed to a function when it is
called.
Example: (simple_function.py)
Parameter
def greet(name): #Function Definition
print('Hello, ' + name + '!')
greet('FYA') # Output: Hello, FYA! #Function Call
Argument
Parameter Passing in Python
• Parameters allow functions to accept input.
• Python supports different ways to pass arguments:
Positional Arguments
Keyword Arguments
Default Parameters
Variable-Length Arguments
1. Positional Arguments
• Arguments are passed based on their position.
• Example:
def greet(name, age):
print(f'Hello {name}, you are {age} years old!')
greet('Alice', 25)
2. Keyword Arguments
• Arguments are passed using parameter names.
• Example:
def greet(name, age):
print(f'Hello {name}, you are {age} years old!')
greet(age=36, name='Sudhir')
3. Default Parameters
• Default values are assigned if no argument is provided.
• Example:
def greet(name='Guest'):
print(f'Hello, {name}!')
greet() # Output: Hello, Guest!
greet('Kiran') # Output: Hello, Kiran!
4. Variable-Length Arguments
(*args & **kwargs)
• *args` handles multiple positional arguments (stored as a
tuple).
• `**kwargs` handles multiple keyword arguments (stored as a
dictionary).
Understanding *args (Positional
Arguments)
• `*args` allows functions to accept any number of arguments.
• It collects all arguments into a tuple.
• Used when we don’t know how many arguments will be
passed.
• Example:
def add_numbers(*numbers):
return sum(numbers)
print(add_numbers(5, 10, 15))
Understanding **kwargs (Keyword
Arguments)
• `**kwargs` allows functions to accept multiple named
arguments.
• It collects all keyword arguments into a dictionary.
• Used when we need dynamic named parameters.
• Example:
def student_details(**details):
for key, value in [Link]():
print(f'{key}: {value}')
student_details(name='Tony', age=62, course='Python')
Using *args and **kwargs Together
• - Both `*args` and `**kwargs` can be used in the same
function.
• - `*args` must be placed before `**kwargs`.
• Example:
def display_info(*args, **kwargs):
print('Positional:', args)
print('Keyword:', kwargs)
display_info(1, 2, name='Tony', age=62)
Real-Life Example: E-commerce
System
• Imagine a shopping cart where users add items with details.
• Example:
def shopping_cart(customer, *items, **options):
print(f'Customer: {customer}')
print('Items:', items)
for key, value in [Link]():
print(f'{key}: {value}')
shopping_cart('Nikita', 'Laptop', 'Mouse', discount=10, shipping='Express')
Returning Values from Functions
• Functions can return values using the `return` statement.
• The returned value can be stored in a variable or used in
expressions.
Example:
def square(num):
return num * num
result = square(5)
print(result) # Output: 25
Returning Multiple Values
• Python allows returning multiple values using tuples.
• Example:
def get_coordinates():
return (10, 20)
x, y = get_coordinates()
print(x, y) # Output: 10 20
Best Practices for Return &
Parameters
• Use meaningful function and parameter
names.
• Keep functions focused on a single task.
• Use default parameters where applicable.
• Avoid excessive use of global variables.
• Document functions using docstrings.
Local vs Global Variables
• Local variables exist only inside a function.
• Global variables exist outside functions and can be accessed
globally.
Example:
x = 10 # Global variable
def my_function():
y = 5 # Local variable
print(y)
my_function()
print(x)
Using Local and Global Variables
➢ You can use the same variable name in both local and global
scope.
➢ Inside a function, the local variable takes precedence.
➢ To modify a global variable inside a function, use global.
➢ To modify an enclosing function's variable in a nested function,
use nonlocal.
Thank You!!!!