Introduction

The If statement is a fundamental concept in Python and plays a crucial role in controlling the flow of your program. If statements allow you to execute a specific block of code only when a certain condition is met. This makes your code more powerful, flexible, and accurate, as you can program it to respond to user input or specific situations in a dynamic and efficient way. In this tutorial, we will go over the basics of If statements in Python, including syntax, logic, and practical examples. So, let's get started!

Table of Contents :

  • The simple Python if statement
  • Control flow for if statement

The simple Python if statement

  • if statement is used when we want a to execute a code block only when a certain logical condition is True.
  • The syntax of the if statement in Python is :

if Logical_Condition:
   inner-code-block

outer-code-block

  • The colon (:) after the condition is very important as it marks the beginning of the if-code-block.
  • The indentation of the if code block is also very important in Python as python uses indentation to mark code blocks.
  • The indentation tells the python interpreter how many statements are within the if code block.

Control flow for if statement :

  • The Logical condition of the if statement is evaluated.
  • If the logical condition is True the statements in the inner-code-block are executed.
  • If the logical condition is False the statements in the inner-code-block are ignored.
  • The control flow then comes to the outer-code-block and its statements are executed.
  • No matter the condition of the if statement is True or False - the statements in the outer-code-block are always executed.
  • Code Sample : When the logical condition of if statement evaluates to True.

x = 10
if x > 5:
	print("I am the inner code block")
	print("Logical condition is True")
	print()

print("I am the outer code block.")

# Output
# I am the inner code block
# Logical condition is True

# I am the outer code block.


  • Code Sample : When the logical condition of if statement evaluates to False.

x = 2
if x > 5:
	print("I am the inner code block")
	print("Logical condition is True")
	print()

print("I am the outer code block.")

# Output
# I am the outer code block.


Prev. Tutorial : Conditional statements

Next Tutorial : If..else Statement