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:

The simplest example for this would be:

output

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.

output

Now if we try adding else statement in the same line then it will give invalid syntax error.

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.

Leave a Reply