• Ctrl+C+Python
  • Posts
  • 🐍 Python Basics: Mastering if, elif, and else Statements

🐍 Python Basics: Mastering if, elif, and else Statements

Conditional statements are one of the core building blocks of programming. In Python, we use if, elif, and else statements to execute code only when certain conditions are met. In this post, you'll learn how these statements work and how to use them effectively!

Take your learning to the next level with quick, aesthetic coding tutorials on my YouTube channel! πŸš€βœ¨

πŸŽ₯ Watch now: @CtrlCPython

Subscribe for bite-sized Python lessons with lofi vibes & clean code. β˜•πŸŽΆ 

1. The if Statement

The if statement allows you to run a block of code only if a condition is true.

Output:

You are an adult!
  • The condition age >= 18) is evaluated.

  • If it’s True, the indented block runs.

  • If it’s False, Python skips the block.

2. The else Statement

The else statement runs when the if condition is false.

Output:

You are a minor.

Think of else as a fallbackβ€”it runs when no if conditions are met.

3. The elif Statement

Sometimes, you need multiple conditions. That’s where elif (short for β€œelse if”) comes in!

Output:

You are a teenager.

Python checks conditions in order:

  1. If age >= 18 β†’ False, move to elif.

  2. If age >= 13 β†’ True, run the block.

  3. If none are True, the else block runs.

4. Using Multiple elif Statements

You can have multiple elif statements for complex conditions:

Output:

Grade: B

Python stops checking once it finds a True conditionβ€”even if later conditions would also be true.

5. Using Logical Operators (and, or, not)

You can combine conditions using logical operators:

Output:

The weather is nice!

More examples:

  • and β†’ Both conditions must be True

  • or β†’ At least one condition must be True

  • not β†’ Reverses a condition

Output:

Please log in!

6. Best Practices for if Statements

βœ… Keep conditions simple β†’ Avoid overly complex logic inside if.

βœ… Use elif instead of multiple if statements β†’ This makes the code efficient.

βœ… Use indentation properly β†’ Python relies on indentation to define blocks.

Bad Example:

Better Example:

πŸ† Conclusion

if, elif, and else statements control the flow of your program by making decisions based on conditions. Mastering these statements is key to writing dynamic Python programs!

What Python basics do you want to learn next? Let me know in the comments! πŸš€πŸ 

Happy coding! πŸš€πŸ

Digital Shade

Want more Python tips and tricks?

πŸ”” Join my Beehiiv newsletter for exclusive cheat sheets, Python hacks, and expert tutorials!

Reply

or to participate.