Python

Functions in Python

Click for All Topics

Functions in Python

 

What are functions?

Functions are helpful tools in coding. They let us organize our code systematically, making it easier to read and reuse. Imagine them as mini-tasks that do certain jobs. By using functions, we can split our big program into smaller parts that are easier to handle. This is like breaking a big problem into smaller pieces.

Additionally, functions prevent us from repeatedly writing the same code. They function similarly to a set of instructions that only need to be written once but can be applied numerous times. Even better, you can provide the directions with some input and then wait for the finished product to return. Therefore, functions let programmers write clearer code, save time, and share their work with others. They serve as the basic units of code, keeping us organized and enabling us to reuse manuals. As our program expands, this is extremely useful because it makes management and operation simpler and more effective.

Why use functions?

Python functions are useful tools that make coding easier:

  1. Breaking into small pieces: They allow you to divide a large, complex program into smaller components. It is simpler to understand because each section focuses on a particular task.
  1. You can use it Again and Again: You only need to write a function once, but you can use it numerous times. Therefore, you are free from having to write the same material repeatedly.
  1. Simple to Read: Code organization is made easier by functions. It is easy to understand what is going on because each function has a distinct purpose.
  1. Hide the Complex Stuff: You can design functions with names that are clear and easy to understand. They perform complex work like magic in the background.
  1. Identify and fix issues: Each function can be examined separately. You can solve the problem quickly if something goes wrong without having to look at everything.
  1. Easy Teamwork: When working on group projects, tasks ensure that everyone understands how various components join together. It’s similar to following an easy-to-follow recipe.
  1. Changes Are Easy: You don’t have to change everything if you need to make a change. Just like fixing a single item in an item’s case, only fix the portion you need.
  1. Maintain Order: Similar items are grouped together by functions. It’s comparable to keeping your shoes in one drawer and your clothing in another.
  1. Make It Faster: Using functions will speed up the operation of your program. It’s comparable to using shortcuts to cross the finish line more quickly in a game.
  1. Do It Yourself: You can use different data to make functions work. It’s comparable to using the same recipe to make biscuits in many flavors.

In short, functions help you organize, reuse, and simplify your code. This makes it easier to manage and boosts your coding skills.

Note:-

Functions also offer namespace separation. A namespace is like a zone where a name or variable has meaning. When you create a function in Python, it has its own namespace. So, any names or variables you use in the function are only understood within that function. This prevents conflicts with names used in other parts of your code. You can freely use meaningful names without worrying about other functions using the same names. write in more simple and precise points

Different types of functions in Python

There are many types of functions in Python. The following are the different types of functions in Python:

  1. Python Built-In functions
  1. Python User-defined functions
  1. Python Recursion functions
  1. Python Lambda functions

Let’s examine these features in more detail.

Built-in Functions

The built-in or predefined functions are those that have already been defined in python. These functions perform common tasks, such as printing statements using print() and entering data with input(), The function reads a line from the input and creates a string from it.

Some of the Built-in functions are listed here:

print(), input(), all(), any(), range(), int(), str(), etc.

User-defined functions

A user-defined function is a function that is created by the programmer according to their specific needs and requirements. As a programmer, you have the ability to develop and customize your own functions.

Function Definition:

We can create User-defined functions in Python: It Begins with the word def followed by a chosen name for your function. This name should describe what the function does. Use lowercase letters and underscores to separate words. note: write about naming parameter

Example:

def calculate():
    # Function code goes here

This function name will serve as a way to call and use your function later in your code.

Parameters (Optional):

If your function requires specific information to do its job, you can put that information inside parentheses when you define the function. These details you put in the parentheses are like notes that the function will use when you use it later. They help the function know what to work with.

def calculate(a,b): #  information inside parentheses are parameters
    # Function code goes here

Function Body:

Write the instructions that tell the function exactly what to do. These are the steps the function follows when you use it. When you call the function, it carries out these instructions.

				
					def calculate(a,b):
    sum = a+b
    print(sum)
calculate(5,9)

# Output
# 14
# The sum of 9 and 5 is 14
				
			

Return Statement (Optional):

If your function is supposed to give something back after it’s done, you can use the return command. It’s like the function is sending a special message back to the part of the program that asked for its help.

				
					def calculate(a,b):
    sum = a+b
    return sum  # return statement
calculate(10,5)

# Output
# 15
# The sum of 10 and 5 is 15
				
			
Calling the Function:

To use the function, you call it by its name, passing the required arguments inside the parentheses.

				
					def calculate(a,b):
    sum = a+b
    return sum
calculate(10,8) # Calling the function

# Output
# 18
# The sum of 10 and 8 is 18
				
			
Let’s see some examples of simple functions:

Example 1: Calculating the area of a rectangle

				
					def calculate_area(length, width):
    area = length * width
    return area

rectangle_area = calculate_area(4, 5)
print(rectangle_area)

# Output
# 20
				
			

Example 2: Checking if a Number is Even:

				
					def is_even(number):
    if number % 2 == 0:
        return True
    else:
        return False

num = 6
if is_even(num):
    print(f"{num} is even.")
else:
    print(f"{num} is odd.")

# Output
# 6 is even.
				
			
Example 3: Checking Prime Numbers:
				
					def is_prime(number):
    if number <= 1:
        return False
    for i in range(2, int(number ** 0.5) + 1):
        if number % i == 0:
            return False
    return True

num_to_check = 17
if is_prime(num_to_check):
    print(f"{num_to_check} is a prime number.")
else:
    print(f"{num_to_check} is not a prime number.")
    
# Output
# 17 is a prime number.
				
			

Recursion function in Python

Python functions that call themselves within their own definitions are referred to as recursive functions. This method of programming is frequently employed to resolve issues that can be divided into more manageable issues with similar characteristics. Recursive functions give you a more beautiful and logical approach to communicating difficult issues.

Recursion functions are made up of two portions:

  1. (Base Case): Imagine this as the “stop” signal in a game. When the function should stop using recursion and begin providing replies is determined by the condition. Think of a situation where you are counting down and you stop at 1 and declare, “Done!” The default case is 1, where you stop and declare it done. In simple words, the base case is the condition to stop the recursion.
  1. (Recursive case): Imagine you are trying to build a tall building. To build the entire building, we have to build one block or one floor at a time. We keep building one block or one floor at a time. You finish a large task (constructing a tall building) by repeatedly finishing smaller tasks or iterations. Recursive functions work in the same way: they make one or more calls to themselves, bringing the problem closer to the base case. It breaks down the larger problem into smaller subproblems.

Let’s see some examples:

Example 1: Creating a countdown using recursion.

				
					def countdown(n):
    if n == 0:
        print("Blastoff!")
    else:
        print(n)
        countdown(n - 1)

countdown(5)

# Output
# 5
# 4
# 3
# 2
# 1
# Blastoff!
				
			
Example 2: Calculating the sum of the digits of a number using recursion.
				
					def sum_of_digits(n):
    if n < 10:
        return n
    else:
        last_digit = n % 10
        remaining_digits = n // 10
        return last_digit + sum_of_digits(remaining_digits)

result = sum_of_digits(12345)
print(result)

# Output:
# 15 (1 + 2 + 3 + 4 + 5)
				
			

Python Lambda functions

Lambda functions are similar to user-defined functions but without a name. They’re commonly referred to as anonymous functions.

Lambda functions are efficient whenever you want to create a function that will only contain simple expressions. That is, expressions that are usually a single line of a statement. They’re also useful when you want to use the function once.

Let’s see some examples:

Example 1:

				
					def sum(a, b):
    return a + b

# Equivalent lambda function
sum_lambda = lambda a, b: a + b

print(sum(5, 3))
print(sum_lambda(5, 3))

# Output: 8
# Output: 8
				
			
Example 2: lambda function that calculates the square of a number:
				
					square = lambda x: x ** 2

print(square(5))  
print(square(8))

# Output: 25
# Output: 64