Python if else statement

Python if else is the most commonly used selection statement in writing scripts. Reason is that there is are some limitation of if statement which as:

  • if statement cannot be used for checking multiple conditions one after another.
  • if statement will only check TRUE case.

In the light of these limitations every high level programming language provide feature of if else statement. When we use if else statement it execute one statement/set of statements when condition is  TRUE  and other statements when given condition is  FALSE .

Syntax if else:

if  expression / condition :

       statement for TRUE case

else:

       statement for FALSE case

Where statement for True case will be executed when the given expression will TRUE, else these statements will be skipped and statements after else part will be executed.

Example if else:

# Use of if else statement

x = -10
if x > 0:
    print("Number is positive")
else:
    print("Number is negative")

Output:

Output of given if else script will be as.

Number is negative

Python if else one line:

Python language also provide a short way to write if else statement in single line, that may be convenient and easy to understand.

Syntax:

Statement  if  expression  else  statement

We can also use variable as LValue in single line if else statement. It will automatically assign TRUE case or FALSE case value to the LValue variable.

Example 1:

This example code will check even or odd value. According to the given lines of code it wil print Odd on the screen as we are checking variable a which is 11.

# Use of if else in single line statement

a = 11
print("Even") if a % 2 == 0 else print("Odd")

Output:

Odd

Example 2:

In this example we are goining to assign value to variable x, which is written on the left side of if else statement. Depending on condition result result it will assigin 0 or value of variable a to x. In this case it will return 14 (value of a). And variable x wil hold 14.

# Use of assignment with if else statement

a = 14
x = 0
x = a if a % 2 == 0 else 0
print(x)

Output:

14

Python if elif

In python if we want to match multiple conditions then we use if elif statement. Where elif refers to else if statement. In this situation first  condition is matched if it does not match then elif condition will be evaluated. In the similr way there may be multiple elif statements for multiple conditions.

Example if elif:

# Use of if elif else

x = 14
if x > 100:
    print("Greater than 100")
elif x > 50:
    print("Greater than 50, Less than 100")
elif x > 0:
    print("Greater then 0, Less than 50")
else:
    print("Number is negative")

Output:

Greater then 0, Less than 50

if elif else

In python we can also use else statement as the default statement if any of the given conditions does not match. This else statement comes at the end of if elif statement.

 
 
Comments
Login to TRACK of Comments.