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
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 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
else if, but other than that it's the same Python structure.
For further reading, check out the style guide for Python.