Course Content
Python Indentation, Comments and Variables
0/2
Object Oriented Programming in Python
0/1
Exception Handling in Python
0/1
Sending emails with Python
0/1
Unit test in python programming
0/1
Python programming (zero to advance!!!)
About Lesson

PYTHON FUNCTIONS

Functions in Python are blocks of reusable code that perform a specific task. They allow you to break down your program into smaller, manageable pieces, making your code more organized, readable, and reusable. Here are some key points about Python functions:

 

CREATE FUNCTIONS IN PYTHON
You create a function using the `def` keyword followed by the function name and parentheses containing any parameters the function accepts. The function body is indented below the function definition.

Syntax:
“`python
def function_name():
     # Function body
     # Perform the desired task
     pass # Placeholder for function body
“`

Example:
“`python
def greet():
        “””Print a simple greeting.”””
        print(“Hello, welcome to Python functions!”)

# Call the function
greet()
“`

 

RETURN STATEMENTS
In Python, the `return` statement is used to exit a function and return a value back to the caller. It allows functions to send data back to the caller so that it can be used further in the program.

Here’s the basic syntax of the `return` statement:

“`python
def function_name(arguments):
           # Function body
          # Perform tasks
          return value # or multiple values separated by commas
“`

Example:

Assuming there is a customer that you – as a developer – should create a calculator that has the following functions: addition, substraction, multiplication and division.

The following code example illustrate the ability of Python functions to help (1) re-use already written code, and (2) breakdown or simplify tasks into smaller actionable pieces.

“`python
def addition2():
        c = str(a + b)
        return c

def substraction2():
  c = str(a – b)
  return c

def multiplication2():
        c = str(a * b)
        return c

def division2():
       c = str(a / b)
       return c
 
 
# task: develop a calculator software … it must be able to perform the following: add, sub, div and mult

a = int(input(“Enter the first value”))
b = int(input(“Enter the second value”))
arithment_operation = input(“Tell us what you wish to do with the numbers”)    # a for addition, s=substraction m=multiplication d=division

if arithment_operation == “a”:
        print(“a + b = ” + addition2())
elif arithment_operation == “s”:
       print(“a – b = ” + substraction2())
elif arithment_operation == “m”:
       print(“a * b = ” + multiplication2())
elif arithment_operation == “d”:
       print(“a / b = ” + division2())
else:
      print(“Not recognised!!!”)
“`
 

“`python
def add_numbers(num1, num2):
       “””Add two numbers and return the result.”””
       return num1 + num2

# Call the function and store the result
result = add_numbers(5, 3)
print(“Result of addition:”, result)

Python functions can return different types of values based on the programmer’s requirements:

1. Function Returning Nothing (None):

In Python, if a function doesn’t explicitly return any value, it implicitly returns `None`.

“`python
def greet():
      print(“Hello, World!”)

      result = greet()
      print(result) # Output: None
“`

Here, the function `greet()` prints a greeting message but doesn’t return any value explicitly. Hence, when we assign the result of `greet()` to a variable, it contains `None`.

2. Function Returning a Single Value:

A function can return a single value using the `return` statement.

“`python
def add(a, b):
     return a + b

result = add(5, 3)
print(result) # Output: 8
“`

In this example, the function `add()` returns the sum of its two arguments `a` and `b`.

3. Function Returning Multiple Values:

Python functions can return multiple values as a tuple.

“`python
def operate(a, b):
      return a + b, a – b, a * b

result = operate(5, 3)
print(result) # Output: (8, 2, 15)
“`

 

Let’s take the example further, this time we get the values of the variables from users by making use of input() function in Python.

def operate_and_return_all():
       return a + b, a – b, a * b, 3*a, a/b
 
a = int(input(“Enter the first value”))
b = int(input(“Enter the second value”))

print(operate_and_return_all())

 

 

The function `operate()` returns the sum, difference, and product of its two arguments as a tuple. We can then unpack the tuple into separate variables if needed.

These examples demonstrate how Python functions can return nothing, a single value, or multiple values based on the requirements of the program.

The `return` statement is essential for functions that need to produce output or calculate results that need to be used elsewhere in the program. It allows for modular and reusable code by encapsulating logic and providing a way to pass data between different parts of the program.

 

PARAMETERS AND ARGUMENTS

In Python, parameters and arguments are often used interchangeably, but they have slightly different meanings:

1. Parameters:

Parameters are the variables listed inside the parentheses in the function definition. They represent the data that a function expects to receive when it is called. Parameters act as placeholders for the actual values (arguments) that will be passed into the function.

“`python
def greet(name):
       print(f”Hello, {name}!”)

# ‘name’ is a parameter
“`

2. Arguments:

Arguments are the actual values that are passed to a function when it is called. They correspond to the parameters defined in the function declaration. When a function is called, the arguments are assigned to the parameters based on their positions.

“`python
# ‘John’ is an argument
greet(‘John’)
“`

In the above example, `name` is a parameter of the `greet()` function, and `’John’` is an argument passed to the function when it is called.

Python supports several types of parameters:

– Positional parameters: These parameters are assigned values based on their positions in the function call.

“`python
def greet(name, message):
       print(f”{message}, {name}!”)

greet(‘John’, ‘Hello’) # ‘John’ is assigned to ‘name’, ‘Hello’ is assigned to ‘message’
“`

– Keyword parameters: These parameters are explicitly named in the function call, and their order can be different from the order in the function definition.

“`python
greet(message=’Hello’, name=’John’) # Order of arguments doesn’t matter
“`

– Default parameters: These parameters have default values specified in the function definition. If an argument is not provided for a default parameter, the default value is used.

“`python
def greet(name=’Guest’):
     print(f”Hello, {name}!”)

greet() # Output: Hello, Guest
“`

– Variable-length parameters: These parameters allow a function to accept any number of arguments. They are defined using `*args` (for positional arguments) or `kwargs` (for keyword arguments).

Variable-length parameters in Python allow functions to accept any number of arguments.
They are defined using `*args` for positional arguments or `kwargs` for keyword arguments.

a. Variable-length positional parameters (`*args`):

“`python
def average(*args):
       return sum(args) / len(args)

# Call the function with different numbers of arguments
print(average(1, 2, 3, 4, 5)) # Output: 3.0
print(average(10, 20, 30)) # Output: 20.0
print(average(2, 4, 6, 8, 10, 12, 14)) # Output: 8.0
“`

In this example, the `average()` function can accept any number of arguments. Inside the function, `args` is a tuple containing all the positional arguments passed to the function. We can then perform operations on these arguments.

In the following examples we demonstrate the use of variable-length positional parameters (`*args`) with strings in Python:

i. Concatenating Strings:

“`python
def concatenate_strings(*args):
       return ‘ ‘.join(args)

result = concatenate_strings(‘Hello’, ‘world’, ‘from’, ‘Python!’)
print(result) # Output: Hello world from Python!
“`

In this example, the `concatenate_strings()` function accepts any number of string arguments and joins them using a space `’ ‘` as a separator.

ii. Formatting Strings:

“`python
def format_strings(*args):
       return ‘, ‘.join(args)

result = format_strings(‘apple’, ‘banana’, ‘orange’)
print(f’Fruits: {result}’) # Output: Fruits: apple, banana, orange
“`

In this case, the `format_strings()` function accepts variable string arguments and joins them using a comma and space as separators.

These examples showcase how variable-length positional parameters (`*args`) can be effectively used with strings in Python functions, allowing flexibility in handling varying numbers of string arguments.

 

b. Variable-length keyword parameters (`kwargs`):

“`python
def greet(kwargs):
      for key, value in kwargs.items():
           print(f”{key}: {value}”)

# Call the function with different keyword arguments
greet(name=’John’, age=30, city=’New York’)
“`

In this example, the `greet()` function can accept any number of keyword arguments. Inside the function, `kwargs` is a dictionary containing all the keyword arguments passed to the function. We can then iterate over this dictionary and access both the keys and values.

Certainly! Here are examples of using variable-length keyword parameters (`kwargs`) with different data types:

1. Dictionary Concatenation:

“`python
def merge_dicts(kwargs):
       merged_dict = {}
       for key, value in kwargs.items():
             merged_dict[key] = value
       return merged_dict

result = merge_dicts(first_name=’John’, last_name=’Doe’, age=30)
print(result) # Output: {‘first_name’: ‘John’, ‘last_name’: ‘Doe’, ‘age’: 30}
“`

In this example, the `merge_dicts()` function accepts variable keyword arguments and merges them into a single dictionary.

2. Displaying Information:

“`python
def display_info(kwargs):
         for key, value in kwargs.items():
               print(f”{key}: {value}”)

display_info(name=’Alice’, city=’New York’, profession=’Engineer’)
“`

This function takes keyword arguments representing various information and prints each key-value pair.

3. Handling Mixed Data Types:

“`python
def process_data(kwargs):
      for key, value in kwargs.items():
            print(f”{key}: {value} ({type(value)})”)

process_data(name=’John’, age=30, height=5.11, employed=True)
“`

Here, the `process_data()` function accepts keyword arguments of mixed data types and displays each key-value pair along with its data type.

These examples illustrate how variable-length keyword parameters (`kwargs`) can be utilized to handle different data types and perform various operations within Python functions.

Variable-length parameters are useful when you want to create flexible functions that can handle different numbers of arguments or keyword arguments without needing to define them explicitly in the function signature.

 

Understanding the distinction between parameters and arguments is important for writing clear and readable code in Python.

Functions are a fundamental concept in Python programming and are used extensively to structure code, promote reusability, and encapsulate logic.

Join the conversation