0

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?

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.