How to call a function in python
How to call a function in python
What does it mean to «call» a function in Python? [closed]
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn’t work, and the expected results. See also: Stack Overflow question checklist
What does «call» mean and do? How would you «call» a function in Python?
4 Answers 4
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
When you «call» a function you are basically just telling the program to execute that function. So if you had a function that added two numbers such as:
you would call the function like this:
which would return 8. You can put any two numbers in the parentheses in this case. You can also call a function like this:
Which would set the variable answer equal to 11 in this case.
I’ll give a slightly advanced answer. In Python, functions are first-class objects. This means they can be «dynamically created, destroyed, passed to a function, returned as a value, and have all the rights as other variables in the programming language have.»
Calling a function/class instance in Python means invoking the __call__ method of that object. For old-style classes, class instances are also callable but only if the object which creates them has a __call__ method. The same applies for new-style classes, except there is no notion of «instance» with new-style classes. Rather they are «types» and «objects».
Thus whenever you define a function with the shorthand def funcname(parameters): you are really just creating an object with a method __call__ and the shorthand for __call__ is to just name the instance and follow it with parentheses containing the arguments to the call. Because functions are first class objects in Python, they can be created on the fly with dynamic parameters (and thus accept dynamic arguments). This comes into handy with decorator functions/classes which you will read about later.
For now I suggest reading the Official Python Tutorial.
Calling a function in Python
Sign in to change your settings
Sign in to your Python Morsels account to save your screencast settings.
Don’t have an account yet? Sign up here.
What are functions and how can we use them?
Calling a function
Let’s use a function that’s built into Python: the built-in sum function.
If we type sum and hit the Enter key, we’ll see what the variable sum points to:
We’re not actually using the function here, we’re referring to the function object that the variable sum points to.
To use this function, we need to put parentheses after it. Putting parenthesis after a function will call the function.
When calling this function we got an error because the sum function requires at least one argument but we didn’t pass it any arguments.
To use the sum function we have to pass it an iterable of numbers as an argument.
Arguments and return values
To pass an argument to a function, you put the argument inside the parentheses when calling the function.
Arguments are basically the inputs to a function. Functions have inputs (as arguments) and an output as a return value. The integer 46 is the return value of this function:
We saw 46 printed out at the Python REPL, but this sum function didn’t actually print 46, it returned 46.
If we put this function call on the right-hand side of an = sign, we can assign the variable total to whatever the return value of calling sum with numbers was (in this case, it was 46).
The default return value is None
Not all functions have returned values. For example, the print function doesn’t have a return value.
If we assign a variable to the return value of a print call:
We’ll see text ( Trey ) printed out, but we’ll also see that the variable name is None :
None is a special value that basically means this function doesn’t have a return value.
In Python, we typically assume that functions either perform some action or return something, but not both. The print function performs an action (it prints something to the screen) whereas the sum function returns a value.
Summary
To use functions in Python, you write the function name (or the variable that points to the function object) followed by parentheses (to call the function). If that function accepts arguments (as most functions do), then you’ll pass the arguments inside the parentheses as you call the function.
If that function has a return value, you can capture that return value into a variable or pass that return value straight into another function call.
Series: Functions
Python, like many programming languages, has functions. A function is a block of code you can call to run that code.
Python’s functions have a lot of «wait I didn’t know that» features. Functions can define default argument values, functions can be called with keyword arguments, and functions can be written to accept any number of arguments.
To track your progress on this Python Morsels topic trail, sign in or sign up.
Different ways to call a function in Python [Examples]
Table of Contents
Introduction to Python call function
Python is well known for its various built-in functions and a large number of modules. These functions make our program more readable and logical. We can access the features and functionality of a function by just calling it. In this tutorial, we will learn about how the python call function works. We will take various examples and learned how we can call python built-in functions and user-defined functions. Moreover, we will cover how to call a function with arguments and without arguments.
At the same time, we will also discuss about the data types of these arguments and their order as well. In a conclusion, this tutorial covers all the concepts and details that you need to start working with functions and calling functions.
Getting started with Python call function
Before starting and learning how to call a function let us see what is a python function and how to define it in python. So, a Python function is a group of codes that allows us to write blocks of code that perform specific tasks. A function can be executed as many times as a developer wants throughout their code. The def keyword is used to define and declare a function. See the syntax below;
To run the code in a function, we must call the function. A function can be called from anywhere after the function is defined. In the following section, we will learn how we can call a function and how they return a value.
Syntax and example of the python call function
We already had learned how we can define a function, now let us see how we can call a function that we have defined. The following syntax is used to call a function.
Now let us create a function that prints welcome and see how we can call it using the above syntax. See the following example.
Calling python function with returned value
In the above example, notice that it did not return any value or expression, it just prints out the welcome statement. In python, we can return a value from a function as well by using the return keyword. First, let us take the same example and return the welcome statement this time, instead of printing it out. See the example below:
Now if we check the type of function’s return by using the python type method, we will get string type because this function returns a string value. See the example below:
Note that the function type is a string. Now let us take one more example which returns the sum of two numbers. See the example below:
Now let us check the type of function by using the python type method. See the example below:
Notice that this time we got int type because our function returns an integer value. The type changes each time because we are finding the returned type of a function using the python type function and applying it on the python call function. If we find the type of function without calling it, we will get «type function». See the example below:
Calling python built-in functions
We know that python is well known for its various built-in functions. Some of these functions come with python and some with different modules. We can access the functionalities of these functions by calling the function. See the example below which call the sum function.
Notice that we didn’t define a function to return the sum of the given number, in fact, the sum is a Python built-in function that returns the sum of the given number. In a similar way, if want to access a function that is inside a module, we have to first import that module and then call the function. See the example below:
In this way, we can access other python built-in functions as well.
Python call function with arguments
So far we have learned how we can call a function that does not takes any arguments, In this section, we will discuss different types of arguments that a function can take. A function can take single or multiple arguments depending on the definition of the function. The syntax of function with arguments looks like this:
And we can call the function by passing arguments. See the syntax below:
Integer arguments in python call function
Not let us take the example of the python function that takes integers as an argument and returns the sum of all the arguments. See the example below:
If we provide the number of arguments greater than or less than the defined ones, we will get an error. See the following example.
String arguments in python call function
Now let us take the example of strings as an argument to python function. See the example which takes three strings as an argument and prints out them.
The order of arguments is very important in python otherwise we might get unexpected output. See the example below where we place our first name in the last and school name in the beginning. See the example below:
Notice that there is not any syntax error but the output is not logical, so the order of argument is very important in python.
Calling a function in python loop
We can even call a function inside from a loop as well. The function will be called each time the loop executes and will stop calling once the loop finishes. In this section, we see how we call a function from a loop.
Python call function inside for loop
A Python for loop is used to loop through an iterable object (like a list, tuple, set, etc.) and perform the same action for each entry. We can call a function from inside of for loop. See the following example which demonstrates the working of the python call function from inside of for loop.
Notice that the function was called each time the statement inside for loop executes.
Python call function inside while loop
A Python while Loop is used to execute a block of statements repeatedly until a given condition is satisfied. And when the condition becomes false, the line immediately after the loop in the program is executed. We can be called from a while loop and can be executed each time unless the loop terminates. See the example below:
Note the once the condition becomes false, the while loop terminates.
Python call function from inside function itself
Python also accepts function recursion, which means a defined function can call itself. Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that we can loop through data to reach a result. Once the condition becomes false, it will stop calling a function, other wise it will continue to infinity. Let us now take an example of the python call function from the inside function itself. See the example below:
Notice that the function is called five times from inside itself and once the condition becomes false, it stops calling.
Summary
Python function is a group of codes that perform a specific task. To get the functionality and features of function, we have to call it. In this tutorial, we learned about the python call function. We learned how we can call built-in function and user-defined function. At the same time, we come across passing and call functions with multiple arguments with different data types. Furthermore, we also came across example and learned how the calling a function from python loops work. In a nutshell, in this tutorial, we learned everything that we need to learn about the python call function.
Further Reading
Related Posts
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your support!!
Python Functions
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
Creating a Function
In Python a function is defined using the def keyword:
Example
Calling a Function
To call a function, use the function name followed by parenthesis:
Example
def my_function():
print(«Hello from a function»)
my_function()
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name:
Example
def my_function(fname):
print(fname + » Refsnes»)
my_function(«Emil»)
my_function(«Tobias»)
my_function(«Linus»)
Arguments are often shortened to args in Python documentations.
Parameters or Arguments?
The terms parameter and argument can be used for the same thing: information that are passed into a function.
From a function’s perspective:
A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that is sent to the function when it is called.
Number of Arguments
By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.
Example
This function expects 2 arguments, and gets 2 arguments:
def my_function(fname, lname):
print(fname + » » + lname)
Example
This function expects 2 arguments, but gets only 1:
def my_function(fname, lname):
print(fname + » » + lname)
Arbitrary Arguments, *args
If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access the items accordingly:
Example
If the number of arguments is unknown, add a * before the parameter name:
def my_function(*kids):
print(«The youngest child is » + kids[2])
my_function(«Emil», «Tobias», «Linus»)
Arbitrary Arguments are often shortened to *args in Python documentations.
Keyword Arguments
You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter.
Example
def my_function(child3, child2, child1):
print(«The youngest child is » + child3)
my_function(child1 = «Emil», child2 = «Tobias», child3 = «Linus»)
The phrase Keyword Arguments are often shortened to kwargs in Python documentations.
Arbitrary Keyword Arguments, **kwargs
If you do not know how many keyword arguments that will be passed into your function, add two asterisk: ** before the parameter name in the function definition.
This way the function will receive a dictionary of arguments, and can access the items accordingly:
Example
If the number of keyword arguments is unknown, add a double ** before the parameter name:
def my_function(**kid):
print(«His last name is » + kid[«lname»])
my_function(fname = «Tobias», lname = «Refsnes»)
Arbitrary Kword Arguments are often shortened to **kwargs in Python documentations.
Default Parameter Value
The following example shows how to use a default parameter value.
If we call the function without argument, it uses the default value:
Example
def my_function(country = «Norway»):
print(«I am from » + country)
Passing a List as an Argument
You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.
E.g. if you send a List as an argument, it will still be a List when it reaches the function:
Example
def my_function(food):
for x in food:
print(x)
fruits = [«apple», «banana», «cherry»]
Return Values
To let a function return a value, use the return statement:
Example
The pass Statement
function definitions cannot be empty, but if you for some reason have a function definition with no content, put in the pass statement to avoid getting an error.
Example
Recursion
Python also accepts function recursion, which means a defined function can call itself.
Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.
The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates, or one that uses excess amounts of memory or processor power. However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming.
To a new developer it can take some time to work out how exactly this works, best way to find out is by testing and modifying it.
Example
print(«\n\nRecursion Example Results»)
tri_recursion(6)
Python Functions – How to Define and Call a Function
In programming, a function is a reusable block of code that executes a certain functionality when it is called.
Functions are integral parts of every programming language because they help make your code more modular and reusable.
In this article, I will show you how to define a function in Python and call it, so you can break down the code of your Python applications into smaller chunks.
I will also show you how arguments and the return keyword works in Python functions.
Basic Syntax for Defining a Function in Python
In Python, you define a function with the def keyword, then write the function identifier (name) followed by parentheses and a colon.
The next thing you have to do is make sure you indent with a tab or 4 spaces, and then specify what you want the function to do for you.
Basic Examples of a Function in Python
Following the basic syntax above, an example of a basic Python function printing “Hello World” to the terminal looks like this:
To call this function, write the name of the function followed by parentheses:
Next, run your code in the terminal by typing python filename.py to show what you want the function to do:
Another basic example of subtractig 2 numbers looks like this:
Arguments in Python Functions
While defining a function in Python, you can pass argument(s) into the function by putting them inside the parenthesis.
The basic syntax for doing this looks as shown below:
When the function is called, then you need to specify a value for the arguments:
Here’s an example of arguments in a Python function:
In the example above:
N.B.: You can specify as many arguments as you want.
How to Use the Return Keyword in Python
In Python, you can use the return keyword to exit a function so it goes back to where it was called. That is, send something out of the function.
The return statement can contain an expression to execute once the function is called.
The example below demonstrates how the return keyword works in Python:
What’s the code above doing?
Conclusion
In this article, you learned how to define and call functions in Python. You also learned how to pass arguments into a function and use the return keyword, so you can be more creative with the functions you write.
If you find this article helpful, don’t hesitate to share it with your friends and family.
Web developer and technical writer focusing on frontend technologies.
If you read this far, tweet to the author to show them you care. Tweet a thanks
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
freeCodeCamp is a donor-supported tax-exempt 501(c)(3) nonprofit organization (United States Federal Tax Identification Number: 82-0779546)
Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.