Reputation: 65
I need to print a tree shape where the user inputs 4 different parameters. Branch height, branch width, stem height and stem width. I have two shapes that form the top part and bottom part of the tree but I can't seem to figure out how to put them together so that it looks like a tree. I figured that I need to calculate the width of the branch and deduct the stem from that but I'm not exactly sure. My output currently looks like this:
Any suggestions?
Enter height of the branches: 5
*
***
*****
*******
*********
Enter width of the stem: 5
*****
*****
*****
*****
*****
def pyramid(height):
for row in range(height):
for count in range(height - row):
print(end=" ")
for count in range(2 * row + 1):
print(end="*")
print()
def square(width):
for i in range(width):
for j in range(width):
print('*', end='')
print()
height = int(input("Enter height of the branches: "))
pyramid(height)
width = int(input("Enter width of the stem: "))
square(width)
Upvotes: 1
Views: 67
Reputation: 34026
You are looking for str.center(width\[, fillchar\])
:
def pyramid(height):
for row in range(height):
print(('*' * (2 * row + 1)).center((2 * height + 1)))
def square(width, height):
for i in range(width):
print(('*' * (width)).center((2 * height + 1)))
height = int(input("Enter height of the branches: "))
pyramid(height)
width = int(input("Enter width of the stem: "))
square(width, height)
Out:
C:\_\Python363-64\python.exe C:/Users/MrD/.PyCharm2018.2/config/scratches/scratch_75.py
Enter height of the branches: 5
*
***
*****
*******
*********
Enter width of the stem: 5
*****
*****
*****
*****
*****
Process finished with exit code 0
Upvotes: 1
Reputation: 21
may be try this :
def pyramid(height):
for row in range(height):
for count in range(height - row):
print(end=" ")
for count in range(2 * row + 1):
print(end="*")
print()
def square(width):
if height % 2 == 0:
space=int((height/2))*' '
else:
space=int((height/2)+1)*' '
for i in range(width):
print(end=space)
for j in range(width):
print('*', end='')
print()
height = int(input("Enter height of the branches: "))
width = int(input("Enter width of the stem: "))
pyramid(height)
square(width)
Upvotes: 2
Reputation: 106465
You can add white spaces before each line of the stem that are enough to fill the height of the pyramid minus half the width of the stem:
def pyramid(height):
for row in range(height):
for count in range(height - row):
print(end=" ")
for count in range(2 * row + 1):
print(end="*")
print()
def square(width, pyramid_height):
for i in range(width):
print(' ' * (pyramid_height - width // 2), end='')
for j in range(width):
print('*', end='')
print()
height = int(input("Enter height of the branches: "))
pyramid(height)
width = int(input("Enter width of the stem: "))
square(width, height)
Upvotes: 1