3.12 & 3.13 Hacks
This is regarding the 3.12 and 3.13 lesson. This includes some notes on the given lessons and the hacks for it.
Notes 3.12
What is a procedure?
- set of instructions that have parameters and return values
- procedures can be classified as sequence, selection, and iteration
How to call procedures?
- if the function is defined as math(x), you can call it by typing math() with whatever parameter
Result of a procedure:
- you can determine the result by looking at the function parameters, return values and statements
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
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")
3.
- return values: value that a function returns to the caller
- output parameter: allows you to return a processed value (processed by the function) back to the caller
4.
import math
x = int(input("input a whole number please"))
# square-root number function
def sqrt(x):
squarednum = math.sqrt(x)
return(squarednum)
sqrt(x)
3.13 hacks 1:
- abstracting your program logic into separate, modular functions lets you manage and understand your code better. But, this doesn't really matter when the algorithm in your function is simple. When your algorithms are complex, it is way easier to use modularity to make your code simple.
def outerfn():
def innerfn():
print("hello outer function!")
innerfn()
print("hellow inner function!")
outerfn()
# The abstraction was needed because it simplified this process for me. I can print hello outer function just by calling the innerfn()
# and I can print both by just calling the outerfn(). I know the example isn't very practical, but the concept has some real use to it.
3.
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
letter = input("enter a letter of the alphabet to search with: ")
def count_words_letter(s, letter):
words = split_string(s)
count = count_words_starting_with_letter(words, letter)
return count
# example usage:
s = " This is a test string! Don't you think this is cool? "
anyletter = count_words_letter(s, letter)
print("words that start with " + str(letter) + " are: " + str(anyletter))
3.13 C hacks: 1.
- Procedure names: name of a procedure (procedure is basically a function)
- arguments: basically, arguments are variables (or items that contain data) that you can import into a function. Importing these arguments lets you send the argument information to the function.