πŸ”½ Python If Statement β€” Making Decisions in Your Code

Introduction 🌟

The if statement is the foundation of decision-making in Python. It allows your program to execute a block of code **only when a condition is True**. This is essential for real-world logic like validation, authentication, calculations, and control flow.

Note

πŸ’‘ Conditions inside an if statement always evaluate to either True or False.

1. Basic If Statement βœ”οΈ

basic_if.py

age = 20

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

If the condition is True, Python executes the indented block.
If False, nothing happens.

2. Indentation Is Important! 🧱

Python uses indentation to define code blocks. Usually 4 spaces are used.

indentation.py

if True:
print("Wrong!")   # ❌ Error: Not properly indented

if True:
    print("Correct!")   # βœ”οΈ

Note

⚠️ Incorrect indentation will cause an error.

3. If Statement With User Input πŸ§‘β€πŸ’»

if_input.py

marks = int(input("Enter your marks: "))

if marks >= 50:
    print("Pass")

4. Using Comparison & Logical Operators in If πŸ”—

if_logic.py

age = 25

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

5. If With Strings πŸ”€

if_strings.py

language = "Python"

if language == "Python":
    print("You are learning Python!")

6. If With Membership Operators πŸ”Ž

if_membership.py

fruits = ["apple", "banana", "mango"]

if "apple" in fruits:
    print("Apple is available")

7. If With Boolean Variables βœ”οΈ

if_boolean.py

is_logged_in = True

if is_logged_in:
    print("Welcome back!")

Note

πŸ’‘ A boolean variable itself can be a condition.

8. Nested If Statements πŸͺœ

Use nested if to check multiple levels of conditions.

nested_if.py

age = 20

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

    if age >= 21:
        print("You can drink alcohol legally in some countries")

9. If Statement With Expressions 🎯

if_expression.py

x = 10

if (x * 2) > 15:
    print("Expression is True")

10. Real-World Example 🌍

real_world_example.py

username = input("Enter username: ")

if username == "admin":
    print("Access Granted")

Conclusion πŸŽ‰

>>β€œThe if statement is where your program learns to think β€” one True or False at a time.” ✨

You now understand Python’s if statement. Want the next topic? Try If-Else, Elif Ladder, Nested Conditions, or Control Flow. Just tell me! 😊