DEV Community

loading...

Christmas Tree using Python

shwetabh1 profile image Shwetabh Shekhar ・1 min read

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.

Discussion (6)

pic
Editor guide
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 Author

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 Author

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