Functions in Python

Our first program will demonstrate functions in Python. Here’s the full source code with explanations:

# Here's a function that takes two integers and returns
# their sum as an integer.
def plus(a: int, b: int) -> int:
    # Python doesn't require explicit returns, but we'll
    # use one here for clarity.
    return a + b

# When you have multiple parameters of the same type,
# you can omit the type annotation for all but the last parameter.
def plus_plus(a, b, c: int) -> int:
    return a + b + c

# The main function is not required in Python, but we'll
# use it to organize our code.
def main():
    # Call a function just as you'd expect, with
    # name(args).
    res = plus(1, 2)
    print("1+2 =", res)

    res = plus_plus(1, 2, 3)
    print("1+2+3 =", res)

# This idiom ensures that the main() function is called
# only if this script is run directly (not imported).
if __name__ == "__main__":
    main()

To run the program, save it as functions.py and use the Python interpreter:

$ python functions.py
1+2 = 3
1+2+3 = 6

Python functions are first-class objects, which means they can be assigned to variables, stored in data structures, passed as arguments to other functions, and even returned as values from other functions.

There are several other features to Python functions. One is multiple return values, which we’ll look at next.