What is a Function in Python?
In Python, a function is a block of reusable code that is
used to perform a single, related action. Functions help make the code
modular, easier to maintain, and reusable. Python has two types of
functions:
-
Built-in functions: These are pre-defined functions
provided by Python (e.g.,
print()
, len()
,
type()
).
-
User-defined functions: These are custom functions
created by programmers using the
def
keyword.
Key Features of Functions
-
Code Reusability: Write once and reuse the function
multiple times.
-
Modularity: Break complex problems into simpler
sub-problems.
-
Improved Readability: Functions help organize code in a
readable manner.
-
Parameterization: Accept input arguments for dynamic
behavior.
-
Return Values: Return processed data or results.
Creating a Function in Python
You can create a function using the def
keyword followed by the
function name, parentheses (which may contain parameters), and a colon. The
function body is indented and contains the statements that define the
function's behavior.
def function_name(parameters):
# Function body
return result # Optional
Example: A Simple Function
def greet(name):
"""This function greets the user by name."""
return f"Hello, {name}!"
# Calling the function
print(greet("Alice")) # Output: Hello, Alice!
Function Parameters and Arguments
In Python, a function is a block of reusable code that is used to perform a single, related action. Functions help make the code modular, easier to maintain, and reusable. Python has two types of functions:
-
Built-in functions: These are pre-defined functions
provided by Python (e.g.,
print()
,len()
,type()
). -
User-defined functions: These are custom functions
created by programmers using the
def
keyword.
- Code Reusability: Write once and reuse the function multiple times.
- Modularity: Break complex problems into simpler sub-problems.
- Improved Readability: Functions help organize code in a readable manner.
- Parameterization: Accept input arguments for dynamic behavior.
- Return Values: Return processed data or results.
def
keyword followed by the
function name, parentheses (which may contain parameters), and a colon. The
function body is indented and contains the statements that define the
function's behavior.
def function_name(parameters):
# Function body
return result # Optional
def greet(name):
"""This function greets the user by name."""
return f"Hello, {name}!"
# Calling the function
print(greet("Alice")) # Output: Hello, Alice!
Functions can accept input values (parameters) to work with. Example: Function with Parameters
def add_numbers(a, b):
"""Returns the sum of two numbers."""
return a + b
# Calling the function with arguments
result = add_numbers(5, 10)
print(result) # Output: 15
Default Parameters
You can assign default values to parameters. If no argument is passed, the default value is used.
def greet(name="Guest"):
"""Greets the user with a default name if no name is provided."""
return f"Hello, {name}!"
print(greet()) # Output: Hello, Guest!
print(greet("Bob")) # Output: Hello, Bob!
Return Statement
A function can send data back to the caller using the return statement.
def multiply(a, b):
"""Multiplies two numbers and returns the result."""
return a * b
product = multiply(4, 5)
print(product) # Output: 20
Variable Scope: Local vs Global
Variables inside a function are local by default and cannot be accessed outside the function.
def example_function():
local_var = "I am local"
return local_var
# print(local_var) # This will raise a NameError
Global variables can be accessed inside the function if declared as global.
global_var = "I am global"
def example_function():
global global_var
global_var = "Modified globally"
return global_var
print(example_function()) # Output: Modified globally
Built-in Functions vs User-defined Functions
Built-in Function Example:
numbers = [1, 2, 3, 4]
print(len(numbers)) # Output: 4
User-defined Function Example:
def square(n):
"""Returns the square of a number."""
return n ** 2
print(square(5)) # Output: 25
Anonymous Functions (Lambda Functions)
Python allows you to create small, one-line functions using the lambda keyword.
square = lambda x: x ** 2
print(square(4)) # Output: 16
add = lambda a, b: a + b
print(add(3, 7)) # Output: 10
Recursive Functions
A function that calls itself is called a recursive function.
Example: Factorial Calculation
def factorial(n):
"""Calculates the factorial of a number using recursion."""
if n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
Practical Examples of Functions
def is_even(number):
"""Returns True if the number is even, else False."""
return number % 2 == 0
print(is_even(10)) # Output: True
print(is_even(7)) # Output: False
2. Generate a List of Squares:
def generate_squares(n):
"""Returns a list of squares of numbers from 1 to n."""
return [x ** 2 for x in range(1, n + 1)]
print(generate_squares(5)) # Output: [1, 4, 9, 16, 25]
Comments
Post a Comment