🔀 If-Else

4th Grade 💻 Coding

If/else is a structure in programming that checks a condition: if it’s true, the program runs the “if” part, and if not, it runs the “else” part.

Free · US Letter · no sign-up
Google Classroom Save to Pinterest Email me

In Python you write the condition after if and end the line with a colon, then indent the instructions underneath with spaces. On one line you could write, for example, if age >= 12: print("Come on in"). Then comes else with a colon, followed by the instructions for when the condition isn’t true.

When there are more than two choices, you use elif (short for “else if”). The computer checks the conditions in order and runs only the first one that’s true — so the order matters, for example going from the highest grade to the lowest. Scratch has an “if … then … else …” block with two “mouths.”

For example

  • Grades: if 90 or higher — “Excellent”; else if 70 or higher — “Good”; else — “Let’s review the material.”
  • Logging in to a website: if the password is correct, you get in; else, you see “Try again.”

📌 Remember: if = if. else = otherwise. elif = otherwise, if.

Quick quiz

  1. When does the else part run?

  2. What is elif used for?

  3. How many parts run in an if/elif/else chain?

🔎 Ask Thinkapedia another question