Lesson 3.12 & 3.13
- Topic 3.12 (3.A) Calling & Understanding Procedures - Kaiden & Amay
- Topic 3.13 (3.B) Managing Complexity - Safin
- Topic 3.13 (3.C) Developing Procedures - David & Alex
- Hacks
Topic 3.12 (3.A) Calling & Understanding Procedures - Kaiden & Amay
Overview: Learning Objectives
- Basics of Procedures
- Calling Procedures
- Determine Results of Procedures
What is a procedure?
Essential Knowledge:
- A procedure is a named set of instructions that can take in parameters and return values.
- May be called "method" or "function" in different programming languages.
- Parameters are independent variables used in the procedure to produce a result. It allows a procedure to execute without initially knowing specific input values.
- Procedures can be classified as sequencing, selection, and iteration. How?
Example:
- What is the procedure's name?
- What are the parameters?
- What did the procedure return?
x = 5
y = 3
def multiply(x, y):
product = x * y
return product
answer = multiply(x, y)
print("The product of", x, "times", y, "is", answer)
num = 5
def math(x):
op1 = x * 2
op2 = op1 - 9
return op2
questionNum = 3
correct = 0
questions = [
"What is are correct names for a procedure? \n A) Method \n B) Function \n C) Both",
"What is a procedure? \n A) Sequencing \n B) Selection \n C) Iteration \n D) All",
"Use this for following question: \n def inchesToFeet(lengthInches): \n\t lengthFeet = lengthInches / 12 \n\t return lengthFeet \n\n What is the procedure name, the parameter, and what the procedure returns? \n A) feetToInches, lengthInches, lengthMeters \n B) inchesToFeet, lengthInches, lengthFeet \n C) inchesToFeet, lengthFeet, lengthInches \n D) lengthInches, inchesToFeet, lengthFeet"]
answers = ["c", "d", "b"]
def qna(question, answer):
print("Question:", question)
response = input()
print("Answer:", response)
if response.lower() == answer:
print("Correct :) \n")
global correct
correct += 1
else:
print("Incorrect :( \n")
for x in range(questionNum):
qna(questions[x], answers[x])
print("Score:", correct, "/ 3")
Determining the Result of a Procedure
-
To determine the result of a procedure or any code, you must follow the code line by line and see what each one does
-
Using syntax, you can determine the result by
- function parameters
- return value and statements
- To use return values, you have to write the syntax return followed by the expression you would like to return var
-
A return statement exits a function and instructs python to continue executing the program and to return a certain value
-
Value can be string, a tuple, or any other type that is being sent back to the main program
Ex:
def divide(num1,num2):
x = num1/num2
return x
-
what is x being assigned to inside the function?
-
As a reminder, to use function parameters, you would have to write the syntax name of the function followed by the parameters needed in parentheses
-
Function parameters are the parameters that are used when calling the function in order to get a result.
What are the function parameters in this procedure?
What values are being passed to the function?
def function(first_name, last_name):
print(first_name + " " + last_name)
function("Peter","Parker")
function("Safin", "Singh")
In the cell above, the function is being called twice, which shows the importance of function in order to accomplish the same thing with different parameters.
What is wrong with the function?
Can you translate the binary numbers into decimal notation?
def find_cube(num):
result = bin(num * num * num)
cube = find_cube(3)
cube2 = find_cube(4)
print('Cube:',cube)
print('Cube:',cube2 )
Once again, I called the function twice, which is useful, because it allows the coder to do the same thing multiple times with different arguments.
Topic 3.13 (3.B) Managing Complexity - Safin
Overview: Learning Objectives
- increasing code modularity using procedures
- abstracting large problems into smaller ones
- extract shared features to reduce code duplication
- using parameters to reuse procedures
- improving code readability with procedures
- manipulating procedure logic and preserving output
Essentially, we'll learn how and when it is appropriate to construct a function (procedural abstraction) and what its benefits are
- Modularity - the practice of breaking a complex program into smaller, independent parts or modules that can be used and reused in different parts of the program
- Abstraction - the practice of hiding the details of how a particular code or system works and exposing only the essential features or functions that are necessary for other parts of the program to use
- Duplication - having multiple duplicate code blocks, often decreasing readability and efficiency
- Logic - the sequence of steps and operations that a computer follows to execute a program, including the specific instructions and decision-making processes built into the code
Parameters
As we saw above, parameters can be used to make functions work with multiple different inputs. Let's review the following code
# these parameters are the inputs to the function, and they are used
# inside the function to perform some operation
def add(x, y):
# inside the function, we can use the x and y parameters just like
# we would use any other variable
result = x + y
return result
# to call the function and pass in values for the x and y parameters,
# we simply provide the values as arguments in the function call
result = add(2, 3)
print(result) # should output 5
# we can also use variables as arguments in the function call
x = 5
y = 10
result = add(x, y)
print(result) # should output 15
# we can even use the result of one function call as an argument
# in another function call
result = add(add(2, 3), add(4, 5))
print(result) # should output 14
import math
def hypotenuse(leg1, leg2):
# notice we're using this <var> * <var> syntax multiple times?
# this has multiple drawbacks:
# - it's repetitive and makes the code longer
# - if we wanted to change the operator being
# applied to `leg1` and `leg2`, we'd have to do it twice!
leg1_squared = leg1 * leg1
leg2_squared = leg2 * leg2
return math.sqrt(leg1_squared + leg2_squared)
## VERSUS ##
# this works, but let's try to write the "squared" variable assignment statements more concisely...
def square(a):
return a * a
def hypotenuse_abstracted(leg1, leg2):
# not only is this shorter, but we can now:
# - better understand the code at a glance--we know exactly
# what `square` should do
# - change the operator in a single place (`square`) rather than
# multiple times within this hypotenuse function
leg1_squared = square(leg1)
leg2_squared = square(leg2)
return math.sqrt(leg1_squared + leg2_squared)
## EXTRA CHALLENGE ##
# is it possible to write the `hypotenuse` function in a single line?
def hypotenuse_abstracted2(leg1, leg2):
# ...
pass
assert hypotenuse(3, 4) == hypotenuse_abstracted(3, 4) == 5
Abstracting Shared Features
Say we want to create a set of functions that count the number of words in a sentence that start with a certain character. We want to create...
count_words_starting_with_a_in_string(sentence)
count_words_starting_with_d_in_string(sentence)
In order to count words starting with a certain character, we'll first need to split up the sentence into words. This behavior will be shared across both functions we intend to create, so procedural abstraction is appropriate here.
# is a separate element in the list
def split_string(s):
# use the split() method to split the string into a list of words
words = s.split(" ")
# initialize a new list to hold all non-empty strings
new_words = []
for word in words:
if word != "":
# add all non-empty substrings of `words` to `new_words`
new_words.append(word)
return words
# this function takes a list of words as input and returns the number of words
# that start with the given letter (case-insensitive)
def count_words_starting_with_letter(words, letter):
count = 0
# loop through the list of words and check if each word starts with the given letter
for word in words:
# use the lower() method to make the comparison case-insensitive
if word.lower().startswith(letter):
count += 1
return count
# this function takes a string as input and returns the number of words that start with 'a'
def count_words_starting_with_a_in_string(s):
# use the split_string() function to split the input string into a list of words
words = split_string(s)
# use the count_words_starting_with_letter() function to count the number of words
# that start with 'a' in the list of words
count = count_words_starting_with_letter(words, "a")
return count
# see above
def count_words_starting_with_d_in_string(s):
words = split_string(s)
count = count_words_starting_with_letter(words, "d")
return count
# example usage:
s = " This is a test string! Don't you think this is cool? "
a_count = count_words_starting_with_a_in_string(s)
d_count = count_words_starting_with_d_in_string(s)
print("Words starting with a:", a_count)
print("Words starting with d:", d_count)
In the above example, we have:
- defined several functions that perform different tasks related to processing a string
- abstracted away shared behavior for both functions that count the number of words starting with a specific character in a string
Topic 3.13 (3.C) Developing Procedures - David & Alex
Overview: Learning Objectives
- parameters being used to manage complexity
- parameters storing variables
- parameters storing arguments
- calling functions with procedure names
- choosing procedure names
- calling procedures in python and javascript
Vocabulary:
- Procedure - a module of code that is created to complete a certain task, this is basically a function
- Procedure Name - the name that is given to a function/procedure
- Parameters - a variable that is used in a function to allow for data to be imported into a function
- Arguments - a way to provide information to a function, usually defined outside a function and then imported into a function with parameters
Functions - Basic Structure
Functions can be created in many different languages. Below are some examples in Collegeboard's format, Python, and Javascript.
Collegeboard
Above, the function is defined as PROCEDURE
, which tells the coder that this is a function. The function is then named with procName
, which is simply how the function is identified. parameter1, parameter2,...
are variables that can be predefined elsewhere and repeatedly used in the same function. This will be gone over later in the lesson so don't worry if you don't get it. block of statements
are just things that you would place inside a function to complete a certain task, such as print()
in Python.
Python
def function(a,b): # function is defined
print(a+b) # prints output of variables
function(1,2) # one instance that it can be used
function(2,3) # another instance
3
5
Python is similar to the Collegeboard example, where def
defines the function, function
, and then is followed by parameters a,b
, which can later be interchanged with any numbers as shown with function(1,2)
. The numbers are called arguments, which are information provided to the function with parameters. In this case, the parameters are being added within the function and then printed.
Javascript
function Function(a,b) {
return a + b;
}
Function(1,2)
Function(2,3)
3
5
Javascript in this case is almost the exact same as Python, the only differences being that function is called with function
and that the formatting is a little different. Otherwise, it does the exact same thing as the Python example.
Example
function div(a,b) {
return (a+b)/2
}
div(3,7)
- What is the procedure name?
- What are the parameters?
- What operation is being done?
- what would the output of this code be?
def function(num1, num2):
if num1 > num2:
print("num1 is greater than num2")
elif num1 <num2:
print("num1 is less than num 2")
num1= 6
num2 = 8
function(num1,num2)
- In this
function
, it takes in two parametersnum1
andnum2
- Whithin this function it uses conditionals to determine if num 1 is larger or smaller than num2
- When calling to this
function
we must put in two arguements, num1 and num2 respectively - We put in 6 for num1 and 8 for num2 and the algorithm runs and gives us an outcome
This basic function in python can be recreated in Javasript
function compare(a,b) {
if(a>b) {
console.log("a is greater than b")
} else if (a<b) {
console.log("a is less than b")
}
}
// How do you call to this function?
- what are the parameters?
- What is the output?
- what are the arguements?
Calling functions
- When calling functions, you have to ask yourself some questions
- Does the function have any parameters?
- does the parameter have output?
- Depending on these answers, the way you will call to a function will be different
Example where it does does have parameters and gives output
def InchestoFeet(inches):
Feet = 0
Feet = inches / 12
return Feet
result = InchestoFeet(24)
print(result)
2
- If you look closely, there is a
return
at the end of the function, this returns a value when you call the function - This is why we have to set a variable, in this case
result
equal to the output of the function. - Also one thing to notice is that this function also takes in a parameter called inches
Here's an example of calling functions in HTML with Javascript:
<!-- function is called here -->
<button id="enter" onclick="print(a,b)">HI</button>
<p id="result"></p>
<!-- javascript -->
<script>
function print(a,b) {
document.getElementById("result").innerHTML = a + b // math
}
// variables are defined
var a = 1
var b = 2
</script>
Hacks
Topic 3.12 (3.A):
- Define procedure and parameter in your own words
- Paste a screenshot of completion of the quiz
- Define Return Values and Output Parameters in your own words
- Code a procedure that finds the square root of any given number. (make sure to call and return the function)
Topic 3.13 (3.B):
- Explain, in your own words, why abstracting away your program logic into separate, modular functions is effective
- Create a procedure that uses other sub-procedures (other functions) within it and explain why the abstraction was needed (conciseness, shared behavior, etc.)
- Add another layer of abstraction to the word counter program (HINT: create a function that can count the number of words starting with ANY character in a given string -- how can we leverage parameters for this?)
Topic 3.13 (3.C):
- Define procedure names and arguments in your own words.
- Code some procedures that use arguments and parameters with Javascript and HTML (make sure they are interactive on your hacks page, allowing the user to input numbers and click a button to produce an output)
- Add two numbers
- Subtract two numbers
- Multiply two numbers
- Divide two numbers