One-Line "if" Statements
You may come across one-line if
-statements in the wild.
In this lesson, you’ll learn the syntax of one-line if
-statements and if they have any advantages or disadvantages over using multi-line if
-statements.
00:00
We are moving right along! Section 3: One Liners. So, here’s the thing. It is possible to write your entire if
statement on one line. And you don’t have to use these, but I wanted to leave them in because you might come across them in the wild.
00:19
So, let’s take a look at the syntax. So, a basic if
statement, instead of the statement being on the second line and being indented, just follows the expression with a space between it and the colon (:
).
00:34
When we want our if
statement to kick off multiple statements, we set it up like this with a semicolon (;
) between each statement.
00:45
When we want to use else
and elif
, those too get put on to single lines. And, again, if we want to run multiple statements after those, we separate them with a semicolon. So, that’s one-line syntax in a nutshell. There’s no real advantage or disadvantage to using these.
01:05 It’s purely for readability and preference, so it’s up to you. And perhaps if you’re working for a company, it could be dictated by their style guide. So, this is just something to more be aware of than, say, something dictated by universal Python law.
Become a Member to join the conversation.