Section 3.12 ~ 3.13
Vocab
- 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.
- 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
- Procedure Name - the name that is given to a function/procedure
- Arguments - a way to provide information to a function, usually defined outside a function and then imported into a function with parameters
def add(a, b): # procedure and a,b is parameter
print(a)
print(b)
add(2, 3)
Notes
Calling Procedures
- 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 #### Ex:
- procedureName(parameter1, parameter2, ...)
- How would you call this procedure? ### 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 variables
- Value can be string, a tuple, or any other type that is being sent back to the main program
- 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.
- A return statement exits a function and instructs python to continue executing the program and to return a certain value ### 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...
- 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. ### Functions - Basic Structure
- Functions can be created in many different languages. Below are some examples in Collegeboard's format, Python, and Javascript. ### Python
- Python is similar to the Collegeboard example, where
def
defines the function,function
, and then is followed by parametersa,b
, which can later be interchanged with any numbers as shown withfunction(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 - 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.
Hack 1
Define Procedure and parameter
- The other word of procedure is a function. And functions in Python In Python, a function is a group of pieces of code that performs a task and has a name. Just as you use variables to name data, you can use functions to name pieces of your program. Grouping code like this is called a function definition.
- A parameter is a variable that receives a value passed as an input to a function. We can use this to put values in the function. For example, a and b will be the parameter in this function.
def add(a,b):
return a+b
print(add(3,4))
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")
Return Value
- A return value is a value that a function performs some function and returns the result to the place where it was called. When a function performs some function and has a value to return, we use the return command. When creating functions, we use the def reserved word. Function content is indented.
- Output Parameter is a also same as parameter. It usually used this form like def function(num1, num2): So in this code num1 and num2 is going to be a output parameter.
import random
a = random.randint(1, 100)
def add(c):
global a
a += c
return a
num = add(60)
print(num)
import math
def root():
num1 = int(input("write a number: "))
a = int(input("how much did you want to divide"))
b = float(1/a)
num2 = float(num1**b)
print(num1, "of",a ,"root is", num2)
root()
Why abstracting away your program logic into separate, modular functions is effective?
- If we abstract away our code logic into separate or modular functions, we can make our code shorter. And we don't have to repeat code by defining functions. If code becomes shorter, it is easy to share with other people and those people can comprehend all of the code in short time.
import random
import time
## Telling the story ##
def displayIntro():
print('You are in a land full of dragons. In front of you,')
print('you see two caves. In one cave, the dragon is friendly')
print('and will share his treasure with you. The other dragon')
print('is greedy and hungry, and will eat you on sight.')
## Saying to player to choose the cave to go ##
def chooseCave():
print('Which cave will you go into? (1 or 2)')
## choosing the cave to go ##
while True:
choose = input()
if choose=='1':
break
elif choose=='2':
break
else :
## if player press not 1 or 2, say player to pick again ##
print('Please type 1 or 2')
continue
print()
## return the value ##
return choose
def goCave(direction):
## Telling the story ##
print('You approach the cave...')
time.sleep(2)
print('It is dark and spooky...')
time.sleep(2)
print('A large dragon jumps out in front of you! He opens his jaws and...')
print()
time.sleep(2)
## randomize the value of Judgement ##
judgement = random.randint(1,2)
## if the direction and judgement is equal, there will be treasure ##
if direction == str(judgement):
print('Gives you his treasure!')
## if the direction is not same with judgement, there will be gobbles
elif direction != str(judgement):
print('Gobbles you down in one bite!')
## print for the space
print()
## To know whether player will continue or not
def playAgain():
print('Do you want to play again? (yes or no)')
while True:
temp=input()
## if temp is yes, the game will start again
if temp == 'yes':
print('Go Again')
print()
return 'yes'
## if temp is no, it means game over
elif temp == 'no':
print('Good Bye')
return 'no'
else :
print('please type yes or no')
###########################################################
regame = 'yes' ## To know that player will continue the game ##
while regame=='yes':
## this is the codes that make game to start
displayIntro()
caveNumber = chooseCave()
goCave(caveNumber)
regame = playAgain()
About the procedure
- This code contains three sub procedures: displayIntro(), chooseCave(), goCave(), and playAgain()
- DisplayIntro() is a procedure that tells about the story of game. It composed by print. In this procedure, there are only letters that are printed.
- chooseCave() is a procedure that make player to choose cave to go. And also deciding the value which cave is right to go.
- goCave() is to consider which cave the player goes. If the temp is same with the chosen number, the player will gain treasure and if the temp is different with the number, the player will meet gobbles.
- playAgain() is to know whether player want to play again. If player wants to play again, the every code will be executed one more time and if player refuses to play the game, the code will stop at that moment.
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 == 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
# this function takes a string as input and returns the number of words that start with any inputted letter
def count_words_starting_with_l_letter(s):
l = input("What letter would you like to check?")
words = split_string(s)
count = count_words_starting_with_letter(words, l)
return count
# example usage:
s = " This is a test string! Don't you think this is cool? "
l_count = count_words_starting_with_l_letter(s)
a_count = count_words_starting_with_a_in_string(s)
d_count = count_words_starting_with_d_in_string(s)
print("Words a starting with your letter:", a_count)
print("Words d starting with your letter:", d_count)
print("Words l starting with your letter:", l_count)
Hack 3
Definition
- Procedure name is the name given in function. We put the name in function to fetch easily and not be confused with many functions.
- A parameter is a variable that receives a value passed as an input to a function, and an argument is an input value passed when calling a function. In def add(a,b), a and b are called parameters. In print(add(3,4)), 3 and 4 are called arguments.
def add(a,b):
return a+b
print(add(3,4))
<!DOCTYPE html>
AC | / | ||
7 | 8 | 9 | * |
4 | 5 | 6 | - |
1 | 2 | 3 | + |
0 | . | = |
<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
<style>
table {
border-collapse: collapse;
}
td {
padding: 5px 10px;
text-align: center;
}
input {
text-align: right;
border: none;
}
input:focus {
outline: none;
}
</style>
</head>
<body>
<table border="1">
<tr>
<td colspan="4">
<input type="text" id="a">
</td>
</tr>
<tr>
<td colspan="4">
<input type="text" id="b">
</td>
</tr>
<tr>
<td colspan="3">AC</td>
<td onclick="add('/')">/</td>
</tr>
<tr>
<td onclick="add(7)">7</td>
<td onclick="add(8)">8</td>
<td onclick="add(9)">9</td>
<td onclick="add('*')">*</td>
</tr>
<tr>
<td onclick="add(4)">4</td>
<td onclick="add(5)">5</td>
<td onclick="add(6)">6</td>
<td onclick="add('-')">-</td>
</tr>
<tr>
<td onclick="add(1)">1</td>
<td onclick="add(2)">2</td>
<td onclick="add(3)">3</td>
<td onclick="add('+')">+</td>
</tr>
<tr>
<td colspan="2" onclick="add(0)">0</td>
<td onclick="add('.')">.</td>
<td onclick="calculate()">=</td>
</tr>
</table>
<script>
function add(char) {
var display = document.getElementById('a');
display.value = display.value + char;
}
function calculate() {
var display = document.getElementById('a');
var result = eval(display.value);
document.getElementById('b').value = result;
}
function reset() {
document.getElementById('a').value = "";
document.getElementById('b').value = "";
}
</script>
</body>
</html>