0%

Python-using repetition structures nest loop to print patterns

Two repetition structures in python:

  • while loop
  • for loop

    Nest loop

    For loop has a nest loop function. clock is a good example.
    Nest loop can use to print some patterns.
    Some examples:
pattern 1
1
2
3
4
5
6
rows = int(input('how many rows?'))
cols = int(input('how many columns?'))
for r in range(rows):
for c in range(cols):
print('*',end='')
print()

after input rows and clos value 6, runing code, it will show

1
2
3
4
5
6
******
******
******
******
******
******
pattern 2
1
2
3
4
5
6
7
*
**
***
****
*****
******
*******

code as following:

1
2
3
4
5
base_size = 7
for r in range(base_size):
for c in range(r+1):
print('*',end='')
print()
pattern 3: up side down triangle:
1
2
3
4
5
6
7
*******
******
*****
****
***
**
*

code like this:

1
2
3
4
5
6
7
8
9
rows =7
cols =7

for i in range(rows):
#num_of_star = cols - i
#print('*' * (cols - i))
for j in range(cols - i):
print('*', end='')
print()
pattern 4:
1
2
3
4
5
6
*
*
*
*
*
*

code for this pattern is:

1
2
3
4
5
num_step =6
for r in range(num_steps):
for c in range(r):
print(' ',end='')
print('#')
pattern 5
1
2
3
4
5
6
**
* *
* *
* *
* *
* *

code for this patter is:

1
2
3
4
5
6
7
col = 6
raw = 6
for a in range(raw):
print('#',end='', sep='')
for b in range(a):
print(' ', end='', sep='')
print('#')