Nested loops
Unit 11.1А: Python programming Basics
Lesson objectives
A nested loop is a loop that runs inside another loop. �Typically nested loops are used to work with two dimensions, such as printing stars in rows and columns, as shown below.
With each iteration of the outer loop, the inner loop will be executed completely. The inner loop must complete all of its iterations before the outer loop can move on to the next iteration.
Example
Conclusion
Tracing Nested Loops
Task 1. Print the stars in the following form.
Answer
n = int(input())�m = int(input())�for i in range(n): � for j in range(m): # вложенный цикл� print('*', end='')� print()
Task 2 . Print the multiplication table for the number n. � (n < 10)
Input:
5
Conclusion:
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25 6*5=30 7*5=35 8*5=40 9*5=45
Answer
k = int(input())�for i in range(1, 10):� print(i, '*', k, '=', k * i, sep='', end='\t')
Task 3 . Print the multiplication table using the following � template.
Answer
for i in range(1, 10): # начало внешнего цикла � for j in range(1, 10): # начало вложенного цикла� # вывод таблицы умножения� print(i, '*', j, '=', i * j,end='\t’)
print() # переход на новую строку
Task 3 . Second solution
i = 1 # инициализация параметра внешнего цикла�while i < 10: # условие внешнего цикла� j = 1 # инициализация параметра вложенного цикла� while j < 10: # условие вложенного цикла � print(i, '*', j, '=', i * j, end='\t') # вывод� j += 1 # изменение параметра вложенного цикла� i += 1 # изменение параметра внешнего цикла� print() # переход на новую строку
Questions :
Tasks
Ex. 1 Write a program to display a pattern using a nested loop.
Sample:
Multiplication table of Pythagoras
Write program which outputs following:
Write a program using nested loop and continue to output the following:
Print following rectangle of stars
Print the first 10 numbers on each line 5 times. Use only nested for loop.
Reflection
What did I know? | What have I learned? | I had a hard time |
| | |
| | |
| | |
Questions