Encapsulating code with functions

Functions are useful for gathering similar pieces of code in one place. Consider the following mathematical function:

Encapsulating code with functions

The Python equivalent is as follows:

def f(x):
    return 2*x + 1

In Figure 1.4 Anatomy of a function the  elements of a function block are explained. 

  • The keyword def   tells Python we are defining a function.
  • f is the name of the function.
  • x is the argument, or input of the function.
  • What is after return is called the output of the function.

Encapsulating code with functions

Figure 1.4: Anatomy of a function

Once the function is defined, it can be called using the following code:

f(2) # 5
f(1) # 3
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.123.126