Chapter 7 Creating New Functions

Keyword Action
def Defines new function
return Returns value at the end of function
from Gives name of an external file
import Brings in functions from an external file

You have been using many Pythons functions, such as range(), sort(), etc., to improve your code. Internally, a function is block of code with a given name. When you use a function (e.g. range(4)) within your code, Python executes the corresponding block of code and returns the result. That way your code stays small and readable.

Apart from the in-built functions Python provides you with, you can also create your own functions. Here is an example.

Code -

def square(x):
    return x*x

print(square(2))
print(square(3))

The keyword ‘def’ gives name to a function, and the variables within the parenthesis are its parameter. The block of indented code following def represents the code of the function, and the ‘return’ statement gives its return value to be used by the main program.

Here, you created a function named ‘square’ that takes only one parameter x. Internally, this function computes x*x and returns the result. Whenever you use square() in your main code, Python runs the block of code from its definition to get a result.

7.1 Code Flow with Functions

We need to also make clear that your main code consists of all lines after excluding the def blocks. The standard linear flow of execution from top to bottom does not hold for the functions. Let us illustrate the point with two codes.

Code 1 -

i=2
j=3

def square(x):
    print("inside",i,j)
    return(x*x)

print(square(i))
print(square(j))

Code 2 -

def square(x):
    print("inside",i,j)
    return x*x

i=2
j=3
print(square(i))
print(square(j))

You will see that both produce the same output. You may find that odd, because i and j are not defined before the function in the second case. How does the function know their values?

They work identically in both cases, because Python isolates the def block and keeps it separately. Then it takes the remaining lines and executes the code from top to bottom. Hence, i and j are already defined by the time the function square is called.

7.2 Providing Default Parameter

Code -

def square(x=1):
    return x*x

print(square())
print(square(2))
print(square(3))

The above code gives default value of 1 to the parameter x. When the function square() is called without any number, Python uses the default value to print 1*1.

7.3 Write a function to compute Fibonacci numbers.

def fibonacci(n, first=0, second=1):
  while n != 0:
    print(first)
    n, first, second = n - 1, second, first + second # assignment


print(fibonacci(10))

7.4 Recursive Functions

7.5 Importing Functions from a File

You learned in the previous section that Python separates out the function definitions, while executing the code. To keep the code readable, programmers often prefer to write the function definitions is a file separate from the main program. How does one run such multi-program code? We will learn that here by creating two files - ‘names.py’ for functions and ‘code.py’ for the main code. You cannot do this in the sandbox.

In file names.py, type -

def square(x=1):
        return x*X

def cube(x=1):
    return x*x*x

In code.py -

#from names import square
from names import *

print(square(2))
print(cube(2))
print(cube(10)/square(10))

Both files need to be in the same directory. When you run code.py, it will automatically incorporate the functions ‘square’ and ‘cube’ from names.py.

Note: import x vs from x import *

We will separate our code into two files and see how they run. You cannot do this in the sandbox.

In file other.py, type -

print("code in other file")

In main.py -

import other

print("code in main file")

Both files need to be in the same directory. When you run main.py, it will automatically include the code from ‘other.py’ and run it.

print("code in main file")

import other

The main purpose of import is to separate function definitions in a separate file. Import from external file happens only once.