×

How to Call a Function in Python

How To Call a Function in Python

Functions are the well-defined and structured piece of code that is used to implement specific functionality. Calling a function in python is the best way to reduce the size of code. Whenever we talk about using 'functions' in a code, we have to mention the following three things-

  • Function declaration
  • Function definition
  • Function calling

The reason behind why python is the most commonly used language among developers is its readability and how it simplifies complex programs.

So, when we are using functions in our python program, we just need to define and call it.

Let’s look at an example where we will see how functions are called in python.

 def add(a,b):    #function to add two numbers
     return a+b
 x=10
 y=20
 print(add(x,y)) #function call 

The above example shows how we can add two numbers in Python using functions.

The way to define functions in Python is-

def function_name(parameters):

                  return _______

  1. The keyword ‘def’ is used to define a function in Python
  2. After that, we must define the name of our function.
  3. And then specify the number of parameters involved in our function.
  4. Finally, we will write the expression required for desired result or output preceded with the keyword return.

In the example given above, we have made a function that adds two numbers.

We have defined the function using the 'def' keyword, named our function like add, and specified the parameters a and b that will hold the values for further computation.

Since the function 'add' will give us the addition of two numbers as the output, we will write this statement as return a+b.

Now the next step is to take the values from the user to check how our function works-

The values from the user can be taken in two ways-

  1. Assign the variables a value like-
 x=10
 y=20 
  • Ask the user to input the values of these variables using the ‘input’ function like-
 x=int(input(“Enter value of x: ”))
 y=int(input(“Enter value of y: ”)) 

Once we receive the values for our variables, we can call the function 'add' and display the result using the print function.

When the function is invoked, the control of the program passes to the called function, executes the statements/computes the values (in case of a mathematical expression) and then the control again comes back to the calling function.

Let’s look at some points we must keep in mind while declaring a function-

  1. The function name is given so that it can be identified uniquely in a function.
  2. Make sure you place a colon outside the parentheses in which you have specified the parameters.
  3. If your function is meant to simply print a statement or a set of statements, then you need not write anything in the parentheses.

For example-

 def message():
     print("Hello All")
 message()
 message() 
  • The indentation should be proper in the code block.
  • The number of arguments at the time of calling the function must be the same as specified in the function definition.
  • The return statement should be present within the function.
  • Once a value is returned from a function, it instantly marks the exit of that function.

LAMBDA FUNCTIONS

Lambda or anonymous functions are the functions that are not declared with the keyword ‘def’ and are a one-line version of our function.

They are created with the help of keyword lambda and contain a single line.

Let’s understand this with the help of an example-

 add=lambda a,b: a+b
 print(“Addition =”,add(2,4)) 

In the above example, the lambda function gives the sum of two parameters a and b, the output is evaluated with the help of the expression a+b and then the result is displayed.

Some Properties of Lambda Functions-

  1. There is no need to give a function name in this case.
  2. It returns a single value which is obtained by evaluating an expression.
  3. There is no need to explicitly mention the return statement.
  4. Since they are a one-line version, they cannot have multiple statements or expressions.
  5. They can’t access global variables.

Let's have a glance at some examples of functions-

  1. Program to add two numbers using functions
 def sum(x,y):
     res=x+y
     print("Sum of {} and {} is {}".format(x,y,res))
 x=int(input("Enter the value of x: "))
 y=int(input("Enter the value of y: "))
 sum(x,y)   
Call a Function in Python
  • Program to find cube of a number
 cube=lambda x:x*x*x
 print("Cube is {}".format(cube(9))) 
Call a Function in Python

Related Topics

Create Table Using PyQt5 in Python

PyQt5: PyQt5 is one of several solutions that Python offers for creating GUI applications. Cross-platform GUI toolkit PyQt5 is a collection of Python interfaces for Qt version 5. With this library's...

4 minutes read.

Python round() function

Python round() function The round() function in Python returns a number rounded to ‘ndigits’ precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input. Syntax round(number[, ndigits]) Parameter Number: This parameter represents the...

1 minute read.

Dynamic Typing in Python

Many key factors for developing a great programming language include how it manages its memory space. This memory space largely depends on empty memory boxes called variables that one creates...

3 minutes read.

tell() function in Python

Introduction The tell() function in Python is used to return the current position of the file read/write pointer within the file. An integer value is returned by this method, and it...

2 minutes read.

Python Set symmetric_difference_update() method

Python Set symmetric_difference_update() method The set.symmetric_difference_update() method in Python updates the original set by removing items that are present in both sets and inserting the other items of the set. Syntax set.symmetric_difference_update(set1) Parameter set- This parameter represents the first...

2 minutes read.

Python Set update() method

Python Set update() method The set.update() method in Python updates the current set, by adding items from another set. If an element is common in both the sets, only one appearance of this item...

1 minute read.

Writing to a CSV file in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

6 minutes read.

Python Printf Style Formating

String objects have one special implicit activity: the % administrator (modulo). This is otherwise called the string designing or interjection administrator. Given design % values (where configuration is a string),...

3 minutes read.

Python AIOHTTP

Python 3.5 introduced some new syntax that makes it simpler for developers to make asynchronous programmes and packages. Aiohttp, an HTTP client/server for asyncio, is one such package. In essence,...

3 minutes read.

How to Create an Array in Python?

How to Create an Array in Python In the previous article, we have discussed how to declare an array in Python. So, let's have a quick revision of that, and then we...

5 minutes read.

Kite Python

Kite in Python: The Kite is a package provided by the python programming language; it works with the help of artificial intelligence and helps us write code inside the visual studio....

3 minutes read.

Python oct() function

Python oct() function The oct() function in Python converts an integer number to an octal string prefixed with “0o”. Syntax oct(x) Parameter x: This parameter represents an Integer Number Return This function returns an octal string. Example 1 #...

1 minute read.

Binary Search Visualization using Pygame in Python

A calculation like Binary Search is seen effectively by picturing. Here in this tutorial, a function that pictures the Binary Search Algorithm is carried out. The Graphical User’s Interface (GUI)...

15 minutes read.

Python Super function

The super function is used to access and call the methods or functions involved in the parent class during Inheritance. What is Inheritance? The process where the parent class inherits some of...

3 minutes read.

Python open() function

Python open() function The open() function in Python opens a file and returns a corresponding file object. If the file cannot be opened, an OSError is raised. Syntax open(file, mode='r', buffering=1, encoding=None, errors=None, newline=None, closefd=True, opener=None) Parameter file It represents the path and name of the file mode...

2 minutes read.

How to Configure Python Interpreter in Eclipse

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Python Console

Console in Python is referred as the command line Interpreter- (CLI) and also knows as Shell and it functions as taking input from the human user and interpreting it through...

6 minutes read.

Python CGI Programming

The Concept of CGI CGI is an abbreviation for Common Gateway Interface. It is not a type of language but a set of rules (specification) that establishes a dynamic interaction between...

9 minutes read.

Sklearn linear Model in Python

The most effective and reliable Python machine learning library is Sklearn. Through a Python consistency interface, it offers a variety of effective tools for statistical modeling and machine learning, including...

5 minutes read.

How to add 2 lists in Python?

In Python, a list is defined as a data structure that contains a sequence of elements. It can contain any kind of data type inside it but in order to concatenate two...

3 minutes read.