0% found this document useful (0 votes)
4 views39 pages

14 Nested For

The document outlines an online course by UNESCO UNITWIN supported by Handong Global University, focusing on programming concepts such as nested loops, break statements, and bubble sort algorithms. It includes various examples, exercises, and practice problems to reinforce learning. Additionally, it emphasizes the prohibition of commercial use of the educational materials provided.

Uploaded by

Thae Thae Aung
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views39 pages

14 Nested For

The document outlines an online course by UNESCO UNITWIN supported by Handong Global University, focusing on programming concepts such as nested loops, break statements, and bubble sort algorithms. It includes various examples, exercises, and practice problems to reinforce learning. Additionally, it emphasizes the prohibition of commercial use of the educational materials provided.

Uploaded by

Thae Thae Aung
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

UNESCO UNITWIN

Online Course
Supported by

Handong Global University


Ministry of Education, Korea

* All copyrights belong to UNESCO UNITWIN and it is prohibited to use these educational materials including the video and other
relevant materials for commercial and for-profit use.
Nested for
14
Global Leadership School
Handong Global University
Learning Objectives
• Understand nested for
• Understand break
• Exercise using nested for
Nested for
• Using for() in for() loop
• Example below

# List

fruit = ["apple", "banana", "lemon", "tomato"]

for fr in fruit :
count = 0
for f in fr :
print(f)
count = count + 1

print(”Item count = ", count)


Execution of nested for
fr f fr f
outer for “apple” outer for “lemon”
inner for “a” inner for “l”
“p” “e”
“p” “m”
“l” “o”
“e” “n”
outer for “banana” outer for “tomato”
inner for “b” inner for “t”
“a” “o”
“n” “m”
“a” “a”
“n” “t”
“a” “o”
nested for
• Use multiple for-loop
for i in range(3) : for i in range(2) :
for j in range(3) : print(“#”)
print (“ $") for j in range(5) :
print (“ $")

i =0
i =0
i =1

i =2
i =1
nest for
for i in range(2,7,2) : # times table : 7, 8
print ("1st level = ", i)
for i in range(7, 9) :
for j in range(1,5,1) : print (i, "th table")
print(" 2nd level = ", j)
print(" i * j = ", i*j) for j in range(1,10,1) :
print( " ", i, " * ", j, " = ", i*j)
What will be printed out?
# what is the value of a

a=0
for i in range(10) :
a=a+1

for j in range(10) :
a=a+1

print(a)
What will be printed out?, Answer
# what is the value of a
a=0
for i in range(10) :
a=a+1

for j in range(10) :
a=a+1

print(a)
What will be printed out?
# what is the value of a
a=0
for i in range(10) :
a=a+1
for j in range(10) :
a=a+1

print(a)
What will be printed out?, Answer
# what is the value of a
a=0
for i in range(10) :
a=a+1
for j in range(10) :
a=a+1

print(a)
What will be printed out?
# What will be printed next?

fruit = "banana"
count = 0
for char in fruit :
if char == ’a’ :
count = count + 1

print(count)
What will be printed out?, Answer
# # What will be printed next?

fruit = "banana"
count = 0
for char in fruit :
if char == ’a’ :
count = count + 1

print(count)
Bubble sort
• Reorganizing numbers and characters in a certain
order.
• The simplest way to arrange.

23 78 45 8 32 56 Original List 23 8 32 45 56 78 After pass 2 (outer loop)

Unsorted

8 23 32 45 56 78 After pass 3 (outer loop)


23 45 8 32 56 78 After pass 1 (outer loop)

Sorted
Bubble sort
numbers = [ 5, 4, 1, 3, 9, 2, 15 ]

for i in range(0, 7):


for j in range(0, 6):
if numbers[ j] > numbers[ j+1]:
temp = numbers[ j] numbers = [ 5, 4, 1, 3, 9, 2, 15 ]
numbers[ j] = numbers[ j+1]
for i in range(0, len(numbers)):
numbers[ j+1] = temp
for j in range(0, len(numbers)-1):
if numbers[ j] > numbers[ j+1]:
temp = numbers[ j]
numbers[ j] = numbers[ j+1]
numbers[ j+1] = temp
Bubble sort Example
number01 = int(input(”Enter the first number: "))
number02 = int(input(”Enter the second number: "))
number03 = int(input(”Enter the third number: "))
number04 = int(input(”Enter the fourth number: "))
number05 = int(input(”Enter the fifth number: "))

numbers = [number01, number02, number03,


number04, number05]

for i in range(0, len(numbers)):


for j in range(0, len(numbers)-i):
if numbers[ j] > numbers[ j+1]:
temp = numbers[ j]
numbers[ j] = numbers[ j+1];
numbers[ j+1] = temp

print(numbers)
Bubble sort Exercise
• Use the Bubble sort from the previous
example
• Print out the larger numbers first
• After, find the difference between the largest
number and smallest.
Bubble sort Exercise
number01 = int(input(”Enter the first number: "))
number02 = int(input(”Enter the second number: "))
number03 = int(input(”Enter the third number: "))
number04 = int(input(”Enter the fourth number: "))
number05 = int(input(”Enter the fifth number: "))

numbers = [number01, number02, number03, number04, number05]

for i in range(0, len(numbers)):


for j in range(0, len(numbers)-i):
if numbers[ j] < numbers[ j+1]:
temp = numbers[ j]
numbers[ j] = numbers[ j+1];
numbers[ j+1] = temp

print(numbers)
print(”The difference between the largest and the smallest is",
int(numbers[0])-int(numbers[4]))
break
• Stop to get out of the loop
• After the loop, the execution flow passes over to
the first instruction.
fruit = "banana"
count = 0

for char in fruit :


if char == 'a':
count = count + 1
elif char == 'n':
break
else :
print(char)

print(count)
break example
• Nested for

# If the sum of two numbers is multiple of 5, end the loop

count = 0

for i in range(5) :
for j in range(3) :
if (i + j) % 5 != 0 :
count = count + 1
print('i='+str(i), 'j='+str( j), "i+j =", i+j, "and count =", count)
else :
break

print('i='+str(i), 'j='+str( j), "i+j =", i+j, "last count: ", count)
break Exercise
• Calculate how many items you can buy with
the amount you currently have.
• Receive the how much you have, the price
and the quantity of the product you want to
buy.
• After every purchase, print the balance
• If the balance is insufficient, end the
repetition using break
break Exercise, Code
balance = int(input(”How much do you have? "))
cost = int(input(”What is the price of the product? "))
num = int(input(”How many do you want? "))

for i in range(1, num+1):


if balance - cost >= 0 :
balance = balance - cost
print(”Buying ", i, " product(s). Current balance is ", balance, " Won")
else :
print(”Insufficient balance. Balance is ", balance, " WON)
break
Check Prime Number
• Definition of prime number
• One of the positive integers and the number
divided by oneself.

• Check process
• Starting with 2, divide the number of inputs,
• Repeat dividing up to (number – 1)
• If it is divided, it’s not a prime number
• If it is not divided, it is a prime number
• If it is divided, change the “flag” variable to False
Prime Number Check
# Check prime number

num = int(input("input a positive integer : "))

prime_yes = True

for i in range(2, num) :


if num % i == 0:
prime_yes = False
break

if prime_yes == True :
print(num, "is a prime number")
else :
print(num, "is not a prime number")
Exercise 1
• Enter an English word
• Enter one of the letter in the received word
• Find where the letter is located
• If the letter doesn’t exist
Exercise 1, Code and Result
word = input(”Enter a word: ")
letter = input(”Enter a letter to find the location: ")

count = 0

for char in word :


count = count + 1
if char == letter:
break

if letter not in word:


print( letter, ”does not exist in ", word, “.”)
else :
print(letter, "is located ", word, ”’s", count, ” index")
Exercise 2
• Receive a message from the user
• Count the number of "a" in the message and
print it out.
Exercise 2, Code and Result
• Read letter by letter and check if the letter is
‘a’

s = input("Input message : ")


count = 0

for c in s :
if c == "a" :
count += 1

print("count of \'a\' : ", count)


Exercise 3
• Print multiplication tables
• Start from the multiple of 2
• User will input how many multiplicand to print
Exercise 3, Code and Result
num = int(input(”Multiplication Table, How many
multiplicand do you want to print? : "))

for i in range(2, num+1, 1) :


print("="*20)
for j in range(2, 10, 1) :
print(i, "*", j, " = ", i * j)
Exercise 4
• Get the number of stars
• Print it out in an upside-down triangle shape
Exercise 4, Code and Result
num = int(input(”Enter the number of stars: "))

for i in range(0, num):


for j in range(num - i):
print("*", end="") # Make it stay on the same line
print() # print on the next line
Lecture Summary
• Understand nested for
• Using for() in for() loop

• Understand break
• Stop to get out of the loop

• Exercise using nested for


Practice Problem 1
• How many times does the “print()” statement
execute? for i in range(2) :
for j in range(7) :
print (“ $")

• 2 times
• 7 times
• 9 times
• 14 times
Practice Problem 1, Answer
• How many times does the “print()” statement
execute? for i in range(2) :
for j in range(7) :
print (“ $")

• 2 times
• 7 times
• 9 times
• 14 times
Practice Problem 2
• What is the output?
a=0
for i in range(5) :
a=a+1
for j in range(5) :
a=a+2
print(a)

• 50
• 55
• 60
• 65
Practice Problem 2, Answer
• What is the output?
a=0
for i in range(5) :
a=a+1
for j in range(5) :
a=a+2
print(a)

• 50
• 55
• 60
• 65
Thank you
14 Nested for
Contact Info
unitwinlms@handong.edu
https://ecampus.handong.edu/

* All copyrights belong to UNESCO UNITWIN and it is prohibited to use these educational
materials including the video and other relevant materials for commercial and for-profit use.
CREDITS: This presentation template was created by Slidesgo, including icons by Flaticon, and infographics & images by Freepik.

You might also like