So far, I have:

def printSquare(x,y):
        for z in range(0,x):
                print(x*y)

printSquare(3,'%') prints out something like this:

%%%
%%%
%%%

instead of using the '*' operation, is there a way to print x numbers of y separated by commas (for better spacing) ie: print(y,y,y)?

Recommended Answers

All 4 Replies

# python 3
print(*(y,) * x, sep=",")

This prints it out with the commas as though it were a string while print(y,y,y) doesn't print out the commas but interprets them as spaces.

after changing your code, I found that

print(*3*(y,))

gives the desired result. What does the '*' before the 3 mean? when I left it out, it returned:
print(3,'%')
('%','%','%')

after changing your code, I found that

print(*3*(y,))

gives the desired result. What does the '*' before the 3 mean? when I left it out, it returned:
print(3,'%')
('%','%','%')

In the python console

>>> def printSquare(x,y):
...  for z in range(0,x):
...   print(*(y,)*x, sep=",")
... 
>>> printSquare(3, "%")
%,%,%
%,%,%
%,%,%

The * is used when you pass a sequence of arguments to a function. print(*(y,y,y)) is the same as print(y,y,y) ,
but the argument list doesn't need to be written explicitly. For example

my_tuple = ('a', 'b', 'c')
print(*my_tuple) # prints a b c, identical to print('a','b','c')
print(my_tuple) # prints ('a', 'b', 'c'), identical to print(('a','b','c'))
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.