vocab

  • Iteration: a repeating portion of an algorithm, repeats a specified number of times or until a given condition is met loop
i = 0
while (i < 5):
    print("Hi")
    i += 1
Hi
Hi
Hi
Hi
Hi
  • Iteration Statement: cause statements to be executed zero or more times, subject to some loop-termination criteria
    • we can use range(a,b) so that the i can start a and end with b-1
a = ""
b = ""
for i in range(6):
    a += str(i)
    a += " "
for j in range(1,6):
    b += str(j)
    b += " "
print(a)
print(b)
0 1 2 3 4 5 
1 2 3 4 5 
  • We can use the command "break" to stop the loop. By using this, when the conditionals that make the loop to stop are met, codes can escape from the loop function
num = 0
while 1:
    print(num)
    if num == 10:
            break
    num += 1
0
1
2
3
4
5
6
7
8
9
10
  • Traversing a list: the process of visiting each element in a list in a sequential order

    • Complete Traversal: All elements in a list are assessed

    • Partial Traversal: Only a given portion of elements are assessed

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

  • 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
  • We can also use the value of list by putting [index] in back of list name
    • ex) list[index]
list = [3,4,5]
list.append(2)
list.remove(3)
list.insert(0,[10, 5])
print(len(list))
print(list)
4
[[10, 5], 4, 5, 2]

Notes

Iteration

  • Iteration is a repeating portion of an algorithm. It repeats until the given conditionals 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: The programmer sets the condition to stop the loop, and when the condition is met, the function can be escaped from being repeated. If the condition is not met, the function continues to repeat.
  • Complete Traversal: All elements in a list are assessed
  • Partial Traversal: Only a given portion of elements are assessed
    ### List
  • A list in Python is a data type in which elements are stored consecutively. At this time, the stored elements do not all have to be of the same data type. A list is represented by enclosing it in square brackets ([, ]), and zero or more elements can be stored inside.
  • 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

Hack 1

Define the Iteration

  • Iteration is like a loop. It can make the function to repeat endlessly or can stop when the condition is met.

Making flow charts

flowchart

Simple Iteration

import random
tries = 0
guess = 0
answer = random.randint(1,100)
print("guess the number between 1 to 100")
guess = int(input("enter the number"))
while True:
    tries = int(tries + 1)
    if tries > 10: 
        print("Answer is ", answer)
        break
    elif guess < answer:
        print("Low")
    elif guess > answer: 
        print("High")
    elif guess == answer:
        print("Congratulation you tries", tries +1, "times")
        break
    guess = int(input("enter the number"))
guess the number between 1 to 100
Low
Low
Low
Low
Low
Low
Low
Low
Low
Low
Answer is  35

Another example

output = ""

for i in range(1, 15):
    for j in range(14, i, -1):
        output += ' '
    for j in range(0,2*i-1):
        output += '*'
    output += '\n'

print(output)
             *
            ***
           *****
          *******
         *********
        ***********
       *************
      ***************
     *****************
    *******************
   *********************
  ***********************
 *************************
***************************

Hack 2

Define Iteration statement

  • Iteration statement: Command that controls the repetition of the same command a certain number of times within a program. Most of the code processed by the program is repetitive. ### Creating list by using loop
a = []
for i in range(10,0,-1):
    a.append(i*i)
print(a)
[100, 81, 64, 49, 36, 25, 16, 9, 4, 1]

making loop which will form given numbers

a = []
let = ""
for i in range(7):
    b = 13*i + 3
    a.append(b)
for j in range(7):
    let += str(a[j])
    if j == 6:
        break
    else:
        let += ","
print(let)
3,16,29,42,55,68,81

Hack 3

Making the list

nums = ["10", "15", "20", "25", "30", "35"]
smallest = int(nums[0])
for i in range(1,len(nums)):
    if int(nums[i]) < smallest:
        smallest = int(nums[i])

print(smallest)
10

Another way to find the smallest

for i in range(1,6):
    print(i)
1
2
3
4
5
nums = ["10", "15", "20", "25", "30", "35"]
k = 0
for i in range(6):
    for j in range(1,6):
        if nums[i] < nums[(j+i)%6]:
            k += 1
            if k == 5:
                print(nums[i])
                break
    k = 0
10
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!")
What allows a value to be inserted into a list at index i?
index()
Correct!
What allows an element at index i to be deleted from a list?
remove()
Correct!
What allows a value to be added at the end of a list?
append()
Correct!
What returns the number of elements currently in a specific list?
length()
Correct!
100.00%
Your total score is:  4 out of 4. Not too bad, keep on studying! 

Extra credit

  • I made a bingo game with the Iteration statement
def board(bingo, dimension):
    for i in range(dimension):
        print(' _', end = '')
    for i in range(dimension):
        print()
        print('|', end = '')
        for j in range(dimension):
            print(bingo[i][j] + '|', end = '')
    print()


while True:
    dimension = int(input("Please input the size of the game board(more than 2): "))
    if dimension <= 2 :
        print('[Error] try again')
    else:
        break

bingo = [['_']*dimension for i in range(dimension)]
board(bingo, dimension)

turn = 1
play_count = 0
while True:
    print('<Play no.{}>'.format(play_count+1))
    if turn == 1:
        print('Currently player: 1')
        row_1 = int(input('Which row?(start with 1)'))
        column_1 = int(input('Which column?(start with 1)'))

        if bingo[row_1-1][column_1-1] != '_':
            print('Space is not empty. Try again')
            turn = 1
            continue
        else:
            bingo[row_1-1][column_1-1] = 'O'
            board(bingo,dimension)
            turn = 2

    elif turn == 2:
        print('Currently player: 2')
        row_2 = int(input('Which row?(start with 1) '))
        column_2 = int(input('Which column?(start with 1) '))

        if bingo[row_2-1][column_2-1] != '_':
            print('Space is not empty. Try again')
            turn = 2
            continue
        else:
            bingo[row_2-1][column_2-1] = 'X'
            board(bingo,dimension)
            turn = 1

    check_diag = []
    check_reverse = []
    check_row = []
    check_column =[]
            
    for i in range(dimension):
        check_diag.append(bingo[i][i])
        check_reverse.append(bingo[dimension-i-1][i])
        

        for j in range(dimension):
            check_row.append(bingo[i][j])
            check_column.append(bingo[j][i])
        
        if set(check_row) == {'O'}:
            print('Player 1 wins!')
            turn = 0
        elif set(check_row) == {'X'}:
            print('Player 2 wins!')
            turn = 0

        check_row = []

        if set(check_column) == {'O'}:
            print('Player 1 wins!')
            turn = 0
        elif set(check_column) == {'X'}:
            print('Player 2 wins!')
            turn = 0
        check_column = []

    check_diag = set(check_diag)
    check_reverse = set(check_reverse)

    if check_diag == {'O'} or check_reverse == {'O'}:
        print('Player 1 wins!')
        turn = 0
        
    elif check_diag == {'X'} or check_reverse == {'X'}:
        print('Player 2 wins!')
        turn = 0

    play_count += 1


    if turn == 0 or play_count == dimension**2:
        print('Finish')
        break
 _ _ _
|_|_|_|
|_|_|_|
|_|_|_|
<Play no.1>
Currently player: 1
 _ _ _
|O|_|_|
|_|_|_|
|_|_|_|
<Play no.2>
Currently player: 2
 _ _ _
|O|_|_|
|_|X|_|
|_|_|_|
<Play no.3>
Currently player: 1
 _ _ _
|O|O|_|
|_|X|_|
|_|_|_|
<Play no.4>
Currently player: 2
 _ _ _
|O|O|_|
|_|X|_|
|_|_|X|
<Play no.5>
Currently player: 1
 _ _ _
|O|O|O|
|_|X|_|
|_|_|X|
Player 1 wins!
Finish

Please give perfect score

Please give me 1. I'm so sad now. If you give me a perfect, I will appreciate to you.