Python if Statement

3 min read ·

The if statement is a decision-making statement. It allows Python to execute code only when a condition is True.
In simple words:
If condition is true → code runs If condition is false → code is skipped

Basic Syntax of if

  • if keyword starts the condition
  • Condition must return True or False
  • Colon : is mandatory
  • Indentation defines the block
Note

The code inside if must be indented, otherwise Python will throw an error.


First Example – Simple if Statement

  • Condition: age >= 18
  • If condition is True, print statement executes
  • If condition is False, nothing happens

if Statement with Boolean Condition

  • No comparison needed
  • Python directly checks the boolean value

if Statement with Comparison Operators

Common Comparison Operators

OperatorMeaning
==Equal to
!=Not equal to
>Greater than
<Less than
>=Greater than or equal
<=Less than or equal

Example


if Statement with Strings

Caution

String comparison is case-sensitive. "Python" and "python" are not the same.


Multiple Conditions using Logical Operators

and Operator

Both conditions must be True.

or Operator

At least one condition must be True.

not Operator


Nested if Statement

An if inside another if.
  • Outer if checks positivity
  • Inner if checks even number
Pro Tip

Avoid deep nesting. It makes code hard to read.


if Statement with User Input

  • input() returns string
  • int() converts it into integer

if Statement with Mathematical Logic


Common Mistakes in if Statement

Missing Colon ❌

Wrong Indentation ❌

Stop

Python will throw SyntaxError or IndentationError in these cases.


Real World Example

Real World Scenario

ATM Machine Condition If balance is sufficient → allow withdrawal


Exercise

Practice Task
  1. Take a number and check if it is greater than 100
  2. Check if a number is even
  3. Create a login check using a boolean variable
  4. Try nesting one if inside another