Python – If-Else Statements

If Statement

Python – If-Else Statements: When a condition is assessed as true, the If statement is used to run a block of code. The software will bypass the if-code block if the condition is found to be untrue.

Syntax

if condition:
  statements

Flow Diagram:

Python If Loop

In the following example, an if code block is written that only runs when the variable I is divisible by 3.

i = 15
if i % 3 == 0:
  print(i," is divisible by 3.")

The output of the above code will be:

15 is divisible by 3.

If-else Statement

Python – If-Else Statements: With an, if statement, the else statement is always utilised. When an if condition returns a false result, it is used to run a block of code.

Syntax

if condition:
  statements
else:
  statements

Flow Diagram:

Python If-else Loop

The else statement is used in the example below to print a message if the variable I is not divisible by three.

i = 16
if i % 3 == 0:
  print(i," is divisible by 3.")
else:
  print(i," is not divisible by 3.")

The output of the above code will be:

16 is not divisible by 3.

Elif Statement

The elif statement is used to add further criteria. The programme begins by examining the if condition. It checks elif conditions if false is detected. If all of the elif conditions are false, then the else code block is run.

Syntax

if condition:
  statements
elif condition:
  statements
...
...
...
else:
  statements

Flow Diagram:

Python If-elif-else Loop

The elif statement is used in the example below to add further criteria between the if and else statements.

i = 16
if  i > 25:
  print(i," is greater than 25.") 
elif i <=25 and i >=10:
  print(i," lies between 10 and 25.") 
else:
  print(i," is less than 10.")

The output of the above code will be:

16 lies between 10 and 25.

Short hand if

When there is just one statement to execute, like in the example below, the code can be written in a single line.

i = 15
if  i % 3 == 0 : print(i," is divisible by 3.")

The output of the above code will be:

15  is divisible by 3.

Short hand if-else

Python – If-Else Statements: When both if and else only need to execute one sentence, the code can be put in a single line, as seen in the example below.

i = 16
print(i," is divisible by 3.") \
  if  i % 3 == 0 else print(i," is not divisible by 3.")

The output of the above code will be:

16  is not divisible by 3.

 

Also Read: Java – Exceptions

Leave a Reply

Your email address will not be published. Required fields are marked *