Unit 3 · Decisions, Decisions · Lesson 28 of 57
Elif-ing Around
More than two choices
Sometimes there are more than two roads. That's what elif is for (short for else if).
First, a quick new tool. len() is a function that teleports back how long something is:
print(len("amer123"))
7
Now let's rate a password by how long it is:
password = input("Password: ")
if len(password) >= 12:
print("Strong")
elif len(password) >= 8:
print("Okay")
else:
print("Weak")
Python checks each question from top to bottom, and runs the first one that's True. Then it skips the rest, even if they'd be True too.
ifalways comes first- you can have as many
elifs as you want elseis optional, and always comes last
Order matters
Here's the same code, with the questions swapped. Before you run it, think about what a 20 letter password should get.
Run it and type in correcthorsebatterystaple (that's 25 letters).
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.
Question
Answer it in the lesson and it is checked as soon as you send it. Create a free account to do this part.
Rishabh wants a program that turns his test score into a letter grade.
- Ask for a score with
input()and turn it into a number. - Print the grade:
- 90 or more:
A - 80 or more:
B - 70 or more:
C - anything lower:
Nope
- 90 or more:
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.