Python Functions

What is a Function?

A function stands as a fundamental concept in programming, representing self-contained modules of code that fulfill specific tasks. Functionality-wise, it's akin to a mathematical concept grouping operations into a coherent identity, simplifying complex expressions. Functions are employed to compartmentalize different program functionalities, enabling their combination for intricate tasks, with most programming languages offering pre-existing functions stored in libraries. This approach minimizes repetition, streamlines code, enhances usability, and facilitates maintenance. Every function involves input and output, with the function's instructions dictating how output is generated from input. Custom functions can also be developed for specialized tasks.

Python Functions

To define a function, the "def" keyword is employed, followed by the function's name and a pair of parentheses encompassing any parameters the function may require, terminated with a colon. Subsequently, a block of statements specific to the function follows. Functions have the capability to return a value to the caller, facilitated by the "return" keyword.

def function-name(Parameter list): statements return [expression]
example
def sayHello(); print("Hello World!!")

The function is now completely defined, yet executing the program at this juncture will yield no outcome, as the function has not been invoked. Therefore, outside the function's definition block, the function is called using sayHello().

example
def sayHello(); print("Hello World!!") sayHello() # call the function here
output
Hello World!!

Python Function Parameters

A parameter is a variable integrated into a method's signature, designated within the parentheses of the function's definition and separated by commas. When calling the function, the values are provided in a similar manner.

example
def findSum(x,y): z=x+y print("Sum of numers are :" ,z) findSum(10,20) findSum(100,50) findSum(4,2)
output
Sum of numers are : 30 Sum of numers are : 150 Sum of numers are : 6
example
def dispStatus(name,age): print("Name is :" ,name) print("Age is :" ,age) dispStatus("John",35) dispStatus("Doe",50)
output
Name is : John Age is : 35 Name is : Doe Age is : 50

Default Argument Values

Python allows the assignment of default values to function parameters, a feature useful when users opt not to provide values. This is achieved through default argument values, assigned using the (=) operator.

example
def dispStatus(name,age=25): print("Name is :" ,name) print("Age is :" ,age) dispStatus("John") dispStatus("Doe")
output
Name is : John Age is : 25 Name is : Doe Age is : 25

The primary benefit of default arguments lies in the ability to assign values exclusively to chosen parameters while relying on default argument values for the rest. This facilitates more flexible and concise function calls.

example
def dispStatus(name,age=25): print("Name is :" ,name) print("Age is :" ,age) dispStatus("John") dispStatus("Doe",34) dispStatus("Doe",age=50)
output
Name is : John Age is : 25 Name is : Doe Age is : 34 Name is : Doe Age is : 50

Variable number of arguments

Occasionally, programs may require defining a function capable of accommodating an arbitrary number of parameters, denoted as a variable number of arguments, achieved through the use of asterisks (*). This mechanism proves invaluable when the exact count of arguments to be passed to a function remains uncertain.

example
import math def dispSquare(*varArgs): #iterate through all the items for num in varArgs: print("The square of the number is :" , num*num ) dispSquare(2,4,6,8,10)
output
The square of the number is : 4 The square of the number is : 16 The square of the number is : 36 The square of the number is : 64 The square of the number is : 100

Returning a Value

Beyond the capability to pass parameter values into a function, functions can also yield values. The "return" statement facilitates this process, allowing a function to conclude and return a value. Following the "return" keyword is an expression that undergoes evaluation before being returned by the function.

example
def findSum(x,y): return x+y print(findSum(10,20)) print(findSum(100,50)) print(findSum(4,2))
output
30 150 6

Inner Functions

The primary advantage of inner functions lies in their encapsulation, which shields them from external influences, effectively concealing them from the global scope and any external interference.

example
def calc(x,y): def findSum(x,y): return x+y sum = findSum(x,y) print("Sum of ", x, " + ", y, " is ", sum) calc(10,20)
output
Sum of 10 + 20 is 30

If you try calling the findSum(10.20) function:

output
Traceback (most recent call last): File "sample.py", line 8, in < module > findSum(10,20) NameError: name 'findSum' is not defined

Assign functions to variables

When you assign a function to a variable you don't use the () but simply the name of the function.

example
def findSum(x,y): return x+y f1 = findSum(10,20) print(f1) f1 = findSum(40,20) print(f1)
output
30 60

Functions as parameters

There are situations we have to pass Functions as parameters to other functions.

example
def sayHello(func): return "Hello " + func def sayName(name): return name print (sayHello(sayName("John")))
output
Hello John

Conclusion

Python functions serve as self-contained code modules that perform specific tasks, enhancing code organization and reusability. They can accept parameters, return values, and even handle a variable number of arguments. With the ability to encapsulate logic and promote code modularity, functions play a key role in structuring effective and maintainable programs.