Python Conditional Statements Explained for Beginners (if, else, elif)

Python Conditional Statements Explained for Beginners (if, else, elif)

Python Conditional Statements Explained for Beginners (if, else, elif)

Introduction

In the previous post, we learned about Python operators. Now it’s time make programs think and take decisions using conditional statements.

Conditional statements help Python make decisions based on conditions.

---

What is a Conditional Statement?

A conditional statement allows a program to execute different code blocks based on a condition.

If a condition is True → one block runs If the condition is False → another block runs
---

1️⃣ if Statement

The if statement runs code only when the condition is True.

age = 18

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

2️⃣ if – else Statement

The else block runs when the if condition is False.

age = 16

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

3️⃣ if – elif – else Statement

The elif statement is used to check multiple conditions.

marks = 75

if marks >= 90:
    print("Grade A")
elif marks >= 75:
    print("Grade B")
elif marks >= 50:
    print("Grade C")
else:
    print("Fail")
---

Indentation in Python

Python uses indentation (spaces) instead of curly brackets.

Indentation is mandatory in Python. Wrong indentation will cause an error.
---

Comparison Operators

Conditional statements use comparison operators:

  • == equal to
  • != not equal to
  • > greater than
  • < less than
  • >= greater than or equal to
  • <= less than or equal to
---

Logical Operators

Logical operators are used to combine conditions.

age = 20
has_id = True

if age >= 18 and has_id:
    print("Entry allowed")
else:
    print("Entry denied")
---

Simple Real-Life Example

Let’s write a program that checks whether a number is positive, negative, or zero.

num = int(input("Enter a number: "))

if num > 0:
    print("Positive number")
elif num < 0:
    print("Negative number")
else:
    print("Zero")
---

Common Beginner Mistakes

  • Missing colon :
  • Wrong indentation
  • Using = instead of ==
Always use == for comparison and = for assignment.
---

What You Learned in This Post

  • if, else, and elif statements
  • Comparison and logical operators
  • Decision making in Python
---

What’s Next?

Now that you understand conditions, it’s time to learn loops.

Next Post: Python Loops Explained (for loop, while loop)

---

👋 About the Author

Ayush Gupta
MSc AI/ML Student | Machine Learning & Python Enthusiast

📧 Email: aygupta9898@gmail.com

Comments

Popular posts from this blog

What is Programming? Simple Explanation for Beginners

What is Python? Why Learn Python for Beginners

How to Install Python on Windows and Mac (Step-by-Step Guide)