Python One-line if-else Statements

Python One-line if-else Statements:

 

  • The conditional operator – also known as the ternary operator – is an alternative form of the if/else statement that helps you to write conditional code blocks in a more concise way.
  • The name “ternary” means there are just 3 parts to the operator: condition, then, and else.
  • You cannot use Python if..elif..else block in one line.
  • The major disadvantage of using this if-else one-line statement is, it reduces the readability of the code.
  • Although there are hacks to modify if..elif..else block into if..else block and then use it in a single line but that can be complex depending upon conditions and should be avoided.

 


 

 


 

One Line If-Else Syntax:

Syntax

item01 if condition else item02

 

01. Example

  • In this expression, we are using if….else statement in a single line.
  • If the value of x is ‘zeroones’ then the expression will return ‘True’.
  • If the value of x is not ‘zeroones’ then the expression will return ‘False’.
web = 'zeroones'
'True' if web=='zeroones' else 'False'

Output:

'True'

 

02. Example

  • In the above example, we created a newData where we filter the list to exclude the negative values, using the if statement.
data = [-10,-20,30,40,50]
newData = [i for i in data if i>=0]
print(newData)

Output:

[30, 40, 50]

 


 

One Line If-Elif-Else Syntax:

Syntax:

We write the if-elif-else statement as per the below syntax:

  • First of all, condition02 is evaluated. If condition02 returns True then expression02 is returned.
  • If condition02 returns False then condition01 is evaluated. If condition02 returns True, then expression01 is returned.
  • If condition01 also returns False then else is executed and expression03 is returned.
expression01 if condition01 else (expression02 if condition02 else expression03)

 

01. Example

In the below example, we are saying that print 2 if data>50, Elif print 1 if data<50, else print 0.

data = int(input('Enter A Number: '))
result = 2 if data>50 else (1 if data<50 else 0)
print (result)

Output:

Enter A Number: 70
2

 


 

One Line Nested If-Else Syntax:

Syntax

For nested if-else conditions, we know the below syntax:

expression01 if condition01 else expression02 if condition02 2 else (expression03 if condition03 else expression04 if condition04 4 else expression05)

 

01. Example

data = int(input("Enter A Number: "))
result = "equal to 100" if data == 100 else "equal to 50" if data == 50 else ("greater than 100" if data > 100 else "less than 100")
print(result)

Output:

Enter A Number: 55
less than 100

 

Leave a comment