I am trying to write a function that prints a diagonal pattern. The arguments to this are:
This is what I have tried:
def pattern(s, r, g):
for i in range(r):
print(" " * g, ("*", " " * g) * s, end="\n")
But the output looks like this: for pattern(2,3,4) where 2 is the number of stars in each row, 3 is the number of rows and 4 is the number of gaps between the stars
('*', ' ', '*', ' ')
('*', ' ', '*', ' ')
('*', ' ', '*', ' ')
How can I execute this without the brackets?
You are printing out tuples. You need to unpack tuple using *
operator:
def pattern(s, r, g):
for i in range (r):
print(' ' * g, *('*', ' ' * g) * s, end='\n')
pattern(2, 3, 4)
Output :
* *
* *
* *
You can add one more loop
for i in range (r):
for j in range(s):
print('*', ' '*g, end='')
print('\n')
pattern(3,5,8)
Output :
* * *
* * *
* * *
* * *
* * *
Alternatively to printing out tuples / expanding the tuples, you could simply print a string built by concatenating the different string parts using +
, eg
def pattern(s, r, g):
for i in range(r):
print(" " * g + ("*" + " " * g) * s, end="\n")
pattern(2, 3, 4)
Output:
* *
* *
* *
Note that end="\\n"
is superfluous here, and there seems to be no diagonal pattern.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.