Challenge 1-6: Logic with If Statements

Challenge 1-6: Logic with If Statements

Making Decisions

Ok, here's a small word with an important meaning.

When we talk about logic, we’re talking about making decisions about what to do next in our code.

One of the ways we do that is with if statements.

Here's what some everyday decisions might look like:

"If the alarm rings, get out of bed."
"
If the dog is hungry, give it some food."

Here's an example of what that might look like in Python code - if a condition is met, perform an action:


>>> myname = "Alfred"

>>> if myname == "Alfred":

... print("Hi Alfred!")

...

Hi Alfred!


Let's break this down:

First we created a variable called myname and gave it the value "Alfred".

Then we told Python to do something if the value of that variable was equal to "Alfred".

Well, of course, the value of myname is "Alfred", so Python did that something we asked it to - it printed out the words "Hi Alfred!".

That's how you construct a simple if statement.

There's something else important to notice here.

Until now, we've only entered one line of code at a time in our Python interpreter.

But these two lines need to be able to work together:


>>> if myname == "Alfred":

... print("Hi Alfred!")


We've done two new things here:

  • we ended the first line with a ':' (or a colon)

  • then we indented the second line four spaces

Ending the first line with a colon lets Python know that there is more code to follow. Indenting the second line tells Python that it should only perform this print command if the condition on the first line is True.

Just to be safe, always indent 4 spaces (use the space bar, NOT the tab key!). If you're using the Python Idle, Idle should automatically indent for you. But if you're using the Python Shell to type this code, as in the previous challenges, you will have to type the indent yourself.

The Python Shell will also automatically put those three full stops in front of the code after you type a colon, to remind you that you are still writing an if statement. You shouldn't add these when you're writing your own code, though!

We'll see some more detailed examples later on that should make all this easier to understand. For now, just pay close attention and make sure that the code examples you type match the ones on these pages.