I am required to use nested for loops and print(\'*\', end=\' \')
to create the pattern shown here:
And here is my code. I have figured out the first t
for i in range (1,n): # loop will execute from 1 to 4(n-1)
for j in range(1,i+1):
print("*",end="")
print()
for i in range (n+1,1,-1):
for j in range(i,1,-1):
print("*",end="")
print()
The function:
def arrow(my_char, max_length):
for i in range(max_length*2):
if i <= max_length:
print(my_char*i)
if i > max_length:
print(my_char*(max_length*2-i))
The main():
def main():
print(arrow('*', 8))
if __name__ == "__main__":
main()
Output:
*
**
***
****
*****
******
*******
********
*******
******
*****
****
***
**
*
Both patterns C and D require leading spaces and you are not printing any spaces, just stars.
Here is alternative code that prints the required leading spaces:
print ("Pattern C")
for e in range (11,0,-1):
print((11-e) * ' ' + e * '*')
print ('')
print ("Pattern D")
for g in range (11,0,-1):
print(g * ' ' + (11-g) * '*')
Here is the output:
Pattern C
***********
**********
*********
********
*******
******
*****
****
***
**
*
Pattern D
*
**
***
****
*****
******
*******
********
*********
**********
In more detail, consider this line:
print((11-e) * ' ' + e * '*')
It prints (11-e)
spaces followed by e
stars. This provides the leading spaces needed to make the patterns.
If your teacher wants nested loops, then you may need to convert print((11-e) * ' ' + e * '*')
into loops printing each space, one at a time, followed by each star, one at a time.
If you followed the hints I gave about nested loops, you would have arrived at a solution for Pattern C like the following:
print ("Pattern C")
for e in range (11,0,-1):
#print((11-e) * ' ' + e * '*')
for d in range (11-e):
print (' ', end = '')
for d in range (e):
print ('*', end = '')
print()