Snake_Byte #26: Python for Javascript Developers (If/Else)

When I joined the team at PokitDok, I was primarily a front-end developer, and although I had lots of experience with Javascript, I had never worked with Python. This meant lots of hours of staring at .py files, searching on Google for answers, and asking for help in Slack. This post intends to introduce someone who works with Javascript to Python, and to note just how similar they are, if you can adapt to the syntax differences. Let's start with the most basic algorithm:

If/else
The most important differences in an if/else statement between Javascript and Python are indentation and line-breaks. Javascript doesn't care if you use 10 lines with 10 line-breaks or 1 line with no line-breaks or indentation. Python, on the other hand, cares very much how many lines, line-breaks, and on which indentation line you are putting something. Each line in a block of code must be indented by the same amount.

In Javascript, you can do whatever you want:

In Python, you have to pay attention to line breaks and indentation:

If you paid attention to the last example you'll notice some other things too:

  • Don't use parentheses on the if/else statement conditional
  • Instead of containing an if/else with curly braces, start it with : and indent anything after that to include in the if statement, end it by going back to the original line indent

Since there aren't any parentheses used for a if/else statement in Python, conditional statements are more conversational and easier to read at a glance. Instead of using && and || like you would in Javascript, you can just use and and or. Instead of using ! to note the opposite of a variable, use not. There is also a more conversational way to check for a null object in Python, using is (not) None.

Check for null in Javascript:

Check for null in Python:

Now you might be asking, what about the else part of the if/else statement? Simple, go back to the same indentation line that the if starts on, add an else:, then indent anything after that to include in the else block. End the block by returning to the same line that the original if started on. The syntax for an else if is a little different, using elif instead of the Javascript else if, but other than that it's the same Python structure.

Full example:

This is by no means a comprehensive overview of a Python if/else structure, but I hope it can help someone who is familiar with Javascript and wants to get into the Wonderful World of Python (theme park opening soon). I know this post would have helped me immensely when I was getting started, and I hope it helps you too!

For further reading, check out the style guide for Python.

Leave a Reply

Your email address will not be published.