Chapter 4 - Introductory Python Custom and

Builtin Functions



AD

4.1 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 arguments

#Output
# 2
# 6
# 99

4.2 Python Builtin Functions

There are many built in 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.sin(math.radians(90)))
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 math_operators.py. 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 definitions in module called math_operators.py
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

4.2.1 The Builtin Math functions are:

Python builtin functions 1. Python builtin functions 2.

Simple math operators in order of precedence.

Python operators.

4.3 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

theSurfDragon.com


Win-Python Navigation

Table of Contents
Ch1-Starting Out
Ch2-Loops
Ch3-If Statements
Ch4-Functions
Ch5-Variable Scope
Ch6-Bubble Sort
Ch7-Intro to OOP
Ch8-Inheritance
Ch9-Plotting
Ch10-Files
Ch11-Print Format
Ch12-Dict-Zip-Comp
Ch13-Slice Arrays