user2101517
user2101517

Reputation: 720

Creating shapes with while loop Python

What I am trying to do is use a while loop to create a square out of asterixs, the code below will print the square filled in, but what I want it to do is print the square unfilled

a='square'
b='unfilled'
c=4
num=0
asterix='*'
while a=='square' and b=='unfilled' and int(num)<int(c):
    num+=1
    print(asterix*int(c))

What the code does:

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

What I want the code to do:

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

Any help would be much appreciated

Upvotes: 0

Views: 4508

Answers (2)

Nick Burns
Nick Burns

Reputation: 983

I know this was answered a long time ago, but I am going through some of my earlier class exercises too and trying to use some of the new things I have learned along the way.

This reminds me a lot of one of my exercises and I eventually answered it similar to the answer above. Since then I have discovered a nice way to write this using a generator:

n = 4
table = ("*  *" if i not in [0, n] else '****' for i in range(n+1))
for row in table: print(row)

You would probably want to generalise this too so that it worked for a variable size, n.

Upvotes: 1

kke
kke

Reputation: 363

    n = 4
    s = "*"
    for i in range(0,n,1):
        if i == 0 or i == n-1:
            print(s*n)
        else:
            print(s+(" "*(n-2))+s)

This should do what you want to. You don't have to convert everything correct.

Upvotes: 1

Related Questions