Unit 3 · Decisions, Decisions · Lesson 27 of 57
If all else fails!
Or else!
if handles what happens when the answer is True. But what about when it's False?
That's what else is for:
age = int(input("How old are you? "))
if age >= 21:
print("Welcome to Club CyberAcad!")
else:
print("Come back in a few years!")
Python takes exactly one of the two paths. Never both, never neither.
Think of it like a fork in the road. The question decides which way you go.
elsedoesn't get a question. It's just "everything else."- It still gets a
:and its own indented lines. - It has to come right after an
if. Anelseon its own doesn't make sense (else... what?).
Let's make a (very) basic login.
- Ask for a password with
input(). - If it's
pyth0n-r0cks, printAccess granted - Otherwise, print
Access denied
Python exercise
Write the program in an editor next to the lesson, run it, and have it checked automatically. Create a free account to do this part.
Do this lesson for real
With a free account you get the terminals, challenges and checks that go with the lessons in Intro to Python, and your progress is saved as you go. CyberAcad is a 501(c)(3) nonprofit, so there is nothing to pay.