Unit 3.12

Vocab

  • procedure: set of instructions that can take parameters (do not have to have parameters and only have ()) and return values or the function
  • parameters: value inputted into a function for the function to produce a result
  • return value: the value that is returned after a function is run
  • output parameters: ?
x = 5
y = 3

def multiply(x, y): #x,y are parameters
    product = x * y
    return product #return value

answer = multiply(x, y)
print("The product of", x, "times", y, "is", answer)
The product of 5 times 3 is 15
import math

def squareroot(num):
    res = math.sqrt(num)
    return res

print(squareroot(4))
print(squareroot(7))
print(squareroot(9))
print(squareroot(10))
2.0
2.6457513110645907
3.0
3.1622776601683795

Quiz (Part of Hacks)

Complete this quiz:

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")
Question: What is are correct names for a procedure? 
 A) Method 
 B) Function 
 C) Both

Unit 3.13

  • 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

Abstracting program logic into separate, smaller tasks is effective because the problem is easier to approach. By separating the tasks, the steps are clearly planned out and this avoids repetition and has more clarity.

import math

#create functions for each calculator function

#step 1: addition
def add(a, b):
    print(a + b)

#step 2: subtraction
def subtract(a, b):
    print(a - b)

#step 3: multiplication
def multiply(a, b):
    print(a * b)

#step 4: division
def div(a, b):
    print(a/b)

#step 5: square root
def squareroot(num):
    print(math.sqrt(num))

#get 2 number inputs for addition, subtraction, multiplication, division
def num_input():
   num1 = int(input("First number:"))
   num2 = int(input("Second number:"))
   return num1, num2

#ask if user wants to add, subtract, multiply, division, squareroot
function = input("Type +, -, /, *, or sqrt")

#based on user's function input, perform math
#add
if function == "+":
    num1, num2 = num_input()
    add(num1, num2)
#subtract
elif function == "-":
    num1, num2 = num_input()
    subtract(num1, num2)
#multiplication
elif function == "*":
    num1, num2 = num_input()
    multiply(num1, num2)
#division
elif function == "/":
    num1, num2 = num_input()
    div(num1, num2)
#sqrt
elif function == "sqrt":
    num1, num2 = num_input()
    squareroot(num1, num2)
3

Abstraction is needed for this math calculator because many steps are needed for the algorithm. First, functions need to be made for each of the mathematical operations. The code also needs to get the user input. Using the user input, the user can then determine what operation they want to use. The code should then print out the solution. These steps need to be broken down for the coder to now how to easily code calculator.

def split_string(s):
    '''takes a string as input and returns a list of words, where each word is a separate element in the list'''
    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):
    '''function takes a list of words as input and returns the number of words that start with the given 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):
    '''takes a string as input and returns the number of words that start with 'a''''
    words = split_string(s)
    count = count_words_starting_with_letter(words, "a")
    return count

#HACKS
def count_words_starting_with_letter_in_string(s, c):
    words = split_string(s)
    count = count_words_starting_with_letter(words, c)
    return count

# example usage:
string = "hello, my name is grace. this is a test string"
h = "h"
t = "t"
s_count1 = count_words_starting_with_letter_in_string(string, h)
s_count2 = count_words_starting_with_letter_in_string(string, t)
print(f"Words starting with h:", s_count1)
print(f"Words starting with t:", s_count2)
Words starting with h: 1
Words starting with t: 2

Vocab

  • Procedure name- name of a function
  • Argument- stuff inputted after procedure name, used to outside function then called with the function with parameters
  • Procedure- a module of code that is created to complete a certain task, this is basically a function
  • Parameters- a variable that is used in a function to allow for data to be imported into a function

collegeboard-format

var a = 3

var b = 4

<!-- function is called here -->
<p>var a = 3</p>
<p>var b = 4</p>
<button id="enter" onclick="add(a,b)">add</button> 
<p id="result1"></p>
<button id="enter" onclick="subtract(a,b)">subtract</button> 
<p id="result2"></p>
<button id="enter" onclick="multiply(a,b)">multiply</button> 
<p id="result3"></p>
<button id="enter" onclick="divide(a,b)">divide</button> 
<p id="result4"></p>


<!-- javascript -->
<script>
    function add(a,b) {
        document.getElementById("result1").innerHTML = a + b // math
    }
    function subtract(a,b) {
        document.getElementById("result2").innerHTML = a - b
    }
    function multiply(a,b) {
        document.getElementById("result3").innerHTML = a * b // math
    }
    function divide(a,b) {
        document.getElementById("result4").innerHTML = a / b // math
    }
    // variables are defined
    var a = 3
    var b = 4
</script>
```