Python

Python Functions

Python Functions

Python functions refer to blocks of code, performing specific tasks and only executed when called.

There are two types of functions, built-in and user-defined by the developer.

  • Built-in functions are available at any time (for instance, “input()” in the previous page).
  • User-defined can be anything, depending on the developer need.

The structure of Python functions is as follows:

  • def is the keyword for defining a function
  • function name, followed by parentheses
  • parameters (inside the parentheses)
  • executable statement(s)

Indentation and colon usage are vital for the operation of a function.

The following is an example of a basic function (no parameters).

# Defining the function
def function_name():
    print("Hello, World!")

# Calling the function
function_name()

# Output: Hello, World!
python functions syntax programming coding tutorial

Parameters and arguments

Functions without parameters still execute the statements within the function. Parameters allow function to pass information. In other words, data can pass through the calling of the function, interact with the function’s statements, and produce a cohesive outcome.

This is better comprehended in an example.

# Defining the function
def person(first_name, surname):
    print("My last name is", surname)
    print("But you can call me", first_name)

# Calling the function
person("James", "Smith")
# Output:
My last name is Smith
But you can call me James

Note: developers often use “parameters” and “arguments” interchangeably. Both keywords pass informational flow, with the former placed in the implementation of the function, and the latter in the calling stage (see below).

# Defining the function
def person(first_name, surname): # <-- parameters

# Calling the function
person("James", "Smith") # <-- arguments 

Next: Python Classes

by AICorr Team

We are proud to offer our extensive knowledge to you, for free. The AICorr Team puts a lot of effort in researching, testing, and writing the content within the platform (aicorr.com). We hope that you learn and progress forward.