sodcalculator

10 Tech How-To

How to Call a Function in Python

Guide 10-40726 · Updated · Step by step

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

  1. 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.

  2. 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 prints Hello!. Python executes the body when it reaches the call.
  3. 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 parameter name. The string is enclosed in quotes because it is text. Arguments are matched to parameters in the order given unless you use keyword arguments.

  4. 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.
  5. 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)  # 7

    The call runs add, and the returned value is assigned to result. You can also use a call directly in an expression, such as print(add(3, 4)).

  6. 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, sqrt is called through the module name, math. Alternatively, from math import sqrt lets you call it as sqrt(25). Import the function before calling it.

  7. 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: greet refers 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 a return statement returns None by default.
  • Using incorrect capitalization: Python names are case-sensitive. Greet() and greet() are different names.
  • Indenting the function body incorrectly: The body must be indented consistently beneath its def line. Incorrect indentation can cause IndentationError or change which lines belong to the function.

Tips

  • Use descriptive function and parameter names, such as calculate_total or price, 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.
  • TypeError about 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.
  • IndentationError or a syntax error: Look at the reported line and the lines just above it. Check the colon after def, 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 uses return. If it only prints a value, capture the result with return instead 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

The whole Tech How-To bed →