Section 8 - Iteration

Section Objectives:

  • Express an algorithm that uses iteration without using a programming language
  • Determine the result or side effect of iteration statements
  • Write iteration statement

Section Vocabulary:

Iteration: a repeating portion of an algorithm, repeats a specified number of times or until a given condition is met

Iteration Statements: change the sequential flow of control by repeating a set of statements zero or more times, until a stopping condition is met

Repeat Until: if the condition evaluates to true initially, the loop body is not executed at all, due to the condition being checked before the loop



Unit 3 Section 8.1

Unit 3 Section 8.1 - Taiyo Iwazaki

Lesson Objectives:

  1. Express an algorithm that uses iteration without using a programming language
  2. Define an iteration
  3. The Basics Of Iteration
  4. Examples

LESSON Vocab:

  1. Iteration: a repeating portion of an algorithm, repeats a specified number of times or until a given condition is met

Before we dive deeper, we need to understand that an iteration is a part of an algorithm. And in that iteration is a set of instructions that need to be followed until a certain desired output is met.

Examples

Here is an example using online shopping:

image

Lets say you are looking for a lost item inside of your house... What steps would you take?

  1. Suppose there are n rooms to search... number the rooms 1-n

  2. Start by searching in room number 1

  3. Search each room thoroughly for you item.

  4. Change the room number to the next highest number

  5. Repeat steps 3 and 4 until you have found your lost item.

  6. Enjoy the lost item.

WAIT! There is a flaw in the program.

This is where a stopping condition is useful for when the iteration already meets the desired requirement and gets out of the loop.

Programming Examples

i = 0
while (i < 5):
    print("Hello, World!")
    i = i + 1
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
i = 0
while (i < 5): #Try changing the 5 and see what happens!
    print("Hello, World!")
    i = i + 1
    if (i == 3): #Try Changing the 3 and see what happens!
        break
Hello, World!
Hello, World!
Hello, World!

These are just a few examples of what you can do with iteration.

Summary:

  1. An Iteration is a repeating portion of an algorithm, repeats a specified number of times or until a given condition is met
  2. We can use stopping conditions to stop an iteration if a condition is already met

Unit 3 Section 3.8.2

Unit 3 Section 3.8.2 - Parav Salaniwal

Lesson Objectives

  • Determine the result or side effect of iteration statements
  • Learn how to use iterations with for loops and while loops
  • Creating code to learn how to incrementally list numbers
  • Learn the range function and using variables in code

Definition: Iteration Statement - cause statements to be executed zero or more times, subject to some loop-termination criteria

The first function we will learn is the range function, which we will use with for loop. As you may be able to guess, this will give us the sum based on the input provided. We always use a variable, such as i, to represent what the range of numbers the output will show. For example, if I wanted to list the numbers from 1-10 using the range function, it would look like this:

for i in range(11):
    print(i)
0
1
2
3
4
5
6
7
8
9
10

Now the first thing you may notice is my input for the range was 11, and you may wonder why is it not 10? This is because when using the range function, the last number, or the ending value, is not included in the output, therefore we would have to add 1 to receive the correct output. Now if we were looking to include a starting value to have it start from 1 and end at 10, the code would look like this:

for i in range(1,11):
    print(i)
1
2
3
4
5
6
7
8
9
10

When using the range with for loop, the you can list much more than just a increment of one, would anyone like to guess how we could include a change in the incremented value? Try making a change in the python code above to change the incremented value. When using the range function:

for i in range(starting value, ending value, incremented value):
    print(i)

Now with while loops, we can provide a similar output with a variation in the input. Similar to for loops, it requires a variable which is the starting value.

i=1
while i<=10:
	print(i)
	i=i+1
1
2
3
4
5
6
7
8
9
10

Based on your knowledge from for loops, which values in the code above are the starting, incrementing, and ending values?

LESSON


Unit 3 Section 3.8.3

Unit 3 Section 3.8.3 - Nikhil

Here is some basic code I have created, let's first look into this one: I created a list of pets, cat, dog, fish, and snake. Then I created a for loop, "for i in pets" and this looks at every element/value in pets, so "cat", "dog", "fish" and "snake". This next if statmenets checks if the element in the list is "fish" and if it is, it breaks the loop. The statement would just print, cat and dog since the loop breaks at fish.

pets = ["cat", "dog", "fish", "snake"]
for i in pets:
    if i == "fish":
        break
    print(i)
cat
dog

This while loop checks if number less than 10 is even and if so, it will print out the even numbers. We set a starting value of number = 0, then while the number is less than 10, the percent sign means modulus so meaning if there is a remaninder when we dvide. So if number divided by 2 has no remainder then it will print number. Then after that it will add 1 to the number and repeat the process untill it reaches 10. So let's check for 0, while 0 is less than ten, then it moves to next statement, since 0 divded by 2 has a remainder of 0 it will print the value of 0. Now it will add 1 to zero. Then it will see that 1 is less than ten, and then check if 1 divided by 2 has a remainder of 0 which it does not, so it skips the print, and goes straight to addding one, so on so forth.

number = 0 
while number < 10:
    if number % 2 == 0:
        print(number)
    number += 1
0
2
4
6
8

The purpose of this code is to find the sum of all the even numbers between and any number of your choosing. The integer input asks for the minimum and maximum value. The next statement puts a starting sum value set to 0. The for i in range (minimum,maximum+1) looks at every number between those two values, in this case 1 and 100. Then the if i modulus 2 checks if any numbers that are divisible by 2 and the remainder comes to 0. If there is a number that has a remainder of 0 when divided by 2, it adds that number to the sum. Then the last print statement, prints out the final sum of all even numbers between the two numbers of your choosing.

minimum = int(input("please enter a minimum number you want your range to be"))
maximum = int(input("please enter a number that you want to be the maximum value"))
sum = 0
for i in range(minimum,maximum+1):
    if i % 2 == 0:
        sum += i
print("The sum of all the even numbers between", minimum, "and", maximum, ":", sum)
    
    
The sum of all the even numbers between 1 and 3 : 2

LESSON


HACKS Unit 3 Section 8

Hacks Unit 3 Section 3.8.1

  1. Define an Iteration
  2. Make your own example of an iteration with at least 4 steps and a stopping condition(Similar to mine that I did)
  3. Program a simple iteration.

Hacks Unit 3 Section 3.8.2

  1. What is an iteration statement, in your own words?
  2. Create a descending list of numbers using for loop
  3. Using while loop, make a list of numbers which will form an output of 3,16,29,42,55,68,81



Section 10 - Lists - Luna Iwazaki, Ethan Tran

Section 10 - Lists

Lists Recap

append() - adding element to the end of the list

names = ['taiyo', 'ethan', 'parav', 'nikhil']
# add element to the end of the list
names.append('luna')
# start with empty list
names = []
names.append('taiyo')
names.append('ethan')
names.append('parav')
names. append('nikhil')

insert() - adding an element in a specific position

names = ['luna', 'taiyo', 'ethan', 'parav', 'nikhil']
# adding in a specific position
names.insert(0, 'taiyo')
names.insert(3, 'ethan')

remove() - remove an item from the list

names = ['luna', 'taiyo', 'ethan', 'parav', 'nikhil']
# deleting by value
names.remove('parav')
# by position
del names[-1]

pop() - takes the item off the top of the "stack" (by default it returns the last element of the list but you can also pop from any position)

names = ['luna', 'taiyo', 'ethan', 'parav', 'nikhil']
# pop last item of list
most_recent_name = names.pop()
print(most_recent_name)
# pop first item of list
first_name = names.pop(0)
print(first_name)

len() - returns the number of items in a list

names = ['luna', 'taiyo', 'ethan', 'parav', 'nikhil']
# find length of list
num_names = len(names)
print("There are" + str(num_names) + "names.")

sort() - changes order of list permanently

sorted() - returns a copy of the list which leaves the original copy unchanged

names = ['luna', 'taiyo', 'ethan', 'parav', 'nikhil']
# sort permanently
names.sort()
# sort permanently in reverse alphabetical order
names.sort(reverse=True)
# temp. sort
print(sorted(names))
print(sorted(names, reverse=True))
# reversing the order of a list
names.reverse()

range() - use to work with number efficiently

for number in range(11):
    print(number)
# making list of numbers 1 to 10
# using the list() value can generate a large list of numbers
numbers = list(range(1, 10))

min() - find the least value in list

nums = [10, 30, 40, 60, 70, 60]
least = min(nums)
print(min(nums))

max() - find the highest value in list

nums = [10, 30, 40, 60, 70, 60]
highest = max(nums)
print(max(nums))

sum() - sum of all in list

nums = [10, 30, 40, 60, 70, 60]
total = sum(nums)
print(sum(nums))

Practice Question

Using the information above fill in the missing code

nums = []
nums.#missing code '15'
nums.#missing code '43'
nums.#missing code '81'
nums.#missing code '25'

least = #missing code
print(#missing code)

AP Exam Reference Sheet

Since CS is taught in different languages the pseudocode represents fundamental programming concepts.

  • provides basic operations on lists
  • provides pseudocode for loops
  • helps you understand code used in questions
  • students can use this reference sheet in the AP Exam

If you looked at the reference sheet and seem to not understand some concepts here is a Khan Academy resource which can help you understand specific topics.

Practice Question

If the list words contain ['song', 'book', 'video', 'book'] what will be the following code output

Finding Values in Lists (Luna Iwazaki)

Part 1

  • use the list below
  • make a variable to hold the minimum and set it to potential minimum value
  • loop
  • check each element to see if it is less than the minimum variable
  • if the element is less than the minimum variable, update the minimum
  • after all the elements of the list have been checked, display the minimum value
nums = ['38', '45', '67', '83', '78']
# add code here

Part 2

  • use the list from part 1
  • find the sum of even numbers in a list

Unit 3.10.2 (Ethan Tran)

  • Traversing a list is the process of visiting each element in a list in a sequential order. It can be used to access, search for, and modify elements in the list.

Traversing Lists

1) Complete Traversal: All elements in a list are assessed

2) Partial Traversal: Only a given portion of elements are assessed

3) Iterative Traversal: When loops are used to iterate through a list and to access each single element at a time.

Quick Lists Reference Sheet

  • A given element of a list can be evaluated using index, [ ]

1) Ex. listName[i] 2) Ex. listName[3]

  • insert( ) allows a value to be inserted into a list at index i
  • append( ) allows a value to be added at the end of a list
  • remove( ) allows an element at index i to be deleted from a list
  • length( ) returns the number of elements currently in a specific list

A loop such as the example above allows a user to access each item within the list

College Board Example Question

</html>
</div> </div>

HACKS Unit 3 Section 10

Find the lowest value in a list (Luna Iwazaki)

  • Use the list made bellow
  • Make a variable to hold the minimum and set it to potential minimum value
  • Loop
  • Check each element to see if it is less than the minimum variable
  • If the element is less than the minimum variable, update the minimum
  • After all the elements of the list have been checked, display the minimum value
nums["10", "15", "20", "25", "30", "35"]
min

Lists Quiz (Ethan Tran)

Take a screenshot of your score on put it on your review ticket!

import getpass, sys
import random

def ask_question (question, answer):

    print(question)
    ans = input(question)
    print(ans)
   
    if ans == answer:
        print("Correct!")
        return 1

    else:
        print("Wrong")
        return 0

question_list = ["What allows a value to be inserted into a list at index i?" , "What allows an element at index i to be deleted from a list?" , "What returns the number of elements currently in a specific list?" , "What allows a value to be added at the end of a list?"]
answer_list = ["index()", "remove()", "length()" , "append()"]

# Set points to 0 at the start of the quiz
points = 0

# If the length of the quiz is greater than 0, then random questions will be chosen from the "question_list" set
while len(question_list) > 0:
    index = random.randint(0, len(question_list) - 1)
    
# The points system where a point is rewarded for each correct answer    
    points = points + ask_question(question_list[index], answer_list[index])
    
# If a question or answer has already been used, then it shall be deleted    
    del question_list[index]
    del answer_list[index]

# Calculating score using the points system and dividing it by the total number of questions (6)
score = (points / 4)

# Calculating the percentage of correct answers by multiplying the score by 100
percent = (score * 100)

# Printing the percentage, and formatting the percentage in a way where two decimals can be shown (through "{:.2f}")
print("{:.2f}".format(percent) + "%")

# Adding final remarks based upon the users given scores
if points >= 5:
         print("Your total score is: ", points, "out of 4. Amazing job!")

elif points == 4:
         print("Your total score is: ", points, "out of 4. Not too bad, keep on studying! " )

else:
         print("Your total score is: ", points, "out of 4. Its alright, better luck next time!")

College Board Reference Sheets

List Operations

</div>