If Statement in Python | Syntax, Example

An if statement in Python is the simplest decision-making statement that allows the programmer to execute a block of statements only if some condition is true.

We use if statement in the Python program to compare data and to make a decision based on the result of comparison.

If statement has one test condition and one action. If the test condition is true, the statements followed by a condition will execute and skip them if the condition is false. It is also called a conditional statement or single selection statement in Python because it either selects or ignores the action.

Syntax of if Statement in Python


If statement in Python consists of a boolean expression followed by one or more statements. The general syntax for using the if statement is as follows:

if test_condition:
    Python statement(s) to be executed if condition is true.
or,
if(test_condition):
    statement(s)

In the above expression,

a) The test condition consists of a boolean expression that returns a boolean value, either true or false.

b) The test condition may contain any relational comparison that comprises relational or comparison operators like <, >, <=, >=, etc. A relational operator compares two values, variables, or complex expressions.

c) If the test condition is true, the block of statements inside the if statement executes. If the test condition is false, the block of statements skips or bypass.

d) It is optional to enclose the test condition with a pair of braces ().

e) A block of if statement (also called a body of if statement) is a sequence of statements. All the statements must be intended with the same number of white spaces (called indentation). The indentation in Python shows the body of if statement. IDLE adds indentation automatically after a colon ‘:’.

f) However, you can choose how many white spaces to use when intending the block of if statement. Generally, we use two or four white spaces for intending, but you can use one space or several spaces if you prefer.

Flowchart Diagram of If statement in Python


Look at the below figure, where you can see the Python if statement flowchart diagram.

Flow chart diagram of if statement in Python

Let’s understand the single selection if statement with the help of an example. Consider the following example code as given below.

myPer = 92
if myPer >= 80:
print("Grade A")

If the boolean expression (test condition) evaluates to true, the intended statement will execute and print the message “Grade A” on the console.

After executing the intended statement inside the block of if statement, the next Python statement in the sequence executes.

If the boolean expression evaluates to false, the intended statement will not execute and the next statement in the sequence executes.


Note: In Python, indentation is important. If you see that the boolean expression ends with a colon, you know that the next statement will be intended.

Let’s take another very simple example to understand the working of Python if statement.

if(True): # Here, we have used a boolean value True to check whether the condition is true or not.
    print("Code to be executed") # It will print statement. 

if(False): 
    print("Code not to be executed") # It will not print statement.

In the preceding example, the test condition is true. Therefore, the interpreter executes the intended statement and print the message “Code to be executed”. After the execution of intended statement, the interpreter executes the next if statement in the sequence. Since the condition is false, the intended statement will not execute by interpreter and skipped.

Some Valid if statements in Python

x = 1
if x > 0:
    print(x, " is a positive number")

x = 10
if(x): # same as: if(x != 0)
    print(x, " is a nonzero number");

x, y = 10, 10
if(x == y):
    print("x and y are equal number")

x, y = 5, 10
if x < y:
    print("x is less than y")

x = True
if(x): # Here, we have used a boolean value to check whether the condition is true or not.
    print("You are eligible to cast vote")

Example Program based on If Statement


Let’s take some example programs based on the if statement in Python.

Example 1:

Let’s write a Python program to calculate the area of a circle if the radius is greater than 0.

radius = 2.5
pi = 3.14
if radius >= 0:
    area = radius * radius * pi
    print("Area of circle: ", area)
Output:
      Area of circle:  19.625

In the preceding example, if the boolean expression or condition evaluates to true, intended statements inside the block of if statement executes.

In other words, if the value of radius is greater than or equal to 0, the Python interpreter computes the area of circle, and displays the result on the console.

Otherwise, the interpreter will skip two intended statements in the block, not execute, and continue with the rest of program.


Example 2:

Let’s write a program in Python in which we will prompt the user to enter a number and check that the number is divisible by 2 or not. If the number is divisible by 2, the program prints a message “number is divisible by 2”.

# Prompt the user to enter a number.
num = int(input("Enter a number that you want to check it is divisible by 2 or not: "))
if num % 2 == 0:
    print(num, " is divisible by 2.")
if num % 2 != 0:
    print(num, " is not divisible by 2.")
Output:
      Enter a number that you want to check it is divisible by 2 or not: 24
      24  is divisible by 2.

Example 3:

Let’s write a program in Python in which we will display a “You are eligible to cast a vote” message if the age is greater than or equal to 18. If the age is not greater than or equal to 18, we will display “You are not eligible to cast a vote!” on the console.

# Prompt the user to enter your age.
age = int(input("Enter your age to check you are eligible to cast a vote or not: "))
if age >= 18:
    print("You are eligible to cast a vote.")

if age < 18:
    print("You are not eligible to cast a vote")
Output:
      Enter your age to check you are eligible to cast a vote or not: 19
      You are eligible to cast a vote.

In the preceding example, we have entered the age 19 and is greater than 18, therefore, the interpreter prints the message “You are eligible to cast a vote”.


Example 4:

Let’s write a Python program in which we will take marks for three subjects, such as math, chemistry, and physics from the user. Then, we will calculate the percentage of three subject marks and print “Grade A” if the percentage is greater than or equal to 90. Look at a glance at the script code to understand better.

# Prompt the user to enter marks of three subjects.
phy = int(input("Enter your physics marks: "))
chem = int(input("Enter your chemistry marks: "))
maths = int(input("Enter your math marks: "))
totalMarks = phy + chem + maths

myPer = totalMarks / 3
print("Total marks obtained: ", totalMarks)
print("Your percentage: ", myPer)

if(myPer >= 90.0): # if the condition is true, then the statement will be displayed.
    print("Grade A")
if(myPer < 90.0): # if the condition is true, then the statement will be displayed.
    print("Grade B")
Output:
      Enter your physics marks: 89
      Enter your chemistry marks: 87
      Enter your math marks: 67
      Total marks obtained:  243
      Your percentage:  81.0
      Grade B

Example 5:

Let’s write a program to check even or odd.

# Read the number from the user to check even or odd.
num = int(input("Enter a number: "))
if num % 2 == 0:
    print(num, 'is an even number')
if num % 2 != 0:
    print(num, 'is a odd number')
Output:
      Enter a number: 5
      5 is a odd number

Use of Logical Operators in If Statement


We can also Python logical operators in the conditional expression if you want to check multiple conditions together. There are three types of logical operators in Python that are as follows.

  • and
  • or
  • not

Let us take some example programs based on logical operators used in the if statement.

Example 1: Use of logical AND (and) operator

x, y, z = 20, 40, 50
if((y > x) and (y < z)): # True 
     print("y is greater than x but smaller than z") 
if((x > y) and (y < z)): # False
     print("z is greater than x, y")
if(y % x == 0 and x != 0): # True
     print("y is divisible by x")
Output:
      y is greater than x but smaller than z
      y is divisible by x

In the preceding example, the first and third if statements evaluates true as both conditional expressions joined by logical and operator are true.

The second if statement evaluates false as the first conditional expression is false. In this example, if statement will produce true only if both expressions are true.

If any of the expressions is false or both expressions are false, if statement will produce false and skip the intended statement.


Example 2: Use of logical OR (or) operator

x, y, z = 2, 1, 4
if(value := x > y or y < z): 
    print(value) 
if(value := x > y or y > z):
    print(value)

if(value := x < y or y < z):
    print(value)
if(value := x < y or y > z):
    print(value)
Output:
      True
      True
      True

In the preceding example, if any of the expression is true or both expressions are true, if statement evaluates true. If both expressions are false, the if statement evaluates false and the block of statements does not execute.


Example 3: Use of logical NOT (not) operator

x, y = 2, 1
if(value := (x == 2) and not(y == 2)):
    print(value)
Output:
      True

Thus, we can combine several conditional expressions by using logical operators. The result will be a boolean type.


In this tutorial, you have learned a single selection if statement in Python with the help of various example programs. I hope that you will have understood all the basic syntax and concepts of if statement. Stay tuned with our next tutorial where you will understand if-else statement in Python with the help of syntax and examples.
Thanks for reading!!!