← All lessons

if: when the condition is true

Sign in · Sign up

Lesson 2.2

if means "if". The code inside runs only when the condition is true:

weather = "rain"

if weather == "rain":
    print("I'll take an umbrella")

Three rules for writing it:

  • after the condition comes a colon :;
  • the body of if is indented (4 spaces);
  • in the condition use == (comparison), not = (assignment).

If the condition is false, Python simply skips that code and moves on.

The example above is not your task: your task has a different word and a different message.

Check a password: if it equals "python", print Access granted. If the password is different — print nothing, because the body of if is simply skipped.

Start from a clean file: there is no starter code. The password is not set in your code but in the check: it runs the program with different values of password, so do not write the line password = ....

Hint

Remember the three rules for writing if:

  • a colon after the condition;
  • the body on the next line, indented 4 spaces;
  • a comparison == in the condition, not a single =.

The body needs one print with the text Access granted — exactly as in the task.