Python Functions
Python functions are one of the core concepts of the language. They allow you to bundle a set of instructions and call them whenever you need. This helps in breaking down complex tasks into smaller, manageable pieces, improving code readability, reusability, and organization.
In this blog post, we will discuss the types of functions in Python, how to define and call them, and explore some examples to demonstrate their usage.
In Python, a function is a block of reusable code that performs a specific task. Functions help in avoiding repetition and make the code more modular.
To define a function in Python, we use the def
keyword, followed by the function name and parentheses. Any code inside the function should be indented.
def function_name(parameters):
# code block
return result
Python comes with many built-in functions that are ready to use. Some of the most commonly used ones include print()
, len()
, type()
, input()
, and more.
# Using the built-in print function
print("Hello, World!")
These are functions defined by the user to perform specific tasks.
# Defining a user-defined function
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
This function takes a parameter name
and prints a greeting.
Functions in Python can accept parameters (also called arguments). These are values that are passed to the function when it is called.
def add_numbers(a, b):
return a + b
result = add_numbers(5, 3) # 5 and 3 are passed as positional arguments
print(result)
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
greet(age=25, name="Bob")
def greet(name, age=30):
print(f"Hello {name}, you are {age} years old.")
greet("Alice") # age will default to 30
The return
statement is used to send the result back to the caller. If there is no return
statement, the function returns None
by default.
def square(number):
return number ** 2
result = square(4)
print(result) # Output: 16
Lambda functions are small anonymous functions that can take any number of arguments but only one expression. They are useful for short, simple functions.
lambda arguments: expression
Example:
# Using a lambda function to add two numbers
add = lambda x, y: x + y
print(add(2, 3)) # Output: 5
Recursion occurs when a function calls itself. It is useful for problems that can be divided into smaller sub-problems.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
result = factorial(5)
print(result) # Output: 120
In Python, the scope refers to the region in which a variable is accessible. Variables declared inside a function are local to that function and cannot be accessed outside it.
global_var = 10 # Global variable
def display():
local_var = 5 # Local variable
print("Local Variable:", local_var)
print("Global Variable:", global_var)
display()