Sitemap

Functions in Python

4 min readAug 22, 2024

--

Functions are the core of any programming paradigm that allows a user to divide his code into independent modules, which are in turn reusable in nature. In Python, functions are used to hold some related code together so that the code can be better read, maintained, and debugged. Among other associated concepts, this section will talk of the concept of functions and their uses, types of functions, anonymous functions, global versus local variables, and function overloading versus function overriding.

1. Introduction to Functions
A function in Python is a block of code that performs a certain task. Functions are defined using the keyword def followed by a function name and parentheses (). They also can take inputs, which we call parameters, and return a value output.

Defining a Function
def my_function():
print(“Hello, World!”)
Calling a Function
Once defined, you can execute the function by naming the function along with a pair of parentheses.
my_function() # Output: Hello, World!
2. Uses of Functions
Functions are used to:

Avoid Repetition: By wrapping up the code in functions, you’ll prevent repeating the already-written code again and again.
Improve Readability: Functions split down the lengthy or complex operations into small pieces that can make sense and be readable.
Encourage Reusability: Once a function has been written, it can be used over and over again many times throughout your program.
Facilitate Testing: You can test a function independently, so that debugging and updating your code becomes more simple.
3. Arguments and Parameters
Function Parameters
Parameters are variables inside the parentheses of the function definition. They stand in for values that will be provided to the function.
def greet(name):
print(f”Hello, {name}!”)
Function Arguments
Arguments are the real values that will be passed to a function when it is called. There are several types of argument in Python:

Positional Arguments: This is both the most common and basic type of argument, where the values are, in essence, passed to the function in the order they are defined.
greet(“Alice”) # Output: Hello, Alice!
Keyword Arguments: They allow one to specify arguments by parameter name.
greet(name=”Bob”) # Output: Hello, Bob!
Default Arguments: A default value for the parameters can be set, which gets used when no argument is passed.
def greet(name=”Guest”):
print(f”Hello, {name}!”)

greet() # Output: Hello, Guest!
Arbitrary Arguments (*args): Enables a function to take any number of positional arguments.
def sum_numbers(*numbers):
return sum(numbers)

print(sum_numbers(1, 2, 3)) # Output: 6
Arbitrary Keyword Arguments (**kwargs): Enables a function to take an arbitrary number of keyword arguments.
def print_info(**info):
for key, value in info.items():
print(f”{key}: {value}”)

print_info(name=”Alice”, age=25)
# Output:
# name: Alice
# age: 25
4. Types of Functions
Python functions fall into different types based on their usage and how they are defined.

Built-in Functions: are functions that are native to Python and always available for use. Examples of built-in functions are print(), len(), and range().

User-Defined Functions: These are functions defined by the user using the keyword def.

Lambda Functions (Anonymous Functions): Lambda functions are small functions without a name defined using the lambda keyword. Generally, they are used where they are needed most.
square = lambda x: x * 2
print(square(5)) # Output: 10
Recursive Functions: These are functions calling themselves for problem-solving.
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)

print(factorial(5)) # Output: 120
5. Anonymous Functions
Anonymous functions, also known as lambda functions, are defined with the lambda keyword instead of def. They are generally used for small, simple operations and can often be used as arguments to higher order functions like map(), filter(), and reduce().
double = lambda x: x * 2
print(double(4)) # Output: 8
The lambda functions can have any number of arguments but only one expression. They are super helpful when you would generally have to do a small function for a very short period of time.

Get Seetharam Bethala’s stories in your inbox

Join Medium for free to get updates from this writer.

6. Global Variables v/s Local Variables
The variables which are defined inside a function are known as local variables and the variables that are defined outside a function are known as global variables.

Local Variables: Those defined within a function can be accessed only within the function.
def my_function():
x = 10 # Local variable
print(x)

my_function() # Output: 10
Global Variables: Those defined outside a function can be accessed throughout the program, even in all the functions defined inside the program.
x = 10 # Global variable

def my_function():
print(x)

my_function() # Output: 10
In case, if there is a need to change a global variable in a function, one must use the global keyword.
x = 10

def my_function():
global x
x = 5

my_function()
print(x) # Output: 5
7. Function Overloading vs. Overriding
Function Overloading
Function Overloading: Python does not support function overloading in the way it supports method overloading in C++ or Java. You may define many functions within the same function name by passing a different number of arguments.
def add(a, b=0, c=0):
return a + b + c

print(add(2, 3)) # Output: 5
print(add(2, 3, 4)) # Output: 9
Function Overriding
Function overriding is when the subclass provides an implementation for a method already defined in its superclass. This feature of the Python programming language can be made intensive with the concept of classes inheritance in object-oriented programming.
class Animal:
def sound(self):
return “Some sound”

class Dog(Animal):
def sound(self):
return “Bark”

dog = Dog()
print(dog.makeSound()) # Output: Bark

Summary
Functions enable modular, reusable, and maintainable code, so that forms the important part of Python programs. For effective programming one needs to understand the way functions are defined and used. Use of different forms of arguments, global and local variables, anonymous functions, issue of function overloading and overriding enable the provision of diversified facilities of a programming language; make Python a versatile programming language for any type of applications.

--

--

Seetharam Bethala
Seetharam Bethala

Written by Seetharam Bethala

Python Software Developer | Recent College Graduate Seeking Entry-Level Programming Position | Certified Machine learning engineer