Summary: In this python tutorial, we will learn to write a single line if statement in Python with examples.
The general syntax for single-line If statement in Python is:
if else
The simplest example of this would be:
animal = "dog"
print("Yes") if animal == "dog" else print("No")
Output: Yes
Now if we try writing the single line if statement then it will give invalid syntax error, hence it is usually termed as ternary operator expression than an if-else statement.
If you are confused with the above statement, you can still use the standard python if
statement as a single line. Let’s see an example.
animal = "dog"
if animal == "dog": print("Yes")
Output: Yes
Now if we try adding else statement in the same line then it will give invalid syntax
error.
animal = "dog"
if animal == "dog": print("Yes") else: print("No")
File "main.py", line 2
if animal == "dog": print("Yes") else: print("No")
^
SyntaxError: invalid syntax
Because of this reason, programmers usually don’t like writing a single line ‘if statement’ in Python.