Home > other >  How to repeat triangle pattern with increased number of rows in Python?
How to repeat triangle pattern with increased number of rows in Python?

Time:10-16

You are given two numbers, one indicates number of rows of the triangle made with "*". Second number indicates number of triangles the program will make but each next triangle needs to have one more row than a previous one.

Example of an input:

2
3

Example of an output:

*
**
*
**
***
*
**
***
****

CodePudding user response:

x=2
y=3
for a in range(y):
    for b in range(1,x a 1):
        for c in range(b):
            print('*', end='')
        print()

output

*
**
*
**
***
*
**
***
****

CodePudding user response:

A double for loop should be helpful in this question. We esentially have a case where we are repeating the same thing x number of times, but also adding 1 extra unit as we go (hence the rows = 1).

triangles = 3
rows = 2

for i in range(triangles):
    for i in range(1, rows   1):
        print("*" * i)
    
    rows  = 1

Note the range(1, rows 1). We do this because of 0th indexing. Rather than multiplying by zero initially, we want to multiply by 1.

  • Related