CHAPTER 4 PYTHON FUNCTIONS
CHAPTER 4 PYTHON FUNCTIONS
Python functions:
Python functions are reusable code blocks that carry out particular tasks, helping programmers structure their code
and make it easier to read. By preventing duplication, functions make the code more modular and manageable. The
'def' keyword, the function name, and any parameters included in parenthesis define a function. The code to be
performed is contained in the function body, and the 'return' statement allows the function to produce a result.
Example
def add_numbers(a, b):
return a + b
result = add_numbers(3, 5)
print(result)
# Output: 8
The function "add_numbers" accepts two parameters, "a" and "b," adds them, and then outputs the outcome. After
'add_numbers(3, 5)' is called, '8' is returned and printed. These functions are crucial to writing tidy, effective, and
reusable Python code.
In Python, a function is declared using the ‘def’ keyword followed by the function name and parentheses
containing any parameters the function may take. The function declaration is followed by a colon, and the function
body is indented, containing the code to be executed. Optionally, a function can use the return statement to ‘return’
a value to the caller.
Example
def greet(name):
return f"Hello, {name}!"
message = greet("Alice")
print(message)
# Output: Hello, Alice!
In this instance, the function "greet" with one parameter, "name," is declared with the expression "def
greet(name):". A greeting string is returned by the function and printed after that. Python function declarations can
be clear and succinct because of this simple syntax.
1. Built-in Functions
These functions are pre-defined in Python and can be used directly without any further declaration.
Example
# Using the built-in len() function
my_list = [1, 2, 3, 4, 5]
print(len(my_list)) # Output: 5
2. User-defined Functions
These are functions that users create to perform specific tasks.
Example
def add_numbers(a, b):
return a + b
result = add_numbers(3, 5)
print(result) # Output: 8
4. Recursive Functions
These are functions that call themselves within their definition. They help solve problems that can be broken down
into smaller, similar problems.
Example
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) Output: 120
5. Higher-Order Functions
These functions can take other functions as arguments or return them as results. Examples include map(), filter(),
and reduce().
Example
def square(x):
return x * x
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(square, numbers))
print(squared_numbers) Output: [1, 4, 9, 16, 25]
6. Generator Functions
These functions yield values one at a time and can produce a sequence of values over time, using the yield
keyword.
Example
def generate_numbers():
for i in range(1, 6):
yield i
for number in generate_numbers():
print(number) Output: 1 2 3 4 5
7. Recursive Function
This function calls itself to solve a problem that can be broken down into smaller, similar problems.
Example
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) Output: 120
Definition
An input value that a function can use to carry out its operations is provided by parameters, also known as
arguments.
Use
Because parameters can function on various inputs, they make functions more versatile and reusable.
Example
Simple Function with Parameters
This function takes two parameters and returns their sum.
def add_numbers(a, b):
return a + b
result = add_numbers(3, 5)
print(result) Output: 8
1. Positional Arguments
Passed to the function in the order in which they are defined.
Example
def add(a, b):
return a + b
result = add(3, 5)
print(result) Output: 8
2. Keyword Arguments
Passed to the function with the parameter name, making the order irrelevant.
Example
def print_info(name, age):
print(f"Name: {name}, Age: {age}")
print_info(age=30, name="John") Output: Name: John, Age: 30
3. Default Arguments
Parameters with default values are used if no argument is provided.
Example
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() Output: Hello, Guest!
greet("Alice") Output: Hello, Alice!
4. Variable-Length Arguments
Allows functions to accept an arbitrary number of arguments. This uses ‘*args’ for positional arguments and
‘**kwargs’ for keyword arguments.
Example
def sum_all(*args):
return sum(args)
result = sum_all(1, 2, 3, 4, 5)
print(result) # Output: 15
def print_details(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_details(name="Alice", age=30, city="New York")
Output:
name: Alice
age: 30
city: New York
Several argument types are supported by Python functions, giving users flexibility and control over the values that
are supplied to them. The primary categories of Python function arguments are listed below, 1. Default
argument
Definition
Described as an argument that, in the event that a value is not supplied in the function call, takes on a
default value.
Usage
To define optional parameters, use the default arguments.
Example
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() Output: Hello, Guest!
greet("Alice") Output: Hello, Alice
3. Positional arguments
Definition
Positional arguments are arguments passed to the function in a specific order based on their position.
Usage
They are the most straightforward way to pass arguments and are required in the order they are defined.
Example
def add(a, b):
return a + b
result = add(3, 5)
print(result) Output: 8
4. Arbitrary arguments
Definition
Arbitrary arguments allow a function to accept an arbitrary number of positional or keyword arguments.
Usage
Useful for functions that need to handle a variable number of inputs.
Example (Arbitrary Positional Arguments)
def sum_all(*args):
return sum(args)
result = sum_all(1, 2, 3, 4, 5)
print(result) Output: 15
1. Returning a Value
The return statement can be used to ‘return’ a value from a function.
Example
def add(a, b):
return a + b
result = add(3, 5)
print(result) Output: 8
3. Returning a List
A function can return complex data structures like lists.
Example
def get_even_numbers(limit):
evens = []
for num in range(limit):
if num % 2 == 0:
evens.append(num)
return evens
even_numbers = get_even_numbers(10)
print(even_numbers) Output: [0, 2, 4, 6, 8]
4. Returning Early
The return statement can be used to exit a function early.
Example
def check_positive(number):
if number <= 0:
return "Not a positive number"
return "Positive number"
result = check_positive(-5)
print(result) Output: Not a positive number
result = check_positive(10)
print(result) Output: Positive number