
The if statement is the simplest form of decision control statement that is frequently used in decision making. An if statement is a selection control statement based on the value of a given Boolean expression.
The general form of a simple if statement is shown below.
if test_expression:
statement 1
..........
statement n
statement x
The if structure may include 1 statement or n statement enclosed within the if block. First the test expression is evaluated. If the test expression is True, the statement of if block (statement 1 to n) are executed otherwise these statements will be skipped and the execution will jump to statement x.
Let’s write a program that increment a number if it is positive.
x = 10 # initialize the value of x
if (x > 0): # test the value of x
x = x + 1 # increment the value of x if it is > 0
print(x) # print the value of x
#output
11
In the above code, we take a variable x and initialize it to 10. In the test expression we check if the value of x is greater than 0. If the test expression evaluates to True, then the value of x is incremented. Then the value of x is printed on the screen.
Observe that the print statement will be executed even if the test expression is False. Python uses indentation to form a block of code.