Calling a function in Python runs the instructions grouped under its name, so you can reuse them whenever you need. You’ll need Python and a place to write and run code, such as a Python file or interactive shell; then you call a function by writing its name followed by parentheses.
What You’ll Need
- Python installed, or an online Python environment.
- A code editor, notebook, or Python interactive shell.
- A function to call, either one you define or one provided by Python or a module.
Step-by-Step
- Find or define the function. A function definition begins with
def, followed by its name, parentheses, and a colon. The indented lines beneath it make up the function body. For example:def greet(): print("Hello!")Defining a function makes it available; it does not run its body.
- Write the function name with parentheses. On a new line after the definition, enter
greet(). The parentheses are what call the function. Run the program, and it printsHello!. Python executes the body when it reaches the call. - Pass required arguments. An argument is a value supplied between the parentheses. If a function expects a name, for example:
def greet(name): print(f"Hello, {name}!") greet("Mina")The call supplies
"Mina"for the parametername. The string is enclosed in quotes because it is text. Arguments are matched to parameters in the order given unless you use keyword arguments. - Use keyword arguments when helpful. You can specify a parameter by name, such as
greet(name="Mina"). This can make calls easier to read, especially when a function takes several inputs. Use the parameter names the function defines; misspelled names cause an error. - Capture a returned result if the function produces one. A function can send a value back with
return:def add(a, b): return a + b result = add(3, 4) print(result) # 7The call runs
add, and the returned value is assigned toresult. You can also use a call directly in an expression, such asprint(add(3, 4)). - Call imported functions using their available name. Some functions belong to modules and must be imported before use. For instance:
import math print(math.sqrt(25))Here,
sqrtis called through the module name,math. Alternatively,from math import sqrtlets you call it assqrt(25). Import the function before calling it. - Run the code and check the result. Save your file and run it with Python, or enter the definition and call in a Python shell. Confirm that the output or returned value is what you expected. If Python reports an error, read its type and the indicated line before changing the code.
Common Mistakes
- Leaving off the parentheses:
greetrefers to the function object;greet()calls it. A reference can be useful when passing a function to another function, but it does not run the function by itself. - Calling before defining: Python normally executes a script from top to bottom. If a call appears before the definition has run, Python may raise
NameError. Define the function first or move the call below its definition. - Providing the wrong number of arguments: Calling a function with too few or too many required positional arguments raises
TypeError. Check the definition and supply the expected values, unless the function has defaults or accepts a variable number of arguments. - Confusing printing with returning:
print()displays a value, but does not make that value the function’s result. A function without areturnstatement returnsNoneby default. - Using incorrect capitalization: Python names are case-sensitive.
Greet()andgreet()are different names. - Indenting the function body incorrectly: The body must be indented consistently beneath its
defline. Incorrect indentation can causeIndentationErroror change which lines belong to the function.
Tips
- Use descriptive function and parameter names, such as
calculate_totalorprice, to make calls easier to understand. - Check a function’s definition or documentation for its parameters, defaults, and return value. In an interactive Python shell,
help(function_name)can show documentation for many built-in or imported functions. - Use keyword arguments where they clarify the meaning of values:
round(number=3.14159, ndigits=2). A function’s actual parameter names determine which keywords are accepted. - Keep a function call separate from its definition while learning. This makes it clear which code creates the function and which code runs it.
- Remember that each call runs the function again. If it changes data or prints output, calling it multiple times can repeat those effects.
Troubleshooting
If the function does not run as expected, check the exact error message and follow these steps:
NameError: Check spelling and capitalization. Confirm that the definition or import runs before the call, and that the name is in the current scope.TypeErrorabout arguments: Compare the call with the function definition. Check the number of values, whether a required value is missing, and whether keyword names are correct. Also check whether each value has the expected type.IndentationErroror a syntax error: Look at the reported line and the lines just above it. Check the colon afterdef, balanced parentheses and quotes, and consistent indentation.- No visible output: The function may return a value without printing it. Assign the call to a variable and print that variable, or use
print(function_call())to display the returned result. - The result is
None: Check whether the function usesreturn. If it only prints a value, capture the result withreturninstead when you need to use it elsewhere. - Imported function not found: Confirm the import statement is present and correctly spelled. For a module function, use its module prefix, such as
math.sqrt(25), unless you imported the function directly.
After making one change, run the code again. Testing a small example with simple arguments can help isolate whether the issue is in the call, the function body, or the surrounding program.
Frequently Asked Questions
What is the basic syntax for calling a function in Python?
Write the function name followed by parentheses: function_name(). Put any required arguments inside the parentheses.
What is the difference between defining and calling a function?
A definition, written with def, creates the function. A call runs its body. Defining a function does not normally run it.
Can a Python function call another function?
Yes. A function can call another function, as long as that other function is available when the call runs. For example, one function can call print() or a function you defined.
How do I call a function that takes more than one argument?
Separate the arguments with commas, such as add(3, 4). You can also use parameter names, such as add(a=3, b=4), if those names match the definition.
How do I call a function from another Python file?
Import it from that file’s module, then call it by the imported name. The files must be arranged so Python can find the module; the import syntax depends on your project structure.
Why does writing a function name not run it?
Without parentheses, the name refers to the function itself. Add parentheses to call it, for example, change greet to greet().
Related
General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.
More in this bed
- Apps to Install for a New Mac: A Practical Starter List
- Show or Hide Thumbnails in Windows 10
- Choose a Loud Bluetooth Speaker for Your Gathering
- iPhone X IMEI and Serial Number: How to Find Them
- Access to Compressed Zipped Folder Is Denied in Windows 10
- Erase Microsoft Surface Data Without Booting Windows