# Python Tutorial 07: Comparison using the If statement in Python

To compare between two values, we need to write an if statement. There are three types of if statements

1. Simple if statment
2. if-else statement
3. it-elif statement

Following example illustrated the difference between all three statements

Following is our results:

## Simple if statement

Following is the syntax of a simple if statement

If (Condition)

Blocks to execute

[vtftable ]
X =;;;1;;;0;;;-1;nn;
Output;;;Simple If Statement{;n}1 is positive{;n}1 is positive (duplicated);;;Simple If Statement;;;Simple If Statement;nn;
Reason;;;Condition matched;;;Condition NOT matched;;;Condition NOT matched;nn;
[/vtftable]

## If-else statement

Following is the syntax of a if-else statement:

If (Condition)

Execute when True

ELSE

Execute when False

[vtftable ]
X =;;;1;;;0;;;-1;nn;
Output;;;If-Else Statement{;n}1 is positive{;n}1 is positive (duplicated);;;If-Else Statement{;n}0 is NOT positive{;n}0 is NOT positive (duplicated);;;If-Else Statement{;n}-1 is NOT positive{;n}-1 is NOT positive (duplicated);nn;
Reason;;;It matched to the condition;;;It doesn’t match with the condition, so it executed the else statement;;;It doesn’t match with the condition, so it executed the else statement;nn;
;;; ;;; ;;; ;nn;
[/vtftable]

## If-elif statement

Following is the syntax of a if-else statement:

If (Condition)

Execute when True (Condition 1)

ELif (Condition2)

Execute when True (Condition 2)

Else

Execute when False (Both Condition 1 and 2)

[vtftable ]
X =;;;1;;;0;;;-1;nn;
Output;;;If-Elif Statement{;n}1 is possitive{;n}1 is positive (duplicated);;;If-Elif Statement{;n}0 is zero{;n}0 is zero (duplicated);;;If-Elif Statement{;n}-1 is negative{;n}-1 is negative (duplicated);nn;
Reason;;;Condition 1 Matched;;;Condition 2 Matched;;;Both condition 1 and 2 is not matched;nn;
;;; ;;; ;;; ;nn;
[/vtftable]

Note: Unlike other languages, indentation in Python is extreme important, Python is using indentation to identify boundary of each blocks while other language may simply use it for readability purposes. In Python, you my have unpredictable result for simply a wrong indentation.

This site uses Akismet to reduce spam. Learn how your comment data is processed.