Functions allow code reuse by defining blocks that can be executed multiple times. Python also supports lambda expressions, which provide a quick way to define simple functions.
A function is defined using the def keyword.
def function_name(parameters):
# Function body
return value # Optionaldef greet():
print("Hello, World!")
greet()Hello, World!def greet(name):
print(f"Hello, {name}!")
greet("Aayush")Hello, Aayush!def add(a, b):
return a + b
result = add(5, 3)
print(result)8Default values can be assigned to function parameters.
def power(base, exponent=2):
return base ** exponent
print(power(3)) # Uses default exponent (2)
print(power(3, 3)) # Uses provided exponent (3)9
27kwargs)Allows passing arguments using key-value pairs.
def person_info(name, age):
print(f"Name: {name}, Age: {age}")
person_info(age=25, name="Ankit") # Order does not matterName: Ankit, Age: 25**kwargs)Allows passing multiple named arguments.
def print_info(**info):
for key, value in info.items():
print(f"{key}: {value}")
print_info(name="Ankit", age=30, city="Delhi")name: Ankit
age: 30
city: DelhiA function can return a value using return.
def multiply(a, b):
return a * b
result = multiply(4, 5)
print(result)20A lambda function is a one-line function without a name.
lambda arguments: expressionsquare = lambda x: x ** 2
print(square(5))25map()numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, numbers))
print(squared)[1, 4, 9, 16]filter()numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)[2, 4, 6]A function inside another function.
def outer():
def inner():
print("Inside inner function")
inner()
outer()Inside inner functionx = 10 # Global variable
def show():
x = 5 # Local variable
print("Inside function:", x)
show()
print("Outside function:", x)Inside function: 5
Outside function: 10Functions allow code reuse and modularity.
Functions can have parameters, return values, and default arguments.
Lambda expressions provide a compact way to define functions.map() and filter() work well with lambda functions.**kwargs allows handling multiple keyword arguments.
Sign in to join the discussion and post comments.
Sign inPython for Web Development
Python for Web Development is a comprehensive tutorial series covering the fundamentals of building web applications using Flask and Django. From setting up a project to working with databases, authentication, REST APIs, and deployment on cloud platforms, this series provides a solid foundation for developing secure and scalable web applications.
Object-Oriented Programming (OOP) in Python
Learn the fundamentals of Object-Oriented Programming (OOP) in Python, including classes, objects, inheritance, polymorphism, encapsulation, and more. Understand how OOP enhances code reusability, scalability, and organization.