In this post, we will discuss how can we write a single line If python statement.
The general syntax for single-line If python statement is:
1 | <statement_when_true> if <condition> else <statement_when_false> |
The simplest example for this would be:
1 2 | animal = "dog" print("Yes") if animal == "dog" else print("No") |
output
1 | 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 standard python if as single line. Let’s see an example.
1 2 | animal = "dog" if animal == "dog": print("Yes") |
output
1 | Yes |
Now if we try adding else statement in the same line then it will give invalid syntax
error.
1 2 | 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.
If you have any doubts or suggestion then please comment below.