The Wayback Machine - https://web.archive.org/web/20241108181031/https://www.geeksforgeeks.org/python-invoking-functions-with-and-without-parentheses/
Open In App

Python – Invoking Functions with and without Parentheses

Last Updated : 01 Nov, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Functions in Python are the defined blocks of code that perform a specific task. In this section, we will discuss the difference in invoking functions with and without Parentheses.

  • When we call a function with parentheses, the function gets execute and returns the result to the callable.
  • In another case, when we call a function without parentheses, a function reference is sent to the callable rather than executing the function itself.

Let’s discuss 3 important concepts:

  • Invoking functions
  • Return functions
  • Passing functions

Invoking functions –

The below function performs a simple task, string concatenation. Here we will invoke the function `concatenate_string` with and without parentheses and see the difference.

Python3




def concatenate_string(*args):
    string1 = args[0]
    string2 = args[1]
 
    return string1 + string2
 
obj = concatenate_string('Hello, ', 'George')
print('Function call with Parentheses: ')
print(obj)
 
obj = concatenate_string
print('Function call without Parentheses: ')
print(obj)


Output

Function call with Parentheses: 
Hello, George
Function call without Parentheses:
<function concatenate_string at 0x7f0bb991df28>

For the first case, when we call

concatenate_string('Hello, ', 'George')

, the function executes and returns the concatenated string. And, for the second case, when we call

concatenate_string

i.e. without parentheses, a reference is passed to the callable rather than executing the function itself. Here the callable can decide what to do with the reference.

Return Functions –

From the above discussion you can understand that, when the function is called with parentheses, the code is executed and returns the result. And, when it is called without parentheses, a function reference is returned to the callable. So, what happens when a function is coded along with a return statement with parentheses and without parentheses. Let’s go through an example.

With Parentheses

Python3




def concatenate_string(*args):
 
    string1 = args[0]
    string2 = args[1]
     
    def merge_string(string1, string2):
        return string1 + string2
     
    return merge_string(string1, string2)
 
def func():
    conc_obj = concatenate_string('Hello, ', 'George')
    print(conc_obj)
 
func()


Output

Hello, George

From the above example, it’s clear that the

merge_string

is a function within the function

concatenate_string

and the main function (

concatenate_string

) returns the sub-function (

merge_string

) to the caller.

 return merge_string(string1, string2) 

Here

merge_string

is invoked with parentheses, hence it executes and provides the result to the

concatenate_string

from where the result is passed to

func

.

Without Parentheses

Python3




def concatenate_string():
     
    def merge_string(string1, string2):
        return string1 + string2
     
    return merge_string
 
def func():
     
    # return the reference of merge_string func
    conc_obj = concatenate_string()
    print(conc_obj)  # prints the reference
 
    # executes the reference
    print(conc_obj('Hello, ', 'George')) 
 
func()


Output:

<function concatenate_string..merge_string at 0x7f1e54ebc158>
Hello, George

Since the

merge_string

is used without parentheses, the

concatenate_string

passes the function reference to the callable

func

rather than executing the

merge_string

.

return merge_string

Hence, we can conclude that when we code sub-function with parentheses in a return statement, the main function executes the sub-function and passes the result to the callable.  And, when we code subfunction without parentheses in a return statement, the main function passes the sub-function reference to the callable rather than executing it. Here the callable decides what to do with the reference.

Passing Functions –

You can pass a function as an argument by creating the reference, calling the function without parentheses, and provide it as an argument. Let’s look into the code.

Python3




def concatenate_string(*args):
    string1 = args[0]
    string2 = args[1]
 
    def merge_string(string1, string2):
        return string1 + string2  # string merge
    
    # executes merge_string and return the result
    return merge_string(string1, string2)
 
def function_call(function):
    string1 = 'Hello, '
    string2 = 'George'
    return function(string1, string2)
 
# passing function as argument
print(function_call(concatenate_string)) 


Output:

Hello, George

In this case, the reference of

concatenate_string

is passed to the

function_call

as an argument.

function_call(concatenate_string)

Inside function_call, it executes the

concatenate_string

using the reference and returns the result to the callable.



Similar Reads

Parentheses, Square Brackets and Curly Braces in Python
In Python, `()`, `{}`, and `[]` are used to represent different data structures and functionalities. Understanding their differences is crucial for writing clear and efficient Python code. As a Python developer, we must know when to use these for writing efficient code. In this article, we have explained their use cases with examples. Difference Be
4 min read
When Are Parentheses Required Around a Tuple in Python?
In Python programming, tuples are a fundamental data structure used to store collections of items. Unlike lists, tuples are immutable, meaning once created, their contents cannot be changed. Tuples are commonly used for grouping related data together. They are defined by enclosing the elements in parentheses, separated by commas, like so: (element1
3 min read
Fix: "SyntaxError: Missing Parentheses in Call to 'print'" in Python
In Python, if we see the "SyntaxError: Missing Parentheses in Call to 'print'" error, it means we forgot to use parentheses around what we want to print. This is the most common error that we encounter when transitioning from Python 2 to Python 3. This error occurs due to a significant change in how the print statement works between Python2 and Pyt
3 min read
Check if the Depth of Parentheses is correct in the given String
Given a string S consisting of opening parentheses, closing parentheses and integers, the task is to print Yes if, in this string, the integers correctly indicates its depth. Depth refers to the number of nested sets of parentheses surrounding that integer. Print No otherwise.Examples: Input: S = "((2)((3)))" Output: Yes Explanation: No of Opening
7 min read
Balance the parentheses for the given number N
Given a number N, the task is to insert the minimum number of opening and closing parenthesis into the number N such that the resultant string is balanced and every digit D is exactly in D pairs of matching parenthesis. Examples: Input: N = 312 Output: (((3))1(2)) Explanation: Every digit in the number is within exactly in D parenthesis. There are
3 min read
Mathematical Functions in Python | Set 2 (Logarithmic and Power Functions)
Numeric functions are discussed in set 1 below Mathematical Functions in Python | Set 1 ( Numeric Functions) Logarithmic and power functions are discussed in this set. 1. exp(a) :- This function returns the value of e raised to the power a (e**a) . 2. log(a, b) :- This function returns the logarithmic value of a with base b. If base is not mentione
3 min read
Mathematical Functions in Python | Set 3 (Trigonometric and Angular Functions)
Some of the mathematical functions are discussed in below set 1 and set 2 Mathematical Functions in Python | Set 1 (Numeric Functions) Mathematical Functions in Python | Set 2 (Logarithmic and Power Functions) Trigonometric and angular functions are discussed in this article. 1. sin() :- This function returns the sine of value passed as argument. T
3 min read
Mathematical Functions in Python | Set 4 (Special Functions and Constants)
Some of the mathematical functions are discussed in below set 1, set 2 and set 3 Mathematical Functions in Python | Set 1 (Numeric Functions) Mathematical Functions in Python | Set 2 (Logarithmic and Power Functions) Mathematical Functions in Python | Set 3 (Trigonometric and Angular Functions) Special Functions and constants are discussed in this
2 min read
Mathematical Functions in Python | Set 1 (Numeric Functions)
In python a number of mathematical operations can be performed with ease by importing a module named "math" which defines various functions which makes our tasks easier. 1. ceil() :- This function returns the smallest integral value greater than the number. If number is already integer, same number is returned. 2. floor() :- This function returns t
3 min read
getpass() and getuser() in Python (Password without echo)
getpass() prompts the user for a password without echoing. The getpass module provides a secure way to handle the password prompts where programs interact with the users via the terminal. getpass module provides two functions :Using getpass() function to prompt user password Syntax: getpass.getpass(prompt='Password: ', stream=None) The getpass() fu
2 min read
Histogram Plotting and stretching in Python (without using inbuilt function)
Prerequisites: OpenCV Python Program to analyze an image using Histogram Histogram of a digital image with intensity levels in the range of 0 to L-1 is a discrete function - h(rk) = nk where rk = kth intensity value and no = number of pixels in the image with rk intensity value. If the image has M rows and N columns, then the total number of pixels
3 min read
How to split data into training and testing in Python without sklearn
Here we will learn how to split a dataset into Train and Test sets in Python without using sklearn. The main concept that will be used here will be slicing. We can use the slicing functionalities to break the data into separate (train and test) parts. If we were to use sklearn this task is very easy but it can be a little tedious in case we are not
2 min read
Python | Set 2 (Variables, Expressions, Conditions and Functions)
Introduction to Python has been dealt with in this article. Now, let us begin with learning python. Running your First Code in Python Python programs are not compiled, rather they are interpreted. Now, let us move to writing python code and running it. Please make sure that python is installed on the system you are working on. If it is not installe
3 min read
Python | startswith() and endswith() functions
Python library provides a number of built-in methods, one such being startswith() and endswith() functions which are used in string related operations. Startswith() Syntax: str.startswith(search_string, start, end) Parameters : search_string : The string to be searched. start : start index of the str from where the search_string is to be searched.
2 min read
maketrans() and translate() functions in Python
In the world of programming, seldom there is a need to replace all the words/characters at once in the whole file python offers this functionality using functions translate() and its helper functions maketrans(). Both functions are discussed in this article. maketrans() maketrans() function is used to construct the transition table i.e specify the
3 min read
Difference Between tf.Session() And tf.InteractiveSession() Functions in Python Tensorflow
In this article, we are going to see the differences between tf.Session() and tf.InteractiveSession(). tf.Session() In TensorFlow, the computations are done using graphs. But when a graph is created, the values and computations are not defined. So a session is used to run the graph. The sessions place the graphs on targeted devices and execute them
3 min read
Python bit functions on int (bit_length, to_bytes and from_bytes)
The int type implements the numbers.Integral abstract base class. 1. int.bit_length() Returns the number of bits required to represent an integer in binary, excluding the sign and leading zeros. Code to demonstrate num = 7 print(num.bit_length()) num = -7 print(num.bit_length()) Output: 3 3 2. int.to_bytes(length, byteorder, *, signed=False) Return
1 min read
Difference between input() and raw_input() functions in Python
Developers often have a need to interact with users, either to get data or to provide some sort of result. Most programs today use a dialog box as a way of asking the user to provide some type of input. While Python provides us with two inbuilt functions to read the input from the keyboard. input ( prompt )raw_input ( prompt )input() function Pytho
4 min read
turtle.setpos() and turtle.goto() functions in Python
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support. turtle.setpos() This method is used to move the turtle to an absolute position. This method has Aliases: setpos, setposition, goto. S
1 min read
Why and how are Python functions hashable?
So start with the question i.e. Why and how are Python functions hashable? First, one should know what actually hashable means in Python. So, hashable is a feature of Python objects that tells if the object has a hash value or not. If the object has a hash value then it can be used as a key for a dictionary or as an element in a set. An object is h
2 min read
Python Regex - re.MatchObject.start() and re.MatchObject.end() functions
In this article, we are going to see re.MatchObject.start() and re.MatchObject.end() regex methods. re.MatchObject.start() This method returns the first index of the substring matched by group. Syntax: re.MatchObject.start([group]) Parameter: group: (optional) group defaults to zero (meaning the whole matched substring). Return -1 if group exists b
2 min read
Array in Python | Set 1 (Introduction and Functions)
Other than some generic containers like lists, Python in its definition can also handle containers with specified data types. The array can be handled in Python by a module named "array". They can be useful when we have to manipulate only specific data type values. Properties of ArraysEach array element is of the same data type and size. For exampl
7 min read
Complex Numbers in Python | Set 2 (Important Functions and Constants)
Introduction to python complex numbers: Complex Numbers in Python | Set 1 (Introduction) Some more important functions and constants are discussed in this article. Operations on complex numbers : 1. exp() :- This function returns the exponent of the complex number mentioned in its argument. 2. log(x,b) :- This function returns the logarithmic value
4 min read
Complex Numbers in Python | Set 3 (Trigonometric and Hyperbolic Functions)
Some of the Important Complex number functions are discussed in the articles below Complex Numbers in Python | Set 1 (Introduction) Complex Numbers in Python | Set 2 (Important Functions and constants) Trigonometric and Hyperbolic Functions are discussed in this article. Trigonometric Functions 1. sin() : This function returns the sine of the compl
4 min read
Statistical Functions in Python | Set 1 (Averages and Measure of Central Location)
Python has the ability to manipulate some statistical data and calculate results of various statistical operations using the file "statistics", useful in domain of mathematics. Important Average and measure of central location functions : 1. mean() :- This function returns the mean or average of the data passed in its arguments. If passed argument
3 min read
Print first m multiples of n without using any loop in Python
Given n and m, print first m multiples of a m number without using any loops in Python. Examples: Input : n = 2, m = 3 Output : 2 4 6 Input : n = 3, m = 4 Output : 3 6 9 12 We can use range() function in Python to store the multiples in a range. First we store the numbers till m multiples using range() function in an array, and then print the array
3 min read
Get filename from path without extension using Python
Getting a filename from Python using a path is a complex process. i.e, In Linux or Mac OS, use "/" as separators of the directory while Windows uses "\" for separating the directories inside the path. So to avoid these problems we will use some built-in package in Python. File Structure: Understanding Paths path name root ext /home/User/Desktop/fil
4 min read
Python - Read CSV Column into List without header
Prerequisites: Reading and Writing data in CSV CSV files are parsed in python with the help of csv library. The csv library contains objects that are used to read, write and process data from and to CSV files. Sometimes, while working with large amounts of data, we want to omit a few rows or columns, so that minimum memory gets utilized. Let's see
2 min read
Image Processing without OpenCV | Python
We know OpenCV is widely used to operate on images and has a wide spectrum of functions to do so. But what if we want to process the image files without using any external library like OpenCV. Let's see how can we do this. Image Scaling (Using Nearest Neighbour Interpolation): Nearest Neighbour interpolation is the simplest way of interpolation. Th
4 min read
Python | Grid Layout in Kivy without .kv file
Kivy is a platform independent as it can be run on Android, IOS, linux and Windows etc. Kivy provides you the functionality to write the code for once and run it on different platforms. It is basically used to develop the Android application, but it Does not mean that it can not be used on Desktops applications. ???????? Kivy Tutorial - Learn Kivy
5 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg