In this ICS3U Grade 11 Computer Science lesson you will be learning to:
You are going to learn about a problem solving technique called Top Down Analysis and Stepwise Refinement.
Example of Modular Design
Suppose you were asked to find the median of a list of numbers. Remember the median is the middle number in an ordered list. The modules needed to solve the problem might be
Input the list
Sort The Data Module
Swap Module
Pick Middle Module
Average Module
Output Results
When using modular programming, your code will generally look as follows:
Usually we use the term function in python to represent a module. You might hear them called methods as well. (There is a difference, but it has to do with some more advanced topics in Object Oriented Programming, which is part of the ICS4U Course) You have already used a lot of python functions when writing your previous programs.
These are functions that execute code internally (that you can’t see) but you can learn how to use. The print function might have 20 lines of code in it, so imagine how long and confusing your programs would be if you had to write those 20 lines every time you wanted to print something.
We want to be able to create our own functions that accomplish very small and specific tasks.
Before a function can be usedd, it must be defined. That is, you define the rules of how the function will behave when used. – A function contains a header and a body
The Header
Sets up the name of the function, it might also have a parameter list
The Body
Contains the code to accomplish the task of function.
Suppose you wanted to create a program that calculates a bunch of slopes of different line segments.
It would be useful in this program to create a function that calculated the slope of a line given two points (x1,y1) and (x2,y2). In order to accomplish this task, you would use the following formula
$$ x = \frac {y2-y1}{x2-x1} $$
The function needs to accept those 4 values to it and it needs to send the answer back to the main program so that answer could be used in some way afterwards
Type the following code into the Python Editor and run the program with different values for inputs
#Function Definitions
def slope(x1,y1,x2,y2):
m = (y2 - y1) / (x2 - x1)
return m
#Main Program that solves a problem
def main():
while True:
#Get points from the user
point1x = float(input("Enter x1: "))
point1y = float(input("Enter y1: "))
point2x = float(input("Enter x2: "))
point2y = float(input("Enter y2: "))
#Send values to the function to process and get answer
userSlope = slope(point1x,point1y,point2x,point2y)
#Output values
print("Your line has a slope of: ", userSlope)
#Stop?
choice = input("Stop? Enter Yes, otherwise hit enter to continue")
if choice.upper() == "YES":
break
#Call the main function to start your code running
main()
The program reads all the function definitions at the top of the program first so when they are called in the future, it knows what to do with it.
The main part of the program is where you are solving a problem, just like you have always done.
To start your program, you just have to call the main function.
Not all functions would necessarily need to return a value. Here is the definition of a function that prints out your credentials. This might be useful at the bottom of an email to save the user from having to type his contact information
def signature():
print("Teacher Name")
print("905 - 555 -5555")
print("teacher@school.com")
Here is a definition of a function that prints out values of a list, one per line.
def printList(l):
for i in range(0,len(l)):
print(l[i])
They would be called just the same as every other function, but no need to assign them to a variable
#Main Program
def main():
myList = [3,4,5,6,7]
#Call printlist Function
printList(myList)
#Call signature Function
signature()
Here are some other list and string functions that might be useful as well when solving problems
Changing a list to a String
def listToString(l):
s = ""
for i in range(0,len(l)):
s = s + l[i]
return s
Changing a String to a list
def stringToList(s):
l = []
for i in range(0, len(s)):
l.append(s[i])
return l
Exchanging the Position of items in a list
def swapList(l,a,b):
temp = l[a]
l[a] = l[b]
l[b] = temp
return l
Copy the function definitions above into the Python Editor. Write a main program that tests their function
#Function Definitions
def listToString(l):
s = ""
for i in range(0,len(l)):
s = s + l[i]
return s
#Main Program to Test
def main():
myList = ["H","i"]
stringEquivalent = listToString(myList)
print(stringEquivalent)
#Call main to start the program
main()
#Function Definitions
def stringToList(s):
l = []
for i in range(0, len(s)):
l.append(s[i])
return l
#Main Program to Test
def main():
myString = input("Enter a word: ")
listEquivalent = stringToList(myString)
print(listEquivalent)
#Call main to start the program
main()
#Function Definitions
def swapList(l,a,b):
temp = l[a]
l[a] = l[b]
l[b] = temp
return l
#Main Program to Test
def main():
myList = [20,30,70,50,60,100,10,40]
#Swap 30 and 60
myList = swapList(myList,1,4)
print(myList)
#Call main to start the program
main()
Suppose you have been asked to write a program that mixes up the characters in a String
The general solution could look something like this:
Type the following code into the Python Editor and run the program with different values for inputs
#Import statements
import random
#Function Definitions
def listToString(l):
s = ""
for i in range(0,len(l)):
s = s + l[i]
return s
def swapList(l,a,b):
temp = l[a]
l[a] = l[b]
l[b] = temp
return l
def stringToList(s):
l = []
for i in range(0, len(s)):
l.append(s[i])
return l
#Main Program to mix up a word
def main():
word = input("Enter the Word to Mix Up: ")
#Make swaps equal to the length of the word
for i in range (0, len(word)):
#Turn String into a list
charList = stringToList(word)
#Get Random Positions
position1 = random.randint(0,len(word)-1)
position2 = random.randint(0,len(word)-1)
#Swap Positions
swappedList = swapList(charList, position1, position2)
#Rebuild to a string
word = listToString(swappedList)
#Output final mixed up word
print("The mixed up word is: ", word)
#Call main to start the program
main()
The main strategy behind this program is that you
You can then repeat this process multiple times until you get it mixed up adequately. I decided that mixing as many times as the length of the string was going to be good enough
This problem solving strategy is reflected in the main function
In order to accomplish that task, I wrote 3 functions
Function #1 – stringToList
Function #2 – swapList
Function #3 – listToString
Watch a video of your teacher summarizing the learning content for this section
Not all variables can be accessed from anywhere in a program. The part of a program where a variable is accessible is called its scope.
Whenever you define a variable within a function, its scope lies ONLY within the function. It is accessible from the point at which it is defined until the end of the function and exists for as long as the function is executing. Which means its value cannot be changed or even accessed from outside the function.
Type the following code into the Python Editor, run the program and observe the error
#Function Definitions
def sampleFunction():
print(x)
#Main Program
def main():
x = 5
sampleFunction()
#Call main to start the program
main()
The variable x is created inside the main function. Its scope is local to main. No other function outside of main knows that it exists.
You can use the same variable names inside different functions. Python treats those as completely separate variables even though they have the same name
Type the following code into the Python Editor, run the program and observe how the functions treat the variable x
#Function Definitions
def sampleFunction():
x = 3
print("x is", x, "in the sample function")
#Main Program
def main():
x = 5
print("x is", x, "in main")
sampleFunction()
print("x is", x, "in main even after changing it in the function")
#Call main to start the program
main()
Whenever a variable is defined outside any function, it becomes a global variable, and its scope is anywhere within the program. Which means it can be used by any function.
Type the following code into the Python Editor, run the program and observe how the functions treat the variable x
#Global Variables
x = 5
#Function Definitions
def sampleFunction():
print("x is", x, "in the sample function")
#Main Program
def main():
print("x is", x, "in main")
sampleFunction()
#Call main to start the program
main()
If there is a global variable and a local variable with the same name, then python will default to use the local scope version of that varaible
Type the following code into the Python Editor, run the program and observe how the functions treat the variable x
#Global Variables
x = 5
#Function Definitions
def sampleFunction():
x = 3
print("x is", x, "in the sample function")
#Main Program
def main():
sampleFunction()
print("x is", x, "in main")
#Call main to start the program
main()
This can become a problem if you want to change the value of a global variable in a function. If in the last example the goal was to change the value of the global variable x to 3, then it would fail.
Type the following code into the Python Editor, run the program and observe how the functions treat the variable x
#Global Variables
x = 5
#Function Definitions
def sampleFunction():
global x
x = 3
print("x is", x, "in the sample function")
#Main Program
def main():
sampleFunction()
print("x is", x, "in main")
#Call main to start the program
main()
Watch a video of your teacher summarizing the learning content for this section
Try to code the following ICS3U questions using an IDE of your choice (Spyder, IDLE, Pycharm, etc). You will save those files on your computer for future reference.
Each question has:
Try your best to solve the problems yourself without looking at the solutions.
Make sure you test your programs with multiple different inputs to ensure it is functioning properly.
Name Your File: “ICS3UaddBetween.py”
Write a function that calculates the sum of all the integers between 2 values (inclusive). Accept two numbers as parameters and retun the sum. Write a main program that illustrates the function working
#Function Definitions
def sumBetween(a,b):
total = 0
for i in range(a,b+1):
total = total + i
return total
#Main Program
def main():
start = int(input("Enter first value: "))
end = int(input("Enter last value: "))
added = sumBetween(start,end)
print("The sum of the integers between those numbers is: ",added)
#Call main to start the program
main()
Name Your File: “ICS3UfactorialSum.py”
Let’s take a look at a factorial
Write a program that calculates the sum of all factorials entered by the user. Your program should ask the user to enter as many factorials as they would like and add up the sum of all those factorials. (Entering zero should signal the program to stop)
For example, If the user entered 4 factorials: 3!, 5!, 8! And 2! It would add 6 + 120 + 40320 + 2 = 40448
You must write a function called factorial to accomplish this task. It should accept the number as a parameter and return the resultant factorial.
#Function Definitions
def factorial(x):
f = 1
for i in range(2,x+1):
f = f * i
return f
#Main Program
def main():
total = 0
while True:
num = int(input("Enter a number: (zero to stop) "))
if num == 0:
break
else:
total = total + factorial(num)
print("\nThe sum of all the factorials is: ", total)
#Call main to start the program
main()
Name Your File: “ICS3UlowestTerms.py”
Write a function that accepts a positive fraction “n/d” as a String and returns another fraction “n/d” in lowest terms
You are going to need to implement a Greatest Common Divisor Algorithm. Don’t use the built in one. Write one yourself that takes two numbers and finds the largest number that divides into both.
#Function Definitions
#Finds the greatest common divisor between 2 integers
def gcd(a,b):
#Largest divisor 1 -> if no other ones found
g = 1
#start search for divisors at the smallest number
if a>b:
start = b
else:
start = a
#Count backwards to find the largest divisor
for i in range (start,1,-1):
#Found largest divisor so stop
if a % i == 0 and b % i == 0:
g = i
break
return g
#Converts a fraction to lowest terms (fraction is a string n/d)
def convert(fraction):
#Get the numbers from the string
nd = fraction.split("/")
numerator = int(nd[0])
denominator = int(nd[1])
#Calculate the greatest common divisor
divisor = gcd(numerator,denominator)
#Reduce the fraction
numerator = numerator//divisor
denominator = denominator//divisor
#Return a new fraction as a string
return str(numerator) + "/"+ str(denominator)
#Main Program
def main():
f = input("Enter fraction (n/d): ")
reduced = convert(f)
print("Lowest Terms: ", reduced)
#Call main to start the program
main()
Name Your File: “ICS3UcountPrimes.py”
Write a function that will determine if an integer is a prime number. It should accept an integer as a parameter and return either True or False if that number is prime. Use it to find the first 200 prime numbers
#Function Definitions
def isPrime(x):
#1 is not a prime #
if x == 1:
prime = False
else:
#Assume it's prime unless it finds a divisor
prime = True
for i in range(2,x):
#If it finds a divisor its not prime
if x % i == 0:
prime = False
break
return prime
#Main Program
def main():
#The number of primes found
count = 0
#The number being tested for prime
num = 1
#loop until finding 200 prime #'s
while count < 200:
#Found a prime so increase count
if isPrime(num):
count = count + 1
print(num)
#Check next number
num = num + 1
#Call main to start the program
main()