🧠 Part 7 – Mastering Conditions in Python: If, Else, Elif and a Bit of Magic

Por Andre M.K.

Now it’s time to let logic do the heavy lifting. Think about those “if it rains, I’ll take an umbrella” situations. Well, Python faces decisions too — and we guide it using conditionals.

🔑 Today’s keywords: if, else, elif

These little words help Python choose its path, depending on what’s going on.


💡 How do they work?

Imagine a smart gate. It opens if you have the key. If you don’t, it won’t budge. In code, it’s this simple:

key = True

if key:
    print("Gate is open!")
else:
    print("No key, no entry.")

Pretty clear, right? But let’s spice it up a bit.


🔄 What if there are more than two choices?

That’s where elif (short for else if) jumps in. It’s like saying, “if not this, maybe that”:

grade = 8

if grade >= 9:
    print("Excellent!")
elif grade >= 7:
    print("Very good!")
elif grade >= 5:
    print("Average.")
else:
    print("Needs improvement...")

🔁 Python checks each condition from top to bottom. The first one that’s true wins — and it skips the rest.


⚠️ Watch your indentation!

Python is picky about spacing. If you don’t align the blocks properly, it’ll throw a fit (aka an error):

age = 18

if age >= 18:
    print("You can vote!")
    print("And drive too!")

🧠 Pro tip: use 4 spaces per block or set your editor to do it automatically.


🛠️ Mini Challenge

Try to create a program that checks if someone can apply for a driver’s license:

age = int(input("How old are you? "))

# Now add conditions:
# - If 18 or older: "You can apply for a license!"
# - If under 18: "You need to wait a bit."

🔍 Learn more:


If you liked it, share with someone learning Python from scratch. 🚀

(Visited 6 times, 1 visits today)