Python Forum

Full Version: Nested while loop in pyramid program.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi All,

I am learning python using Python 3.6.1 by online complier.

I have a doubt about the below pyramid program.
------------------------------------------------
I = 1
j = 1 
rows = 5 
count1 = '*' 
while I < 5: 
    while j < I: 
       print count1 
       j = j + 1 
I = I + 1
------------------------------------------------
1,It is not running as expected.it seems to be hanging.
2,It is very difficult to align space in loop statement.somewhat confusing it.

I have seen few pyramid programs in the google.com.But i used the above same logic in C language.
Hence,anyone please where is the mistake

Any Suggestions.


Thanks & Regards,
Raj
The last statement should be in the body of the while loop started at line 5.
The problems you have is that you print a new line for each "*" and that you do not set j = 0 for each outer loop iteration. The spaces can be done this way:
while I < rows:
     out = ''.join((rows - I) * [' '])
     j = 0
     while j < I:
         out = '%s%s ' % (out, count1)
         j += 1
     print out
     out = ''
     I += 1
The spaces in each layer can be set as the number of rows - I. create a list holding that many " " and join them, now you have the spaces. now for the '*' you have to reset j for each outer iteration since you want to print I '*' on each layer and j has to start counting again for each outer iteration