Reputation: 27
Python newbie here. I Got an exercise to write a function that receives 2 parameters, the first is a single note string, and the other is the max length(int) of the middle row. (i.e arrow(my_char, max_length) Basically the function is supposed to return an "arrow formation". I'm supposed to use a for loop for this. for ex. the print for print(arrow("*", 5)) is supposed to be:
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
What I've done so far:
for i in range(1, max_length + 1):
print (my_char * i)
for i in range(max_length, 1, -1):
print (my_char * i)
I got the formation right, but the formation is not returned and I need to add spaces between the asterisks.
Upvotes: 1
Views: 277
Reputation: 83
Following your question description and what you did, it appears that to works properly the argument of print()
in your second for loop must be my_char*(i-1)
instead of my_char*i
. Then you can add spaces between asterisks, and tie all into a function taking 2 parameters as follows:
def arrow(my_char, max_length):
for i in range(1, max_length + 1):
print(" ".join(my_char * i))
for i in range(max_length, 1, -1):
print(" ".join(my_char * (i-1)))
Example: If you take my_char = "*"
and max_length = 5
, the function arrow(my_char, max_length)
will output:
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
Upvotes: 1
Reputation: 380
One of many answers would be like this:
def arrow(char, length):
for i in range(length):
for j in range(i):
print(char + ' ', end='')
print ()
for i in range(length,0,-1):
for j in range(i,0,-1):
print(char + ' ', end='')
print ()
Upvotes: 0