MWZ

MINDWAREZONE

If Statements in python

Decision-making is a fundamental part of programming. In Python, the if statement allows a program to make decisions and execute specific code blocks based on conditions. Whether you're checking a user's age, validating input, or controlling program flow, if statements are essential.

What is an if Statement?

An if statement evaluates a condition. If the condition is True, the code inside the if block executes. If the condition is False, Python skips that block.

Syntax

if condition:
   # code to execute
            

Key Points About if Statements

  • Used for decision-making in programs.
  • Executes code only when a condition is True.
  • Conditions return either True or False.
  • Indentation is mandatory in Python.
  • Can be combined with else and elif for multiple conditions.
  • Supports comparison operators such as:== (equal to)!= (not equal to)> (greater than)< (less than)>= (greater than or equal to)<= (less than or equal to)

Example 1: Checking Age Eligibility

age = 20 
if age >= 18: 
   print("You are eligible to vote.")
            

Output

You are eligible to vote.
            

Explanation

The condition age >= 18 is True, so the message is displayed.

Example 2: Checking a Number

number = 5 
if number > 0: 
    print("The number is positive.")
            

Output

The number is positive.
            

Explanation

Since 5 is greater than 0, the condition evaluates to True.

Multiple Statements in If Block

You can have multiple statements inside an if block. All statements must be indented at the same level.

Example

age = 20
if age >= 18:
  print("You are an adult")
  print("You can vote")
  print("You have full legal rights")
            

Common Mistakes to Avoid

  • Forgetting the colon (:) after the condition.
  • Incorrect indentation.
  • Using = instead of == for comparisons.
  • Writing conditions that always evaluate to True or False unintentionally.