Unit 3 Sections 1-2

Notes

  • Variable is an abstraction inside a program that can hold a value
  • organizes data by labeling it with descriptive name
  • consists of three parts: name, value, and type
  • When naming variables, keep it easy and simple to read, because it can be messy and confusing later on
  • types of data, integer is a number, text/string is a word, and Boolean is data that determines if something is true or false
  • assignment operator allows a program to change the value represented by a variable, used to assign values to variables
  • value stored in a variable will be the most recent value assigned

Data Abstraction

  • Method used in coding to represent data in a useful form, by taking away aspects of data that aren't being used in the situation
  • Variables and lists are primary tools in data abstraction
  • Provides a separation between the abstract properties of a data type and the concrete details of its representation

Lists & Strings

  • List = ordered sequence of elements
  • Element = individual value in a list that is assigned to a unique index
  • Index = a way to reference the elements in a list or string using natural numbers; each element of a string is referenced by an index
  • String = ordered sequence of characters (Letters, numbers, special characters)

What are Lists?

  • Allow for data abstraction
  • Bundle variables together
  • Store multiple elements
  • Allows multiple related items to be treated as a single value
  • Give one name to a set of memory cells
  • Can keep adding elements to it as needed
  • Can store elements as a single variable by using a list

3 Types of List Operations

  1. Assigning values to a list at certain indices
  2. Creating an empty list and assigning it to a variable
  3. Assigning a copy of one list to another list (setting one list equal to another list)

Practice

colorList=["green", "red", "pink", "purple", "blue", "brown"]

print(str(colorList))
['green', 'red', 'pink', 'purple', 'blue', 'brown']

Homework/Hacks

print("General Knowledge Trivia")
QandA = { 
    "#1) What is the largest mammal?": "blue whale", 
    "#2) What is the largest organ in the body?": "skin", 
    "#3) What galaxy do we live in?": "milky way", 
    "#4) Who founded Amazon?": "jeff bezos", 
    "#5) What is the world's largest ocean?": "pacific ocean", 
}

def qandresp(question): # display question, return inputted response
    print(question)
    resp = input()
    return resp

correct = 0 

# Setup
print("Current number of questions: " + str(len(QandA)))

# iterate over each key
for key in QandA:
    rsp = qandresp(key) # save user's response to a variable rsp
    rsp = rsp.lower() # answer is case sensitive, so match response to lowercase for answer key to work
    if rsp == QandA[key]: # check if the response is equal to the answer in the dictionary
        print(f"Correct!")
        correct += 1
    else:
        print(f"{rsp} is incorrect ") 

percent = str(round(correct/len(QandA), 2)*100) # calculate percentage

print("You scored " + str(correct) +"/" + str(len(QandA)))
print(f"Which is also, {percent}%") # print score and percentage
General Knowledge Trivia
Current number of questions: 5
#1) What is the largest mammal?
Correct!
#2) What is the largest organ in the body?
heart is incorrect 
#3) What galaxy do we live in?
Correct!
#4) Who founded Amazon?
Correct!
#5) What is the world's largest ocean?
atlantic ocean is incorrect 
You scored 3/5
Which is also, 60.0%

Unit 3 Sections 3-4

Notes

  • An algorithm has three components: sequencing, selection, and iteration
  • sequencing is algorithms doing tasks in the order of specification
  • selection is allowing is to choose two different outcomes based off a decision
  • iteration is that if a condition is true, then the code is repeated

Algorithm Can Be Represented In Two Ways

  • flowcharts, which uses shapes and arrows to represent steps of an algorithm
  • pseudocode, which is a blend of human language and coding format

Basic Operations

  • subtraction, represented by -
  • addition, represented by +
  • multiplication, represented by *
  • division, represented by /
  • getting the remainder, represented by MOD(% in python)

Different Ways Values Are Stored in Variables

  • numerical value stored in variable
  • value of another variable stored in variable
  • result of an operation stored in a variable
  • result of a procedure call stored in a variable

Strings

What is a String? A String: A string is a collection of characters. What is a character as character can be anything from numbers, letters, spaces, special symbols, etc.

A string is a collection of characters. What is a character as character can be anything from numbers, letters, spaces, special symbols, etc.

Certain procedures may be used with strings and they vary from programming language to language Python examples

len() to find the length of a string

lower() to convert to lowercase

etc. Pseudocode examples

len() returns the length of a string

concat() returns a string made up of the concatenated strings ex. concat("string1", "string2") would return string1string2

substring() returns the characters from the string beginning at the at the first position to the last so an example of this would be substring ("abcdefghijk", 2, 5) would print bcde (pseudocode starts at 1)

Homework/Hacks

Tracking Variables Hack

Num1 = 50
Num2 = Num1 % 9 + 15
Num3 = Num2 / Num1 + ( Num2 * 2 )
Num4 = Num3 + Num1 / 5 - 10
Result = Num4 - Num2
# Result is 20.4
Num1 = 10
Num2 = Num1 % 3 * 4
Num1 = Num2
Num3 = Num1 * 3
Result = Num3 % 2
# Result is 0
valueA = 4
valueB = 90
valueC = 17
valueB = valueC - valueA
valueA = valueA * 10
if valueB > 10:
    print(valueC)
# Result is 17 
17
type = "curly"
color = "brown"
length = "short"
type = "straight"
hair = type + color + length
print(hair)
# Result is straightbrownshort
straightbrownshort

String Hacks

Problem 1
Noun = "Mr.Mortenson"
Adjective = "handsome"
Adjective2 = "Very"
Verb = "is"
abrev = Noun[:7]
yoda = abrev + " " + Verb + " " + Adjective2 + " " + Adjective + "."
print(yoda)
Mr.Mort is Very handsome.
Problem 2
cookie = "choclate"
cookie2 = "rasin"
len1 = len(cookie) / 2
len2 = len(cookie2) * 45
vote1 = (str(cookie) + " vote " + str(len2))
vote2 = (str(cookie2) + " vote " + str(len1))
votes = (str(vote1) + " " + str(vote2))
print(votes)
choclate vote 225 rasin vote 4.0

Unit 3 Sections 8-10

Notes

Lists: a sequence of variables

  • we can use lists to store multiple items into one variable
  • used to store collections of data
  • changeable, ordered, allow duplicates

There is list, then four total collection data types in Python

  • Tuple: collection that is ordered, unchangeable, allows duplicates
  • Set: collection that is unordered, unchangeable, doesn't allow duplicates
  • Dictionary: collection that is ordered, changeable, doesn't allow duplicates

More Terms

  • Index: a term used to sort data in order to reference to an element in a list (allows for duplicates)
  • Elements: the values in the list assigned to an index

Methods

Method Definition Example
append() adds element to the end of the list fruits.append("watermelon")
index() returns the index of the first element with the specified value fruits.index("apple")
insert() adds element at given position fruits.insert(1, "watermelon")
remove() removes the first item with the specified value fruits.remove("strawberry")
reverse() reverses the list order fruits.reverse()
sort() sorts the list fruits.sort()
count() returns the amount of elements with the specified value fruits.count("apple")
copy() returns a copy of the list fruits.copy()
clear() removes the elements from the list fruits.clear()

Iteration

  • Iteration is the repetition of a process or utterance applied to the result or taken from a previous statement.
  • There's a lot of types of iteration though, what to use? How do we apply iteration to lists?
  • Some methods include using a "for loop", using a "for loop and range()", using a "while loop", and using comprehension
  • here are 2 types of iteration: definite and indefinite. Definite iteration clarifies how many times the loop is going to run, while indefinite specifies a condition that must be met

Else, elif, break

  • Else: when the condition does not meet, do statement()
  • Elif: when the condition does not meet, but meets another condition, do statement()
  • Break: stop the loop

Homework

HW Iteration

words = ["alfa", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india", "juliett", "kilo",
"lima", "mike", "november", "oscar", "papa", "quebec", "romeo", "sierra", "tango", "uniform", "victor", "whiskey", "xray", "yankee", "zulu"]

inp = input().lower()
print(inp + " ->")
for i in range(len(inp)):
    for j in range(len(words)):
        if inp[i] == words [j][0]:
            print(words[j])
derek ->
delta
echo
romeo
echo
kilo

Other way to print matrix

keypad =   [[1, 2, 3],
            [4, 5, 6],
            [7, 8, 9],
            [" ", 0, " "]]
def print_matrix3(matrix):
    for i in range(len(keypad)):
        print(*keypad[i])
print_matrix3(keypad)
1 2 3
4 5 6
7 8 9
  0  

Birth Month HW

keyboard = [["`", 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, "-", "="],
            ["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "[", "]"],
            ["A", "S", "D", "F", "G", "H", "J", "K", "L", ";", "'"],
            ["Z", "X", "C", "V", "B", "N", "M", ",", ".", "/"]]

      
print(str(keyboard[0][1]) + str(keyboard[3][9]) + str(keyboard[0][1]) + str(keyboard[0][7]) + str(keyboard[3][9]) + str(keyboard[0][2]) + str(keyboard[0][10]) + str(keyboard[0][10]) + str(keyboard[0][5]) + "\n" + str(keyboard[0][1]) + str(keyboard[0][7]))
1/17/2005
17

Unit 3 Sections 9-11

Notes

Algorithms

  • Algorithms can be written in different ways and still accomplish the same tasks
  • Algorithms that appear similar can yield different side effects or results.
  • Some conditional statements can be written as the same as Boolean expressions (VICE VERSA)
  • Different algorithms can be developed or use to solve the same problem.

Conditionals vs. Boolean

The condition and instructions are what differ, that's where the magic happens. The condition is a boolean expression when an expression outputs either true or false. Boolean values are another type of data type in programming languages, and they can only ever hold true or false.

Selection vs. Iteration

Selection:

  • A process used in algorithms where a conditional if-statement leads to one of two outcomes
  • Outcome 1: if the conditional statement is true, something will happen
  • Outcome 2: if the conditional statement is false, something else will happen

Iteration

  • A process used in algorithms that allows certain things to happen until a condition is satisfied
  • Once the condition is satisfied, then an outcome is produced
  • This can take the form of a for-loop, while-loop, and/or if-statement

Takeaways

  • You can use code you've previously wrote in order to make a project easier.
  • Breaking algorithms down into steps can make things easier and more simple.

Homework

Unit 3 Sections 12-13

Notes

Calling Procedures

Slide 1:

  • A procedure is a named group of programming instructions that may have parameters and return values.
  • Procedures are referred to by different names, such as method or function, depending on the programing language.
  • Parameters are input values of a procedure. Arguments specify the values of the parameters when procedure is called.
  • A procedure call interrupts the sequential execution of statements causing the program to execute the statements within the procedure before continuing. One the last statement in the procedure (or a return statement) has executed, flow or control is returned to the point immediately following where the procedure was called.

Slide 2:

  • When calling procedures, it's important to take notice to whether it returns data, or a block of statements.
  • If the procedure just returns a block of statements, you call the procedure by referring to the procedure name, and inputting the arguments.
  • If the procedure returns some sort of data like a boolean or value, then you will assign that value to a variable

Slide 3:

  • Assume the Temperature outside is Fahrenheit.
  • The procedure convertFahrenheit is intended to convert from Fahrenheit to Celsius.
  • Convert the following psuedocode to python

Developing Procedures

Slide 8:

Picking a descriptive name is important in case you revisit the code later on (separate words with capitals) There are 2 different types of procedures- ones that return a value and those that simply execute a block of statements Steps of developing procedure: picking a useful name, thinking of parameters (what data does the procedure need to know), making a flowchart or writing procedure in pseudocode, and actually developing the procedure.

Slide 9:

In this example, a teacher is writing a program that will replace the grade on a previous quiz if the new grade is better than the previous.

  • What would be a good name for this procedure?
  • What parameters do we need for this procedure?
  • Try writing this procedure out in python based on the given pseudocode

Procedural Abstraction

  • One type of abstraction is procedural abstraction which provides a name for a process and allows a procedure to be used only knowing what it does and not how it does it
  • This is very helpful in managing complexity in a program
  • Subdivision of a program into separate subprograms is called modularity
  • A procedural abstraction may extract shared features to generalize functionality instead of duplicating code. This allows for program reuse, which helps manage complexity
  • When a pre-written procedure is called, you don’t necessarily need to know the details of this, just what it does and how to call it
  • Simply, procedural abstraction is naming and calling a prewritten procedure
  • Making sure to include the right arguments so the procedure can do what its supposed to do is crucial

Homework