Python Functions: Defining Functions 🎯

A function in Python is a reusable block of code that performs a specific task. Functions help reduce redundancy, increase readability, and make code modular.
1️⃣ Defining a Function (Using def Keyword)
🔹 Basic Function Syntax
def function_name():
# Function body (indented)
print("Hello, World!")
# Calling the function
function_name()
# Output: Hello, World!
🔹 Function with Parameters
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # Output: Hello, Alice!
greet("Bob") # Output: Hello, Bob!
🔹 Function with Return Value
def square(number):
return number * number
result = square(5)
print(result) # Output: 25
2️⃣ Function Arguments & Parameters
Python functions can have different types of arguments:
Argument Type Example
Positional Arguments greet("Alice")
Default Arguments greet(name="Guest")
Keyword Arguments greet(name="Bob")
Arbitrary Arguments (*args) sum_all(1, 2, 3, 4)
Arbitrary Keyword Arguments (**kwargs) person_info(name="Alice", age=25)
🔹 Positional & Default Arguments
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Output: Hello, Guest!
greet("Alice") # Output: Hello, Alice!
🔹 Keyword Arguments
def person_info(name, age):
print(f"Name: {name}, Age: {age}")
person_info(age=25, name="Bob")
# Output: Name: Bob, Age: 25
🔹 Arbitrary Arguments (*args)
Used when we don’t know how many arguments will be passed.
def sum_all(*numbers):
return sum(numbers)
print(sum_all(1, 2, 3, 4, 5)) # Output: 15
🔹 Arbitrary Keyword Arguments (**kwargs)
Used when we don’t know how many keyword arguments will be passed.
def display_info(**details):
for key, value in details.items():
print(f"{key}: {value}")
display_info(name="Alice", age=25, city="New York")
# Output:
# name: Alice
# age: 25
# city: New York
3️⃣ Return Statement & Multiple Returns
🔹 Returning a Value
def multiply(x, y):
return x * y
result = multiply(4, 5)
print(result) # Output: 20
🔹 Returning Multiple Values
def get_coordinates():
return 10, 20 # Returns a tuple
x, y = get_coordinates()
print(x, y) # Output: 10 20
4️⃣ Nested Functions & Scope
🔹 Nested Functions
def outer_function():
print("Outer function")
def inner_function():
print("Inner function")
inner_function()
outer_function()
# Output:
# Outer function
# Inner function
🔹 Variable Scope (Local & Global)
global_var = "I am global"
def my_function():
local_var = "I am local"
print(global_var) # ✅ Can access global variable
print(local_var) # ✅ Can access local variable
my_function()
# print(local_var) # ❌ Error: local_var is not accessible outside the function
5️⃣ Lambda (Anonymous) Functions
A lambda function is a short, one-line function without a name.
square = lambda x: x * x
print(square(4)) # Output: 16
6️⃣ When to Use Functions?
✅ When you need code reusability.
✅ When you want better readability.
✅ When you need modularity in your program.
Date: 2025-03-22 00:00:00.000000