Forum

Learn Python Basics…
 
Notifications
Clear all

Learn Python Basics If-Then Statements

1 Posts
1 Users
0 Reactions
12 Views
 josh
(@josh)
Member Admin
Joined: 2 months ago
Posts: 510
Topic starter  

Absolutely! Python’s if statements are the foundation of decision-making in your code—they let your program choose what to do based on conditions. 🧠✨


🧩 Basic Structure

if condition:
    # code to run if condition is True
  • The condition is a logical expression (like x > 5)
  • If it’s True, Python runs the indented code block
  • If it’s False, Python skips it

🔄 Adding else and elif

if condition1:
    # runs if condition1 is True
elif condition2:
    # runs if condition1 is False and condition2 is True
else:
    # runs if none of the above conditions are True

This lets you handle multiple possibilities.


🧪 Example

age = 20

if age < 18:
    print("You're a minor.")
elif age < 65:
    print("You're an adult.")
else:
    print("You're a senior.")

Output:

You're an adult.

⚠️ Indentation Matters

Python uses indentation (usually 4 spaces) to define blocks of code. If you forget to indent, Python will throw an error.


🧠 Bonus: One-Line if Statement

print("Yes") if x > 5 else print("No")

This is called a ternary expression—handy for quick decisions.


 


   
Quote
Share: