Definition

New:

  • function definition
    • header
    • parameters
    • body

We've briefly mentioned the idea of function definition in the first course. We said that function definition is the code which "creates" the function; it needs to be written only once, and is always separate from use.

So, first, let's come up with a new name β€” we recommend to use a verb, an action corresponding to what the function does. You can't use pow: it's semantically incorrect to re-use existing names1. Let's go with get_power, it's clear and appropriate. If we were to call that new function, the call would look like this:

get_power(3, 2)

Function pow can operate in two modes: simple exponentiation and exponentiation with modulo2. We only need the simple exponentiation, so that's what we'll implement ourselves. Let’s start defining our function. There're 2 parts involved:

  1. Function's header which consists of the def keyword followed by function's name and parameters.

    def get_power(base, power):
    

    By writing the code in such order β€” def get_power(base, power): β€” we declare the birth of a new machine.

    Our function should be able to receive exactly 2 numeric values from a call to perform exponentiation. To enable that, we've created 2 containers in the brackets after the name. These containers are called parameters. Each parameter must be given an appropriate name; we thought base and power are pretty good. These names are going to be used in the body.

    At the time of writing the function the programmer does not have any values yet. Parameters are the way to refer to future values before they actually exist. It's like in math when you use x instead of an actual number.

    The closing bracket is followed by a colon : symbol, a small but important part which indicates that the following line is the beginning of the body.

  2. Function's body.

    We are going to create the body based on the purpose of the future function. The body always starts on the next line after the header, and is written with indentation of four spaces3. The REPL.it editor adds indentation automatically when you press Enter after writing the header. In other editors you may need to manually push the spacebar four times. In Python, such indentation for the body is a mandatory syntax rule4 It’s not just for visual comfort, like in other languages.

    We want to describe the exponentiation using the values via parameters:

    def get_power(base, power):
        base ** power
    

    The body may contain multiple lines of code. The indentation controls the border of the body, i.e. the body ends as soon as there's a line without indentation. The body cannot be split into several parts.

We've started the definition of one function, and the choices we've made β€” name, amount and names of parameters β€” are relevant for this particular function. When you create your own functions, you will make your own choices based on the requirements and the goals.

The general pattern for defining functions is as follows:

def function_name(parameter_1, parameter_2,...):
    body

(Note that there could be any amount of parameters, including zero β€” no parameters at all.)

This pattern demonstrates the strictness of programming in general and Python in particular. Each little detail matters: parameters must be in round brackets and must be comma-separated, the header must end with a colon, the body must be indented, and so on. You'll be dealing with more complex syntactical structures, and encounter more little things which, when written incorrectly, could render the whole program invalid. Or worse: your mistake may be interpreted by the interpreter as something else, not as something you wanted. This often happens when one copies fragments of code from the web. A large portion of programmer's work is finding that tiny comma or a whitespace. Of course, there are tools that help, but in the end it's you versus the syntax.

Technically, our definition is complete, but it's not really useful yet. In the next lesson we'll understand why by testing it.

Syntax rules for names of variables, functions and parameters

Python has strict rules for any names a programmer can create. This includes variables, functions, parameters and other entities that you'll learn in the future. The rules were introduced in "Python, part 1", here they are to refresh your memory:

1. Symbols. Only letters, digits and underscore _ allowed. Others are prohibited.

  • em@il, c]oud, go_#_home are incorrect

2. First symbol. Cannot be a digit.

  • 2go, 99, 13floor are incorrect

3. Reserved keywords. Prohibited to use Python's reserved keywords5.

  • def, None, lambda are incorrect

4. Case-sensitivity.

  • get_power and Get_power, run and RUN are different names

Conclusions:

  1. Definition (creation) of a function starts with the def keyword, followed by function name, parameters in parentheses and semicolon :. This line is called a function header.
  2. After the header goes the function's body with indentation of four spaces.
  3. Parameter is a container used to pass information into a function. Like variables, parameters must be named.
1

In addition, re-using names of built-in functions might lead to unexpected behavior and errors. (See a list of built-in functions.)

2

The modulo operation finds the remainder after a division of one number by another. This is related to Modular arithmetic and has applications in math, cryptography and computing.

3

Soon we will start writing complex structures inside the bodies. Such structures contain their own, further indentation. Thus, certain lines code may have more than 4 spaces of indentation. However, all of them are still considered to be a part of the body.

4

Python requires at least 2 spaces for indentation. 4 is also acceptable. The coding standard called PEP-8 is widely used in the industry, and according to it 4 spaces should be used. Keep this in mind when you read or copy code from other sources. Some programmers prefer 2 spaces. The goal is to be consistent, and for you and most programmers the simplest way is to follow PEP-8. Also, note that REPL.it editor creates indentation automatically with 2 spaces by default. For example, when you write a function header and press Enter, 2 spaces are automatically added. When pasting code into REPL.it, notice the vertical lines on the left of code: they indicate the depth of indentation and appear each 2, 4 or 8 spaces depending on settings. You can change the settings by clicking the gear icon in the left sidebar.

5

Full list of Python keywords:

False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise