Python Functions

Close-up of a computer screen displaying colorful programming code with depth of field.

Functions in Python are a way to organize and reuse code. A function is a block of code that takes input parameters, performs a set of operations, and returns an output (or multiple outputs). Functions can be called multiple times and from different parts of a program.
Defining a function in Python starts with the def keyword, followed by the function name, input parameters (enclosed in parentheses), and a colon. The code inside the function must be indented. The return keyword is used to return the output of the function.
Here is an example:

In this example, the add function takes two input parameters a and b and returns their sum. The function is called by passing two arguments and the result is assigned to the result variable.

Types of functions

In Python programming, there are two types of functions
Built-in functions: Functions that are built into Python, such as print(), len(), and max().
User-defined functions: Functions defined by the user, created using the “def” keyword.
Syntax for User Defined functions
The syntax for defining a user-defined function in Python is as follows:

def function_name(arguments):
 # function body
 # statements
     return [expression]


“def” is a keyword used to define a function.
“function_name” is the name of the function. It should follow the same rules as variable names.
“arguments” are optional parameters that can be passed to the function.
The function body is indented and contains one or more statements.
The “return” statement is used to return a value from the function. The expression after return is optional.

Calling user defined function

To call a user-defined function , use the name of the function followed by parentheses and pass any required arguments within the parentheses.
For example:

Passing Parameter for a user defined function

You can pass parameters to a user-defined function by placing them within the parentheses of the function definition.
For example:

You can also pass multiple parameters to a function:

return statement

The return statement is used in Python to return a value from a function. It exits the function and passes the specified value to the caller.
Example:

Default Parameter

A default parameter in a Python function allows you to specify a default value for a parameter, which will be used if a value for that parameter is not provided when the function is called.
For example:

def greet(name, greeting=“Hello”):
 print(f“{greeting}, {name}”)
greet(“John”) # prints “Hello, John”
greet(“Jane”, “Hi”) # prints “Hi, Jane”

In the above example, the greet function takes two parameters name and greeting. The second parameter greeting has a default value of “Hello”. When the function is called with only one argument, the default value is used. But when it’s called with two arguments, the second argument overwrites
the default value.
Note: f-strings, also known as “formatted string literals”, They allow you to embed expressions within a string by placing an “f” before the string

Command Line Arguments

Command line arguments are arguments passed to a script when executing it from the command line. In Python, the sys module provides access to these arguments through the sys.argv list. The first element of this list, sys.argv[0], is the name of the script itself. The remaining elements are the arguments passed to the script.
The following example shows how to access command line arguments in a Python script:

import sys
print(“Number of arguments:”, len(sys.argv))
print(“Arguments:”, sys.argv)

When running the above script from the command line, you can pass arguments as follows:
script.py arg1 arg2 arg3

Keyword Arguments

Keyword arguments in Python allow you to specify arguments in a function call by matching the argument names in the function definition. This allows you to pass arguments in any order, not just the order specified in the function definition.
For example, let’s say you have a function print_student_info that takes in 3 parameters: name, age,
and gender.
Using keyword arguments, you can call this function as follows:
print_student_info(name=“John Doe”, gender=“Male”, age=30)
This is useful when you have a lot of parameters in a function and want to avoid the confusion of which parameter is assigned to which value.

Recursive Function

A recursive function is a function that calls itself, either directly or indirectly, until a certain condition is met. This allows solving problems by breaking them down into smaller subproblems.
Example:

Direct Recursion Function

Direct recursion is a type of recursion in which a function calls itself directly in its own definition. It’s the simplest form of recursion where a function calls itself until a base condition is met.
Here is an example:

In the above example, factorial function calls itself directly until the base condition n == 1 is met.

Indirect Recursion Function

Indirect recursion is a type of recursion in which multiple functions call each other to solve a problem. In indirect recursion, multiple functions call each other in a circular manner until the base case is reached. For example, function A calls function B, which in turn calls function C, which then calls function A again, and so on. Indirect recursion is used when the problem can be divided into multiple subproblems, each of which is solved by a different function.

Example
An indirect recursion is when two or more functions call each other in a cyclic manner.
Here’s an example of indirect recursion in Python:

def funcA(n):
 if n == 0:
 return
 print(“In funcA”)
 funcB(n-1)
def funcB(n):
 if n == 0:
 return
 print(“In funcB”)
 funcA(n-1)

In this example, funcA calls funcB and funcB calls funcA in a cyclic manner until n reaches 0.

Scope of Variables

The scope of a variable in Python refers to the part of the program where it can be accessed. Variables in Python can have either local or global scope.
Local Variables: Local variables are declared within a function and can only be accessed within that function. They are created and destroyed each time the function is called.
Global Variables: Global variables are declared outside of any function and can be accessed from any part of the program. They are created when the program starts and destroyed when the program ends.
To use a global variable inside a function, you need to use the global keyword to indicate that you want to use the global variable, not a local one with the same name.
Example:

Lifetime of Variables in Function

The lifetime of a variable in a function refers to the duration for which the variable is accessible or exists within the function. A variable defined inside a function has a lifetime that lasts only for the duration of the function call, and is destroyed once the function execution is completed. This is known as the local scope of the variable, which is limited to the function in which it was defined. On the other hand, variables defined outside of a function are known as global variables and have a lifetime that lasts throughout the lifetime of the program, and can be accessed by any function in the program.
Example
In the following example, the variable “x” is declared inside the function “my_func”, its lifetime starts when the function is called and ends when the function returns.

Here, the variable “x” inside the function has a different value from the variable “x” outside the function. This is because each variable has its own lifetime and scope within a function, which means that variables inside the function cannot be accessed outside the function.

To buy Python books click the below links
Python Programming
Python Programming 2E
Handbook of Python Programming

Leave a Comment

Your email address will not be published. Required fields are marked *