Skip to main content

Unit 3 · Decisions, Decisions · Lesson 26 of 57

If You Say So

If you say so

Now that Python can ask questions, let's make it do something with the answer.

password = input("Password: ")

if password == "amer123":
    print("Really, Amer?")

print("Done!")

Read it like English: if the password is amer123, print Really, Amer?.

Here's how it works:

  1. Python asks the question after if.
  2. If the answer is True, it runs the indented lines underneath.
  3. If the answer is False, it skips them completely.
  4. Either way, it carries on with whatever comes after (Done! always prints).

The colon and the indent

Look familiar? It's the same shape as a function:

def add(number1, number2):
    return number1 + number2
  • The line ends with a :, which tells Python "the stuff that belongs to me starts on the next line."
  • Everything that belongs to it is indented (pushed in with spaces, usually 4). That's how Python knows where the if ends.

Indentation isn't just for looks in Python. It's how Python knows what belongs to what, so it matters a LOT.

Here's that code with the indent missing. Run it and see what Python thinks.

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.

IndentationError

IndentationError: expected an indented block after 'if' statement on line 3

Python saw the : and expected the next line to be pushed in. When it wasn't, Python had no idea what was supposed to happen if the password matched, so it refused to run anything.

Press Tab in the editor to indent a line. To un-indent, press Shift + Tab.

Karl's secret club has a bouncer. (It's a Python program. Budget cuts.)

  1. Ask for a name with input().
  2. If the name is Alex, print Nope. You deleted the website.
  3. After that (no matter who it is), print Next!

If Alex shows up, it should print both lines. Anyone else just gets Next!

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.