Python Forum
Nested while loop in pyramid program.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Nested while loop in pyramid program.
#1
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
Reply
#2
The last statement should be in the body of the while loop started at line 5.
Reply
#3
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Big O runtime nested for loop and append yarinsh 4 1,394 Dec-31-2022, 11:50 PM
Last Post: stevendaprano
  Noob here. Random quiz program. Using a while loop function and alot of conditionals. monkeydesu 6 1,395 Sep-07-2022, 02:01 AM
Last Post: kaega2
  Nested for loops - help with iterating a variable outside of the main loop dm222 4 1,593 Aug-17-2022, 10:17 PM
Last Post: deanhystad
  Python Program to Find the Total Sum of a Nested List vlearner 8 4,922 Jan-23-2022, 07:20 PM
Last Post: menator01
  How do I add another loop to my nested loop greenpine 11 4,572 Jan-12-2021, 04:41 PM
Last Post: greenpine
  Error on nested loop : Invalid syntax dvazquezgu 3 3,238 Nov-25-2020, 10:04 AM
Last Post: palladium
  how to install pyramid.arima in jupyter notebook bntayfur 1 4,180 Aug-06-2020, 04:37 AM
Last Post: ndc85430
  Nested loop indexing Morte 4 3,919 Aug-04-2020, 07:24 AM
Last Post: Morte
  Try-except in while loop: error with closing program Lupin_III 7 2,874 Jul-03-2020, 10:57 AM
Last Post: Lupin_III
  Nested for loop not looping puttingwordstogether 0 1,715 Jun-16-2020, 11:15 PM
Last Post: puttingwordstogether

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020