Sunny
Sunny

Reputation: 51

Nested Loop in Python Not Working

I would like to have this output:

* * * 
2 2 2 
4 4 4  
6 6 6 
8 8 8

I cannot get it and I've tried many ways, but my code doesn't seem to work. Here is my current code:

for row in range(3):
    print ("*", end = " ")
    print ()
    for col in range(2,9,2):
        print (row, end = " ")
        print ()
print()

What do I do?

Upvotes: 0

Views: 364

Answers (3)

vishes_shell
vishes_shell

Reputation: 23484

print('* * *') 
for col in range(2,9,2):
    print (*[col]*3, sep=' ')

To be more clear.

>>> a = 2
>>> [a]
[2]
>>> [a]*3
[2, 2, 2]
>>> print(*[a]*3, sep=' ')  # equal to print(a, a, a, sep=' ')
2 2 2

Upvotes: 0

Juxhin
Juxhin

Reputation: 5600

For a start, you only have one row that contains * * * which can be printed at the very top, outside of any loops:

print('* * *')

Next, you would need to start your loop from values 2 (inclusive) and 9 (exclusive) in steps of 2:

for col in range(2,9,2):

You don't need to use any end keyword here, so just printing the row multiple times is sufficient:

print('{0} {0} {0}'.format(i))

So the final block of code looks like:

print('* * *')
for row in range(2,9,2):
    print('{0} {0} {0}'.format(row))

You don't need to add another print(), print already ends with a newline anyway.

Upvotes: 0

Patrick Haugh
Patrick Haugh

Reputation: 60944

I don't see why you are using end in your print statements. Keep in mind that you must print line by line. There is no way to print column by column.

print('* * *')
for i in range(2, 9, 2):
    print('{0} {0} {0}'.format(i))

For further explanation about the {0}s, look up the format method for strings: https://docs.python.org/2/library/string.html#format-string-syntax

Upvotes: 2

Related Questions