Section 3.8 and 3.10
i = 0
while (i < 5):
print("Hi")
i += 1
- 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)
- 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
-
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)
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
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"))
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)
a = []
for i in range(10,0,-1):
a.append(i*i)
print(a)
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)
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)
for i in range(1,6):
print(i)
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
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!")
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