Methods and Functions

Python Functions (def): Definition with Examples

Python combines the features of aspect-oriented programming and object-oriented programming. It borrows a lot of its features from object-oriented programming languages. However, it is not an OOP strictly. It is an intuitive and high-level programming language. We can see that Python is influenced by Ruby, JavaScript, Groovy, and Go. As you study Python more and more, you will realize that everything in Python is an object. It promotes the concepts of functions where each function performs a particular task. Let us learn more about python function. 

What is a function in Python?

A function is one of the most significant parts of Python. It is a block of code that the programmers can reuse. One of the primary advantages of Python function is that it can be called any time if they are defined. Functions are the basic building blocks of a Python program. There is no restriction on the number of times you can call a function in Python. Thus, the modularity and segmentation of the program improve. The advantages of using functions in a program are-

  • Using functions promotes the reusability of the code. Thus, the programmer does not have to spend time or effort on writing the same piece of code over and over again. 
  • A Python function can be called multiple times. Additionally, you can call it from anywhere in the program.
  • Tracking large programs becomes convenient if it is divided into smaller modules. Thus, functions allow modularity.
  • Python allows programmers to create user-defined functions. Thus, it is easy to modify a function as per the requirements. 

Syntax of a function to sum two numbers:

                    

# Defining the function  

def sum_numbers():  

    a = 1  

    b = 2  

    c = a+b  

    return c  

# calling sum_numbers() function in print statement  

print("The sum of the two numbers is:",sum()) 

The above programs can sum up two numbers and return their sum. Print() is an in-built Python function that is used to print the sum.

Docstrings

Docstrings are the strings in the Python function that appear after the function header. It could also be present after the definition of a class or a module. Docstrings could be single-line or multi-line.

Example:

                    

def add_3(n):

    '''Takes in a number n, returns the sum after adding 3 to n'''

    return n+2

Here, the string “Takes in a number n, returns the sum after adding 3 to n” with a triple quotation is known as the docstring. It appears right after the function definition and gives us an idea of what the function is meant to do. 

There is a slight difference between Python comments and Python docstrings. The comments help a programmer to understand the intention with which the program was written. We can use “#” to write a single-line comment in Python. On the other hand, docstrings are written after the function definition.

The return statement in Python

The return statement is a statement that programmers can use within a Python function to send the result of the function back to the calling module. It is done by writing the “return” keyword followed by the value that it has to return. It is an optional statement.

Syntax: 

                    

# Defining the function  

def multiply_numbers():  

    a = 1  

    b = 2  

    c = a * b  

    return c  

# calling multiply_numbers() function in print statement  

print("The product of the two numbers is:",multiply_numbers()) 

Output: 

                    

The product of the two numbers is: 2

In the above program, the return statement is used to return the product of the two numbers.

Example of the use of comments in Python:

                    

# Program to print "I love programming"

print("I love programming") 

Working of a Python function 

The working of a function refers to calling the function that the programmer wrote either through a function or through the Python prompt. An example of a function calling another function can be seen in nested Python Functions.

Scope and Lifetime of variables

In Python, the scope of a variable refers to the duration and the part of the code for which the variable can be accessed. Local variables are the variables that are accessible within a particular block of code (a specific method). They will not be accessible outside the method.

Example:

                    

def function():

a='Local_a'

print(a)

func1() # calling func1()

Output: 

On the other hand, global variables are defined in the main function and will be available throughout the lifetime of the program.

Example:

                    

a = 'Global_a'

def func1():

print(x) # Calling variable ‘a’ inside func1()

func1()

print(x) # Calling variable ‘a’ outside func1()

Output: 

The variable will be accessible throughout the program as it is a global variable.

Types of functions in Python

There are three types of functions in Python-

  • In-built functions: These are the in-built functions that Python provides the programmers. Some examples of in-built Python functions are print() and min(). The print() function is used to print results, while min() is used to find the minimum value between the arguments 

Syntax: 

                    

def test_function():

  print("Hello! What is your name?")

Output:

  • User-defined functions: A function that the programmer can define by himself is known as a user-defined function. It provides flexibility to the programmer as he can modify it as per his requirements. Thus, the programmer can reuse pieces of code that he would not have been able to use otherwise.

Syntax:

                    

def multiply_num(a,b):

   product = a * b

   return product



n1 = 3

n2 = 4



print("The product is", multiply_num(n1, n2))

Output:

  • Anonymous functions: These functions do not use the “def” keyword. Hence, they are also known as lambda functions.

Q & A on Python Functions (def): Definition with Examples

1. How do you define a function in Python?

Answer: It is pretty simple to define a function in Python. The following points need to be kept in mind while defining a Python function:

  1. Keyword “def”: In Python, you need to use the keyword “def” to specify the function.
  2. Function name followed by parenthesis “()”: After the keyword “def”, you need to write the name of the function. The naming convention rules for naming it are the same as rules for Python identifiers. A good practice is to name the function keeping in mind the task it is supposed to do.
  3. Input parameters: The arguments or the input parameters have to be mentioned within the parenthesis following the function name.
  4. A colon after the parenthesis: A colon will be following the parenthesis where arguments are entered. It marks the end of the function header. The colon precedes the code block and is indented. 
  5. Docstring: It is an optional section that documents what the role of the function is. It enhances readability if a user looks at his code after a long duration.
  6. Function Body: It comprises one or more Python statements. Essentially, these are valid statements that have the same indentation.
  7. Return statement: It is an optional statement. The return keyword can be used by the Python function to return a value.

Sample syntax of a Python function

                    

def understand_func(name):

    """

    The docstring section can tell information about the function.

    """

    print("Hello, " + name + ". Hope you are doing fine!")

2. What is a function in Python with an example?

Answer: A Python function refers to a block of code that can be reused to perform the same task. Functions allow breaking your program into modules. A function runs only after you call it. You can pass parameters and arguments in the function. A few examples are-

Syntax: 

                    

def test_function():

  print("Hello! I hope you are doing fine")

Output:

                    

Hello! I hope you are doing fine

Syntax:

                    

def my_function(firstname):

  print(fname + " Weasley")



my_function("Fred")

my_function("Ron")

my_function("Ginny")

Output:

                    

Fred Weasley

Ron Weasley

Ginny Weasley

Here the argument that is being passed as an argument in the function is being concatenated with the string “Weasley”.

3. What is the function of == in Python?

Answer: The “==” operator is known as the equality operator. The operator will return “true” if both the operands are equal. However, it should not be confused with the “=” operator or the “is” operator. “=” works as an assignment operator. It assigns values to the variables. On the other hand, the “is” operator in Python verifies whether the two variables point to the same object in the memory. In general, programmers use “==” and “!=” operators to compare values.

Suppose, x=1

y=2

z=2

(x==y) will return false as both are assigned different values. (y==z) will return true as both are assigned the same values.

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

avatar
  Subscribe  
Notify of

Customize your course in 30 seconds

Which class are you in?
No thanks.