Introduction to Computing Lecture 4 28 August 2019
Introduction to Computing
Lecture 4
28 August 2019
Review of last lecture
Last time we discussed:
I Boolean datatype bool.I Boolean operators: and, or, not.I Relational operators: >, <, >=, <=, ==, !=.I Sequential and conditional control.I if, else and elif statements.I Indentation.
Program routines
I In order to manage the complexity of a large problem, it isoften broken down into smaller subproblems.
I Then, each subproblem can be focused on and solvedseparately.
I In programming, we do the same thing. Programs are dividedinto manageable pieces.
I In Python this is done using functions.
Program routines
I In order to manage the complexity of a large problem, it isoften broken down into smaller subproblems.
I Then, each subproblem can be focused on and solvedseparately.
I In programming, we do the same thing. Programs are dividedinto manageable pieces.
I In Python this is done using functions.
Program routines
I In order to manage the complexity of a large problem, it isoften broken down into smaller subproblems.
I Then, each subproblem can be focused on and solvedseparately.
I In programming, we do the same thing. Programs are dividedinto manageable pieces.
I In Python this is done using functions.
Program routines
I In order to manage the complexity of a large problem, it isoften broken down into smaller subproblems.
I Then, each subproblem can be focused on and solvedseparately.
I In programming, we do the same thing. Programs are dividedinto manageable pieces.
I In Python this is done using functions.
Functions in PythonLet us start with an example:
def angle(s1, s2, s3):A = math.acos((s1**2 + s2**2 - s3**2)/(2*s1*s2))return 180*(A / math.pi)
This is a function with takes three side lengths of a triangle asarguments and returns the angle opposite to side 3.
Syntax
def <function name> (parameters...):.........
Functions in PythonLet us start with an example:
def angle(s1, s2, s3):A = math.acos((s1**2 + s2**2 - s3**2)/(2*s1*s2))return 180*(A / math.pi)
This is a function with takes three side lengths of a triangle asarguments and returns the angle opposite to side 3.
Syntax
def <function name> (parameters...):.........
Functions in PythonLet us start with an example:
def angle(s1, s2, s3):A = math.acos((s1**2 + s2**2 - s3**2)/(2*s1*s2))return 180*(A / math.pi)
This is a function with takes three side lengths of a triangle asarguments and returns the angle opposite to side 3.
Syntax
def <function name> (parameters...):.........
Function Exampleangle.py
def angle(s1, s2, s3):A = math.acos((s1**2 + s2**2 - s3**2)/(2*s1*s2))return 180*(A / math.pi)
print("Enter the lengths of sides of a triangle.")a = float(input("side 1: "))b = float(input("side 2: "))c = float(input("side 3: "))
import mathA = angle(b, c, a)B = angle(c, a, b)C = angle(a, b, c)
print("The angles of the triangle in degrees are:",format(A, '.2f'), format(B, '.2f'), format(C, '.2f'))
Function terminologyI The variables listed inside brackets while defining a function are
called formal parameters or simply parameters.The parameters for angle are s1, s2, s3.
I Parameters can be of any of the datatypes, int, float,str, bool. We can define a function which does not have anyparameters whatsoever.
I Using a function inside the program is termed calling thefunction. A function can be called only after it has beendefined.
I While calling a function the exact same number of values haveto be passed as the number of parameters of the function.
I The values passed to a function when calling it are called theactual arguments or simply arguments.
Go back to the previous slide.
Function terminologyI The variables listed inside brackets while defining a function are
called formal parameters or simply parameters.The parameters for angle are s1, s2, s3.
I Parameters can be of any of the datatypes, int, float,str, bool. We can define a function which does not have anyparameters whatsoever.
I Using a function inside the program is termed calling thefunction. A function can be called only after it has beendefined.
I While calling a function the exact same number of values haveto be passed as the number of parameters of the function.
I The values passed to a function when calling it are called theactual arguments or simply arguments.
Go back to the previous slide.
Function terminologyI The variables listed inside brackets while defining a function are
called formal parameters or simply parameters.The parameters for angle are s1, s2, s3.
I Parameters can be of any of the datatypes, int, float,str, bool. We can define a function which does not have anyparameters whatsoever.
I Using a function inside the program is termed calling thefunction. A function can be called only after it has beendefined.
I While calling a function the exact same number of values haveto be passed as the number of parameters of the function.
I The values passed to a function when calling it are called theactual arguments or simply arguments.
Go back to the previous slide.
Function terminologyI The variables listed inside brackets while defining a function are
called formal parameters or simply parameters.The parameters for angle are s1, s2, s3.
I Parameters can be of any of the datatypes, int, float,str, bool. We can define a function which does not have anyparameters whatsoever.
I Using a function inside the program is termed calling thefunction. A function can be called only after it has beendefined.
I While calling a function the exact same number of values haveto be passed as the number of parameters of the function.
I The values passed to a function when calling it are called theactual arguments or simply arguments.
Go back to the previous slide.
Function terminologyI The variables listed inside brackets while defining a function are
called formal parameters or simply parameters.The parameters for angle are s1, s2, s3.
I Parameters can be of any of the datatypes, int, float,str, bool. We can define a function which does not have anyparameters whatsoever.
I Using a function inside the program is termed calling thefunction. A function can be called only after it has beendefined.
I While calling a function the exact same number of values haveto be passed as the number of parameters of the function.
I The values passed to a function when calling it are called theactual arguments or simply arguments.
Go back to the previous slide.
Function terminologyI The variables listed inside brackets while defining a function are
called formal parameters or simply parameters.The parameters for angle are s1, s2, s3.
I Parameters can be of any of the datatypes, int, float,str, bool. We can define a function which does not have anyparameters whatsoever.
I Using a function inside the program is termed calling thefunction. A function can be called only after it has beendefined.
I While calling a function the exact same number of values haveto be passed as the number of parameters of the function.
I The values passed to a function when calling it are called theactual arguments or simply arguments.
Go back to the previous slide.
Mathematical functionsI Polynomial function f (x , y) = 3x2 + 4xy + 6y2:
def f(x, y):return 3*(x**2) + 4*x*y + 6*(y**2)
I Piecewise function
u(x) =
exp(−1/x) if x > 0− exp(1/x) if x < 00 if x = 0.
def u(x):if x == 0:
return 0else:
return (x/abs(x)) * math.exp(-1/abs(x))
Mathematical functionsI Polynomial function f (x , y) = 3x2 + 4xy + 6y2:
def f(x, y):return 3*(x**2) + 4*x*y + 6*(y**2)
I Piecewise function
u(x) =
exp(−1/x) if x > 0− exp(1/x) if x < 00 if x = 0.
def u(x):if x == 0:
return 0else:
return (x/abs(x)) * math.exp(-1/abs(x))
Function that returns a string:
def type_of_platonic_solid(num_sides):if num_sides == 4:
type = "Tetrahedron"elif num_sides == 6:
type = "Cube"elif num_sides == 8:
type = "Octahedron"elif num_sides == 12:
type = "Dodecahedron"elif num_sides == 20:
type = "Icosahedron"else:
type = "Not a platonic solid."
return type
Function that returns a boolean
def is_prime_less_than_25(n):if (n >= 25) or (n <= 1):
return Falseelif (n == 2) or (n == 3):
return Trueelif (n%2 == 0) or (n%3 == 0):
return Falseelse:
return True
Some built-in function
I abs(), bin(), hex(), oct(), len(), max(), min(). . .
I int(), float(), str(), chr(), bool(), ord() . . .
I input(), print(), format() . . .
I math.cos, math.sin, math.acos, math.asin . . .
I keyword.iskeyword()
Some built-in function
I abs(), bin(), hex(), oct(), len(), max(), min(). . .
I int(), float(), str(), chr(), bool(), ord() . . .
I input(), print(), format() . . .
I math.cos, math.sin, math.acos, math.asin . . .
I keyword.iskeyword()
Some built-in function
I abs(), bin(), hex(), oct(), len(), max(), min(). . .
I int(), float(), str(), chr(), bool(), ord() . . .
I input(), print(), format() . . .
I math.cos, math.sin, math.acos, math.asin . . .
I keyword.iskeyword()
Some built-in function
I abs(), bin(), hex(), oct(), len(), max(), min(). . .
I int(), float(), str(), chr(), bool(), ord() . . .
I input(), print(), format() . . .
I math.cos, math.sin, math.acos, math.asin . . .
I keyword.iskeyword()
Some built-in function
I abs(), bin(), hex(), oct(), len(), max(), min(). . .
I int(), float(), str(), chr(), bool(), ord() . . .
I input(), print(), format() . . .
I math.cos, math.sin, math.acos, math.asin . . .
I keyword.iskeyword()
Value-returning functions
So far we have mostly seen functions which always gives an output.Such functions are called value-returning functions.
This is achieved using the return keyword.
Syntax
return <value>
The returned value can be used elsewhere in the program.
Value-returning functions
So far we have mostly seen functions which always gives an output.Such functions are called value-returning functions.
This is achieved using the return keyword.
Syntax
return <value>
The returned value can be used elsewhere in the program.
Value-returning functions
So far we have mostly seen functions which always gives an output.Such functions are called value-returning functions.
This is achieved using the return keyword.
Syntax
return <value>
The returned value can be used elsewhere in the program.
Value-returning functions
So far we have mostly seen functions which always gives an output.Such functions are called value-returning functions.
This is achieved using the return keyword.
Syntax
return <value>
The returned value can be used elsewhere in the program.
Non-value-returning functions
Functions may also not return any value. For example the print()function.
I Such functions are called non-value-returning functions andthey do not have a return statement.
I These functions are used to perform a certain task within aprogram.
Non-value-returning functions
Functions may also not return any value. For example the print()function.
I Such functions are called non-value-returning functions andthey do not have a return statement.
I These functions are used to perform a certain task within aprogram.
Non-value-returning functions
Functions may also not return any value. For example the print()function.
I Such functions are called non-value-returning functions andthey do not have a return statement.
I These functions are used to perform a certain task within aprogram.
Example - Determinant
determinant.py
# Determinant of a small matrix
def det_2(a, b, c, d): # Determinant of 2X2 matrixreturn a*d - b*c
# Determinant of 3X3 matrix
def det_3(a11, a12, a13, a21, a22, a23, a31, a32, a33):determinant = 0determinant += a11 * det2(a22, a23, a32, a33)determinant += - a12 * det2(a21, a23, a31, a33)determinant += a13 * det2(a21, a22, a31, a32)return determinant
Example - Determinant continued
# Print matrices
def print_matrix2(a, b, c, d):print('[', format(a,'>5'), format(b, '>5'), ']')print('[', format(c,'<5'), format(d, '>5'), ']')
def print_matrix3(a11, a12, a13, a21, a22, a23, a31, a32, a33):print('[', format(a11,'<5'), format(a12, '^5'),
format(a13, '>5'), ']')print('[', format(a21,'<5'), format(a22, '^5'),
format(a23, '>5'), ']')print('[', format(a31,'<5'), format(a32, '^5'),
format(a33, '>5'), ']')
Example - Determinant continued
# Main
n = int(input("Enter the order of a sqaure matrix: "))
if n == 2:print("Enter a 2X2 matrix:\n")a = float(input("Entry (1,1): "))b = float(input("Entry (1,2): "))c = float(input("Entry (2,1): "))d = float(input("Entry (2,2): "))print("Determinant of")print_matrix2(a, b, c, d)print("is", det_2(a, b, c, d))
Example - Determinant continuedelif n == 3:
print("Enter a 3X3 matrix:\n")a11 = float(input("Entry (1,1): "))a12 = float(input("Entry (1,2): "))a13 = float(input("Entry (1,3): "))a21 = float(input("Entry (2,1): "))a22 = float(input("Entry (2,2): "))a23 = float(input("Entry (2,3): "))a31 = float(input("Entry (3,1): "))a32 = float(input("Entry (3,2): "))a33 = float(input("Entry (3,3): "))print("Determinant of")print_matrix3(a11, a12, a13, a21, a22, a23, a31, a32, a33)print("is",
det_3(a11, a12, a13, a21, a22, a23, a31, a32, a33))else:
print("Matrix too big for this program.")
Variables within a function
A variable which is assigned a value within a function is notavailable outside the function.
Consider the program: variable_scope.py
# Function to convert angles in radians to degrees
def angle360(angle_in_radians):n = angles_in_radians//(2*math.pi)angle_in_radians -= n * (2 * math.pi)angle_in_degrees = 180 * (angle_in_radians / math.pi)return angles_in_degrees
Variables within a function
# Main
A = float(input("Enter an angle in radians: "))B = angle360(A)print(A, "radians in degrees is", format(B, ".2f"))
input("Press enter to continue.")
print("What happens if we print angle_in_degrees",angle_in_degrees)
print("What happens if we print angle_in_radians",angle_in_radians)
print("What happens if we print n", n)
Variables outside a functionVariables outside a function are not changed if you assign a variablewith the same identifier inside a function. For instance spiderman.py
A = "Spiderman"
def Home():A = "Peter Parker"print("At home I am", A)
Home()print("But outside I am", A)
Produces the output
At home I am Peter ParkerBut outside I am Spiderman
Variables outside a functionVariables outside a function are not changed if you assign a variablewith the same identifier inside a function. For instance spiderman.py
A = "Spiderman"
def Home():A = "Peter Parker"print("At home I am", A)
Home()print("But outside I am", A)
Produces the output
At home I am Peter ParkerBut outside I am Spiderman
Salient features about functions to remember
I A function can be called only after it has been defines.
I Functions may or may not return a value.
I Variables passed on to functions as arguments do not changetheir values even if they get manipulated inside the function.
I Variables inside a function can not be accessed outside thefunction.
I Variables outside a function can be accessed inside the functiononly if there is no variable asigned in the function with thesame identifier.
Salient features about functions to remember
I A function can be called only after it has been defines.
I Functions may or may not return a value.
I Variables passed on to functions as arguments do not changetheir values even if they get manipulated inside the function.
I Variables inside a function can not be accessed outside thefunction.
I Variables outside a function can be accessed inside the functiononly if there is no variable asigned in the function with thesame identifier.
Salient features about functions to remember
I A function can be called only after it has been defines.
I Functions may or may not return a value.
I Variables passed on to functions as arguments do not changetheir values even if they get manipulated inside the function.
I Variables inside a function can not be accessed outside thefunction.
I Variables outside a function can be accessed inside the functiononly if there is no variable asigned in the function with thesame identifier.
Salient features about functions to remember
I A function can be called only after it has been defines.
I Functions may or may not return a value.
I Variables passed on to functions as arguments do not changetheir values even if they get manipulated inside the function.
I Variables inside a function can not be accessed outside thefunction.
I Variables outside a function can be accessed inside the functiononly if there is no variable asigned in the function with thesame identifier.
Salient features about functions to remember
I A function can be called only after it has been defines.
I Functions may or may not return a value.
I Variables passed on to functions as arguments do not changetheir values even if they get manipulated inside the function.
I Variables inside a function can not be accessed outside thefunction.
I Variables outside a function can be accessed inside the functiononly if there is no variable asigned in the function with thesame identifier.