If Statement

Code Fragment can be executed only if a certain condition is met.

Syntax

condition has a boolean type (True or False).

Basic Example

Output:

if condition is True - execute the code inside if fragment.

Comparison Operators

Operator Description Examples Result
== Equal to 5 == 5 True
4 == 5 False
'4' == 4 False
!= Not equal to 7 != 5 True
4 != 4 False
True != False True
> Greater than 5 > 0 True
5 > 5 False
10 > 0 True
>= Greater than or equal to 3 >= 3 True
5 >= 4 True
3 >= 5 False
< Less than 3 < 5 True
5 < 6 True
5 < 5 False
<= Less than or equal to 2 <= 0 False
5 <= 5 True
5 < 1 False

Let's create a program that uses comparisons operators.

Determine whether person is adult (age >= 21) or child (age < 13) depending on his/her age.

Output:

Since age is greater than 21, line 3 executes.

Because age is not less than 13, line 6 is not executed.

Indentation

If statement, without indentation, causes error:

In order to not throw exception, it needs to be rewritten like this: