Python - If-Else Statements

Python - If-Else Statements


Previous Page

If Statement

The If statement is used to execute a block of code when the condition is evaluated to be true. When the condition is evaluated to be false, the program will skip the if-code block.

Syntax


if condition:
  statements

Flow Diagram:

Python If Loop

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

Output

15 is divisible by 3.

If-else Statement

The else statement is always used with If statement. It is used to execute block of codes whenever If condition gives false result.

Syntax


if condition:
  statements
else:
  statements

Flow Diagram:

Python If-else Loop

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

Output

16 is not divisible by 3.

elif Statement

elif statement is used to tackle multiple conditions at a time. For adding more conditions, elif statement in used. Please see the syntax.

Syntax


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

Flow Diagram:

Python If-elif-else Loop

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.")

Output

16 lies between 10 and 25.

Short hand if

When if has only one statement to execute, the code can be written in a single line as described In the below example.

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

Output

15  is divisible by 3.

Short hand if-else

When if and else both have only one statement to execute, the code can be written in a single line as described In the below example.

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

Output

16  is not divisible by 3.




Recommended Pages

  • Next Page


Previous Page