π½ 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! π