Short Hand If Condition

If there is only one statement to test than we use shorthand if condition and it can be placed only in single line Like.

if a > b: print("a is greater than b")

This code will check either a is greater than b or not after comparing it will print “a is greater than b”

Short Hand If , Else

If there is only one statement one for if and one for also it can also be place in one same line for Example.

num_1 = 2
num_2 = 40
print("A") if num_1 > num_2 else print("B")

In this one line code program will print A if num_1 is greater than num_2 and Print B in else case.

Note: This method is similar to ternary operators.

One Line if, else with 3 condtions

num_2 = 330
num_1 = 330
Print("A") if num_1 > num_2 else print("=") if num_1 == num_2 else print("B")

In this statement program first check if num_1 is greater than num_2 than it will print A and remaining statement will not execute if this statement will become false than in else block there is another if statement that will check if num_1 is equal to num_2 than it will print = sign and at the end in last else it will print B .

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s