Chapter 10 - Introductory Python Custom and

Builtin Functions


10.1.0 Python Custom Functions

Functions allow us to name a repetitive task and call the name of the function to complete the task. The following function starts with def and ends with return. Notice the indents. The value of the function is called in the print statement. The function parameters are a and b. The arguments are 3 and 4.

def myfunction(a,b):
   c = a + b
   return c

print('Value of the function is:' ,myfunction(3,4))

# Output    Value of the function is: 7

The number of parameters and arguments must be the same, and in the correct order. If you do not know how many arguments there are, use *args. The following is an example.

def mynumbfunct(*args):    # Unknown number of arguments
   for arg in args:
       print(arg)     # Prints all arguments

mynumbfunct(2,6,99)    # Three parameters

# Output
# 2
# 6
# 99

10.2.0 Python Builtin Functions

There are many builtin functions in Python. There are specialized modules full of functions. The math module is always available. Just type import math. Then type math. and the name of the function. The following is an example.

import math
print (math.sqrt(4))
# Argument of trig functions must be radians
print(math.pi *3)

# Output
# 2.0
# 1.0
# 9.42477796076938

A module is a collection of functions in a py file. We can import the module and use it’s functions. As a simple example, we have created the module in a file called We created functions for add, subtract, and multiply. We then called the module math_operators and used it to add, subtract, and multiply.

# A module is a collection of functions in a py file
# We create these functions in a module called
def add(a, b):
  return a + b
def subtract(a, b):
  return a - b
def multiply(a, b):
   return a * b

# A module is a collection of functions in a py file
# We can import the module and use it's functions
import math_operators
print(math_operators.add(3, 4))
print(math_operators.subtract(9, 7))
print(math_operators.multiply(2, 3))

# Output
# 7
# 2
# 6

10.3.0 The Builtin Math functions are:

Python builtin functions 1. Python builtin functions 2.

Simple math operators in order of precedence.

Python operators.

10.4.0 Default Value for a Function Parameter

If you see a parameter equal to a value in the declaration of a function, it is the default value. In the following example, if there is no argument for mynumber() then the value is 50.

#Default value for a parameter
def mynumber(number = 50):   # Default parameter is 50
   return str(number)
print(mynumber(15))    # Returns 15
print(mynumber())    # Returns 50

Win-Python Navigation

Table of Contents
Ch1-Install Python
Ch2-Install PyCharm
Ch3-Save Work
Ch4-Add Project
Ch11-Bubble Sort
Ch14-Print Format