< Prev  |  Home  |  Next >

Python ‘if’ Statement

Boolean (True or False) values are useful, because sometimes we only want to do something in our program if something else is True (or False). Like in our earlier ‘Hello’ program, we might want to print a welcome message if the user’s name is, say, George, but not print anything if another name is entered.

This is a flowchart showing how I want the program to work:

Flowchart for the greeting program

We have a new diamond symbol in this flowchart, which represents a decision. Depending on the answer to the question in the diamond box, our program will do one of two things.

Here’s the python version of this design:

Notice that we have a colon (:) at the end of the ‘if’ line, and that the print statement is indented. You can indent by pressing tab, or pressing space a few times. In this program, anything that’s indented will only happen if the name is ‘George’.

I’ll prove it. Add a line to the end of the program and you’ll see that because it isn’t indented, it isn’t part of the ‘if’ statement and it’ll always print:

We should probably test the program, to make sure it does what it’s supposed to do. Let’s create a test plan to find out. It’s not as boring as it sounds. Oh wait, it is:

Data Expected Actual
name == "Anna" No output No output
name == "George" Hello George! Hello George!

Notice how we compare what we want to happen with what actually happens. And here’s our evidence:

What is your name? Anna

What is your name? George
Hello George!


Create a short quiz. Ask the user a question, and say “Well Done :)” if they get it right. You can ask them any question you like. Yep, even a silly one. What do I care, I’m not your mother.

You should include:

  • A flowchart design;
  • The Python code;
  • The test plan;
  • Print screen evidence that your program does as it should.

Use the example above to help you. This will be the format of all challenges from now on.

< Prev  |  Home  |  Next >