Python If Statement

An if statement is used to execute a block of code only if a specified condition is true. Syntax Simple If Statement Example: Output: How It Works The condition is evaluated first. Example: Output: Using Comparison Operators Comparison operators are commonly used with if statements. Operator Description == Equal to != Not equal to > […]

2 mins read Lesson 16 of 43 37% through track

An if statement is used to execute a block of code only if a specified condition is true.

Syntax

if condition:
    # code to execute

Simple If Statement

Example:

age = 18

if age >= 18:
    print("You are an adult")

Output:

You are an adult

How It Works

The condition is evaluated first.

  • If the condition is True, the code block runs.
  • If the condition is False, the code block is skipped.

Example:

x = 10

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

Output:

x is greater than 5

Using Comparison Operators

Comparison operators are commonly used with if statements.

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

Example:

number = 20

if number == 20:
    print("Number is 20")

Output:

Number is 20

Using Variables

Example:

name = "John"

if name == "John":
    print("Welcome John")

Output:

Welcome John

Multiple Statements

You can execute multiple statements inside an if block.

Example:

age = 25

if age >= 18:
    print("You are an adult")
    print("You can vote")

Output:

You are an adult
You can vote

Using Logical Operators

Example:

age = 25

if age >= 18 and age <= 60:
    print("Eligible")

Output:

Eligible

Nested If Statement

You can place one if statement inside another.

Example:

age = 25

if age >= 18:
    if age >= 21:
        print("Access Granted")

Output:

Access Granted

If with Boolean Values

Example:

is_logged_in = True

if is_logged_in:
    print("Welcome")

Output:

Welcome

Short Hand If

If you have only one statement to execute, you can write it on one line.

Example:

age = 18

if age >= 18: print("Adult")

Output:

Adult

Practical Example

Check if a number is positive.

Example:

number = 10

if number > 0:
    print("Positive Number")

Output:

Positive Number

Common Mistake

Missing indentation:

age = 18

if age >= 18:
print("Adult")

Output:

IndentationError: expected an indented block

Correct:

age = 18

if age >= 18:
    print("Adult")

Summary

  • The if statement executes code when a condition is True.
  • Conditions are evaluated using comparison operators.
  • Indentation is required inside if blocks.
  • Multiple statements can be placed inside an if block.
  • Logical operators such as and, or, and not can be used.
  • if statements can be nested inside other if statements.