3 Replies - 13530 Views - Last Post: 09 May 2011 - 12:10 PM Rate Topic: -----

#1 Ais17  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 09-May 11

Nested While loops to make star patterns

Posted 09 May 2011 - 03:30 AM

Hi. I am a beginner at this and am having trouble with nested while loops. I am trying to print a pattern made out of the * symbols but the symbol will not print no matter how many times i try.

This is an example of the question i am working on.

Use nested loops to print out the following pattern.
******
****
**

This is what ive done so far.

i=0
while i <=3:
    j=0
    while j<=2:
        print "i:", i,"j;" ,j , "j.i:", j*i
        j=j+1
    i=i+1   
        



i dont know how to integrate the * into it.

Is This A Good Question/Topic? 0
  • +

Replies To: Nested While loops to make star patterns

#2 LiveToCode  Icon User is offline

  • New D.I.C Head

Reputation: 11
  • View blog
  • Posts: 37
  • Joined: 17-March 10

Re: Nested While loops to make star patterns

Posted 09 May 2011 - 06:58 AM

Ask yourself these questions:

1. How many times does the outer loop executes?
2. For each loop of the outer loop, how many times does the inner loop executes? (This is dependent on the outer loop)
Was This Post Helpful? 0
  • +
  • -

#3 Nallo  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 163
  • View blog
  • Posts: 255
  • Joined: 19-July 09

Re: Nested While loops to make star patterns

Posted 09 May 2011 - 07:55 AM

As for printing a * without also printing a newline or a space at the end:
print "",
for i in range(4):
    print "\b*" #the \b means backspace. We have to get rid of the space created by 
                #the comma in print "*",
                #will not work in idle, as idle messes up the \b control character
print #print a newline, once we are done with the current line


Was This Post Helpful? 0
  • +
  • -

#4 atraub  Icon User is offline

  • Pythoneer
  • member icon

Reputation: 759
  • View blog
  • Posts: 2,010
  • Joined: 23-December 08

Re: Nested While loops to make star patterns

Posted 09 May 2011 - 12:10 PM

For loops are far better suited for this task, but if you must use while loops, I would probably use an approach like this:

i=0
while i <=3:
    j=3
    while j>=0:
        print '*'*(2*j)
        j=j-1
    i=i+1   



Identical code using for loops:
for i in range(4):
    for j in range(3,-1,-1):
        print '*'*(2*j)



And here's your output:
******
****
**

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

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

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

This post has been edited by atraub: 09 May 2011 - 12:20 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1