Unit 3 Lesson 12 - 13 Hacks and Notes
Call and Developing Procedures
Notes:
- 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.
- To call a procedure you would write the name of the procedure followed by the parentheses with the parameters of the procedure
- Procedures do not require parameters, but the parentheses must be there
- To use return values, you have to write the syntax return followed by the expression you would like to return var
- 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
- Arguments - a way to provide information to a function, usually defined outside a function and then imported into a function with parameters
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")
- Define return values and output parameters in your own words
return values: the output of a function
parameter: input value to the function
- Code a procedure that finds the square root of any given number. (make sure to call and return the function)
import math
number = input("Insert the number that you want to take the square root of")
def sqrtfunction(number):
result = math.sqrt(int(number))
return result
print("The square root is: " + str(sqrtfunction(number)))
Lesson 3.13 (3.B)
-
Explain, in your own words, why abstracting away your program logic into separate, modular functions is effective
Abstracting away your program logic into separate, modular functions is effective because it makes it easier to manage code and shortens your code so that there are less duplicates in the code.
-
Create a procedure that uses other sub-procedures (other functions) within it and explain why the abstraction was needed (conciseness, shared behavior, etc.)
def binary_search(nums, target):
def sort_list (input_list):
input_list.sort()
return input_list
sort_nums = sort_list(nums)
mid_val = len(sort_nums) // 2
print("===============================")
print("mid_index is ", mid_val)
print("len of nums is ", len(sort_nums))
print(sort_nums)
print(target)
if target == sort_nums[mid_val]:
print("Found match value!")
return sort_nums[mid_val]
elif len(sort_nums) == 1:
print("Found closest value!")
return sort_nums
elif target < sort_nums[mid_val]:
binary_search(sort_nums[:mid_val],target)
else:
binary_search(sort_nums[mid_val:],target)
user_list = [3,5,98,34,56,23,11,24,12]
result = binary_search(user_list, 12)
print(result)
# The abstraction was added with the parameters of nums and target number.
# The two defined functions have different functions but both of them are able to be called
# By having subprocedures the two functions sort the numbers in the given unsorted list and perform the binary search
- 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?)
def split_string(s):
words = s.split(" ")
new_words = []
for word in words:
if word != "":
new_words.append(word)
return words
def count_words_starting_with_letter(words, letter):
count = 0
for word in words:
if word.lower().startswith(letter):
count += 1
return count
def count_words_starting_with_a_in_string(s):
words = split_string(s)
count = count_words_starting_with_letter(words, "a")
return count
def count_words_starting_with_d_in_string(s):
words = split_string(s)
count = count_words_starting_with_letter(words, "d")
return count
# HACKS
def count_words_starting_with_any_letter_in_string(s, z):
words = split_string(s)
count = count_words_starting_with_letter(words, z)
return count
# using hacks:
string = "hey yall this is a test string!"
y = "y"
e = "e"
s_count1 = count_words_starting_with_any_letter_in_string(string, y)
s_count2 = count_words_starting_with_any_letter_in_string(string, e)
print("Words that start with y:", s_count1)
print("Words that start with e:", s_count2)
Lesson 3.13 (3.C)
-
Define procedure names and arguments in your own words.
procedure names: names that are used to give a function a name
arguments: a value that is given to a function when it is called
-
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
var a = 7
var b = 13
<!-- function -->
<p>var a = 7</p>
<p>var b = 13</p>
<button id="enter" onclick="add(a,b)">add</button>
<p id="resultadd"></p>
<button id="enter" onclick="subtract(a,b)">subtract</button>
<p id="resultsub"></p>
<button id="enter" onclick="multiply(a,b)">multiply</button>
<p id="resultmult"></p>
<button id="enter" onclick="divide(a,b)">divide</button>
<p id="resultdiv"></p>
<!-- javascript -->
<script>
function add(a,b) {
document.getElementById("resultadd").innerHTML = a + b // math
}
function subtract(a,b) {
document.getElementById("resultsub").innerHTML = a - b
}
function multiply(a,b) {
document.getElementById("resultmult").innerHTML = a * b // math
}
function divide(a,b) {
document.getElementById("resultdiv").innerHTML = a / b // math
}
// variables are defined
var a = 7
var b = 13
</script>