Using for loops to create a christmas tree
Solution 1
OK, you have two problems. First, when you go to do your indentation, you write:
print('',end='')
In python (and other languages), ''
is an empty string. You should use ' '
.
Second, your x
incrementing logic seems to be wrong. Simply adding 2
each loop works fine, making your program:
def holidaybush(n):
z=n-1
x=1
for i in range(0,n):
for i in range(0,z):
print(' ',end='')
for i in range(0,x):
print('+',end='')
for i in range(0,z):
print(' ',end='')
x=x+2
z=z-1
print()
holidaybush(5)
Your code can be made more compact by:
- Using infix operators, replacing
x=x+2
withx+=2
range
automatically starts at zero, sorange(0,z)
can be replaced withrange(z)
- Using string multiplication, replacing your inner
for
loops with' ' * z
Applying these results in:
def holidaybush(n):
z = n - 1
x = 1
for i in range(n):
print(' ' * z + '+' * x + ' ' * z)
x+=2
z-=1
holidaybush(5)
But you might want to stick with the verbose version.
Solution 2
how about this:
def holidaybush(n):
for i in range(n):
print ' ' * (n - (i + 1)),'+' * (2*i+1)
holidaybush(5)
Solution 3
You could use string.center()
, just for adding another solution, this made the code more compact:
def holidaybush(n):
for i in range(n):
print(("+" * (i * 2 + 1)).center(n * 2 - 1))
holidaybush(5)
Solution 4
This is the very simplest code to draw Christmas tree:
for i in range(1,20,2):
print(('*'*i).center(20))
for leg in range(3):
print(('||').center(20))
print(('\====/').center(20))
Admin
Updated on February 21, 2022Comments
-
Admin about 2 years
I am trying to create a program where you enter a number and the program creates a "christmastree" arrangement of +'s. For example if I enter the number 5 the program should print:
+ +++ +++++ +++++++ +++++++++
What I have so far is:
def holidaybush(n): z=n-1 x=1 for i in range(0,n): for i in range(0,z): print('',end='') for i in range(0,x): print('+',end='') for i in range(0,z): print('',end='') x=x*2 x=x-1 z=z-1 print() holidaybush(5)
It does not work quite the way I expect, even though I go through the logic and it seems to work in my head. Any help? I just learned for loops today so I may not know everything about them.