DEV Community

Shwetabh Shekhar
Shwetabh Shekhar

Posted on

Christmas Tree using Python

Merry Christmas Dev community. Here is a simple Christmas tree using Python.

# Christmas Tree in Python
for i in range(10):
    print(''.join(['.'] * (9 - i) + ['^'] * (1 + i * 2) + ['.'] * (9 - i)))
else:
    print(''.join(['-'] * 8 + ['| |'] + ['-'] * 8))

'''
                .........^.........
                ........^^^........
                .......^^^^^.......
                ......^^^^^^^......
                .....^^^^^^^^^.....
                ....^^^^^^^^^^^....
                ...^^^^^^^^^^^^^...
                ..^^^^^^^^^^^^^^^..
                .^^^^^^^^^^^^^^^^^.
                ^^^^^^^^^^^^^^^^^^^
                --------| |--------
          Merry Christmas to all of you. @shwetabh1
'''
Enter fullscreen mode Exit fullscreen mode

There is no use of the else clause but I have used it deliberately, to expose it to devs who are yet not aware of it.

The else clause executes after the loop completes normally. It is useful in cases when we break from a loop. You can read more about it here.

Top comments (6)

Collapse
 
chrisgreening profile image
Chris Greening

lol I like that you added the else clause just so others can learn πŸ™Œ

Collapse
 
shwetabh1 profile image
Shwetabh Shekhar

Thanks. I also discovered it a bit late so wanted to share it with others.

Collapse
 
chrisgreening profile image
Chris Greening

I didn't know about it until almost 2 years of learning Python, certainly a nifty hidden gem; the same goes for try-except secretly being try-except-else-finally lol

Thread Thread
 
shwetabh1 profile image
Shwetabh Shekhar

haha didn't know about the else part in the try-except as well. thanks

Collapse
 
waylonwalker profile image
Waylon Walker

Super fun project

Collapse
 
shwetabh1 profile image
Shwetabh Shekhar

Thank you :)