Skip to content

The if Statement in Python: A Comprehensive Guide

Updated: at 04:56 AM

The if statement is one of the most fundamental and important concepts in programming languages like Python. It allows you to test a condition and execute different code blocks based on whether the condition is true or false. Mastering if statements is essential for writing clean, organized and efficient Python code.

In this comprehensive guide, we will cover everything you need to know about using if, elif, and else statements in Python.

Table of Contents

Open Table of Contents

Introduction to If Statements

An if statement is a conditional statement that runs a block of code if its condition evaluates to True, and optionally another block of code if the condition is False.

The basic syntax of an if statement in Python is:

if condition:
    # execute this code block if condition is True

Here, condition can be any expression that evaluates to either True or False. This includes comparisons, Boolean variables, and calls to functions that return Booleans.

For example:

x = 10
if x > 5:
    print("x is greater than 5")

This will check if x is greater than 5. Since x is 10, the condition x > 5 evaluates to True, so the print statement will execute and “x is greater than 5” will be printed.

The code block indented under the if statement is called the body of the if statement. This code will only run if the condition is True. No indentation means the code is not part of the body.

If-Else Statements

Often, we want to execute one block of code if a condition is True and another block if the condition is False. This can be done using an if-else statement.

The syntax is:

if condition:
    # code to execute if condition is True
else:
    # code to execute if condition is False

For example:

age = 15
if age >= 18:
    print("You are eligible to vote")
else:
    print("You are not eligible to vote")

Here, we check if age is greater than or equal to 18. If so, we print that the person is eligible to vote. Otherwise, we print that they are not eligible.

The else clause provides an alternative block of code that executes only when the if condition is False. At most one of the two code blocks will run.

Elif Statements

In some cases, we may want to check multiple conditions and execute different code for each one. This can be done by chaining if, elif and else statements.

The syntax is:

if condition1:
    # code block 1
elif condition2:
    # code block 2
elif condition3:
    # code block 3
else:
    # default code block

This allows you to test multiple conditions and execute different code for each one. For example:

grade = 85

if grade >= 90:
    print("A")
elif grade >= 80:
    print("B")
elif grade >= 70:
    print("C")
elif grade >= 60:
    print("D")
else:
    print("F")

Here we check the grade and print the letter grade corresponding to different grade ranges. The first condition that is True will have its code block executed and the rest will be skipped.

Using elif and else together is an efficient way to check multiple conditions instead of nesting multiple if statements.

Indentation

In Python, indentation is very important. The body of the if statement must be indented after the if line. Same for elif and else.

For example:

x = 10

if x > 5:
print("Greater than 5") # Indentation error, this will raise an exception

This will cause an IndentationError because the print statement is not indented after the if.

Proper indentation would be:

x = 10

if x > 5:
    print("Greater than 5") # Properly indented under if block

In general, indent using 4 spaces for each level. Maintaining proper indentation helps make code readable.

Code Blocks

The indented code under if, elif and else are called code blocks. In Python, code blocks are defined by indentation rather than braces {} like other languages.

A code block may contain any number and type of statements, including other if statements for nested conditionals. For example:

x = 15
if x > 10:
    print("Above 10")
    if x > 20:
       print("and also above 20!")
    else:
       print("but not above 20")

Here we have a nested if statement inside the outer if block that only runs when x > 10. Code blocks allow you to construct complex conditional logic in your programs.

Boolean Expressions

The condition in an if statement must evaluate to a Boolean value - either True or False. These values are obtained by using comparison, identity, membership operators or Boolean expressions.

Some examples of comparison operators:

x == y # True if x equals y
x != y # True if x is not equal to y
x > y  # True if x is greater than y
x < y  # True if x is less than y

Some examples of Boolean expressions:

x > 0 and x < 10  # True if x is between 0 and 10
x == 5 or x == 10 # True if x is 5 or 10
not x >= 0        # True if x is negative

You can build complex Boolean logic by combining comparison operators with and, or and not.

Here are some examples of if statements using different Boolean expressions:

num = 10

if num > 5:
   print("Num is greater than 5")

if num % 2 == 0:
   print("Num is even")

if num >= 0 and num <= 100:
   print("Num is between 0 and 100")

The condition can also call functions like isinstance() or isnumeric() that return Boolean values:

inp = "15"

if inp.isnumeric():
   print("Input is a number")

This allows for powerful conditional testing in your code.

Single Statement Blocks

For very simple code blocks containing just a single statement, we can put it on the same line as the if, elif or else keyword without indentation:

if x > 0: print("Positive")

However, it is recommended to still use proper indentation for clarity, even if it is just one line:

if x > 0:
    print("Positive")

Single statement blocks without indentation should only be used for very short and simple conditional checks.

If Statement Without Else Block

An else block is optional. You can just use an if statement alone when you only want to execute code if a condition is true, but don’t need to do anything specific otherwise.

For example:

num = 15

if num > 10:
    print("Num greater than 10")

print("Program continues...")

Here we just want to print a message if num > 10 without an else block. The rest of the code continues normally.

nested if Statements

You can have if statements inside if statements, known as nested conditionals. Each inner if statement is checked only if the outer if statement passes.

This allows you to test for multiple conditions in succession:

x = 15

if x > 10:
   print("x is greater than 10")

   if x > 20:
      print("x is also greater than 20")

   else:
      print("but x is not greater than 20")

The inner if only runs if x > 10. And the inner else only runs if x > 10 but x <= 20.

Nested if statements are indented further to the right to represent that hierarchy visually. You can nest conditionals multiple levels deep, but too many levels can make code difficult to read.

Using If Statements With Lists and Dictionaries

if statements can also test conditions on list or dictionary elements.

For example:

names = ["John", "Mary", "Bob"]

if "Mary" in names:
   print("Mary is present")

This checks if "Mary" exists in the names list using in.

We can also check dictionary keys:

person = {
  "name": "John",
  "age": 20
}

if "name" in person:
   print(person["name"])

This will print John since "name" key exists.

Some other useful checks on lists/dictionaries:

if len(names) > 2:
   print("There are more than 2 names")

if "age" not in person:
   print("Age key does not exist")

So if statements give you flexibility to test many different conditions.

Using If Statements with User Input

If statements are often used to validate user input or implement conditional behavior based on input.

For example:

num = input("Enter a number: ")

if num.isnumeric():
   num = int(num)

   if num > 0:
      print("You entered a positive number")

   else:
      print("You did not enter a positive number")

else:
   print("You did not enter a valid number")

This:

  1. Takes numeric input using input()
  2. Checks if it is actually numeric using isnumeric()
  3. Converts it to an integer if yes
  4. Then checks if positive
  5. Prints appropriate messages based on input

Proper input validation and conditional testing prevents bugs and crashes.

Common Mistakes

Some common mistakes when using if statements in Python:

Pay close attention to these issues to avoid logical errors in your conditional statements.

Conclusion

The if statement is used to control the flow of program execution based on certain conditions. Mastering if, elif and else along with Boolean logic provides the ability to implement complex decision making in Python code.

Key points to remember:

Whether you are a beginner or expert Python programmer, understanding if statements will enable you to write smarter code that can make decisions and adapt to different situations.