AppDividend
Latest Code Tutorials

How to Write Python inline if statement

0

The if-else statement in Python is logical. Python does not use the ternary operator for inline if statement as other language uses. Instead, it offers a one-line code to evaluate the first expression if the condition is true. Otherwise, it evaluates the second expression.

Python inline if

The inline if-else expression in Python contains two statements and executes one of them based on the evaluation of the condition. There two types of if statements in Python.

  1. Simple if statement
  2. if-else expression statement

In a simple, if statement, we writing a condition, and based on that condition, the if block will be executed.

if condition: statement
if condition:
    block

Let’s write an inline if statement in which if the condition is True, the expression will be executed.

Let’s see an example.

data = 21

if data < 22: print("It's cool")

Output

It's cool

You can see that we have written an inline if statement. But this statement does not contain else part.

Python inline if-else statement

The inline if-else expression in Python must contain an else clause.

x = 1 if y else 0

If you want to leave your ‘x’ variable value unchanged – assing old ‘x’ value.

Let’s see another example where we can write both if and else condition in inline.

data = 21
info = 19

print(data if info else 0)

Output

21

If the info is 0 then it will output in 0.

data = 21
info = 0

print(data if info else 0)

Output

0

That is it for Python inline if-else statement.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.