Python if else statements – Driving Lesson #4

  • Pre-driving checks

If you are here you should be able use an editor to write Python code to control  your Pi-Car and understand what we mean when we talk about constants, variables and print statements. If not by all means have a go at this lesson but if you get stuck try Driving Lesson#1Driving Lesson#2 or Driving Lesson#3.

  • What’s in this driving lesson?

In this lesson we will be introducing logic – rather than the Raspberry Pi just carrying out each instruction in the program one after another as it has done so far, we can make it a bit cleverer.  We do this by adding logical instructions to the program that tell the Raspberry Pi to only do certain things based on what is happening at a certain time.

To do this we will introduce the concept of an if instruction and the else instruction.

This is where you may start to see how powerful programming can be. If you get to the end and still don’t really see why it is important, again don’t worry, just trust us that they are important! As you do more you will begin to see the power these instructions will give you to do increasingly complicated things.

  • A little theory

Unless you already know what an if instruction is you probably do need to read the theory section this time – but I am sure this won’t stop you jumping down to the driving part! As always if you get stuck come back and have a read when you do, or just to refresh your mind, it may take a while to get these concepts.

if instructions (also known as ‘if statements’)

In the real world we have to make all sorts of decisions every day. Which decision we make depends on certain factors. For example a decision that (some) people have to make is –

‘Should I buy a Ferrari or a Mercedes today?’

There are probably loads of things they have to consider when making this decision but let’s just imagine it depends on whether they have enough money:

‘If I have enough money then buy a Ferrari, if I don’t then buy a Mercedes’

This is of course a much simplified version of how we may make a decision but demonstrates us (as humans) performing logical steps to make decisions and instruct ourselves to do certain things.

It follows that to make our program more intelligent we need give it the ability to make logical decisions – we don’t just want the Raspberry Pi to carry out all the instructions one after another but rather make decisions as to which instructions to perform.

As we have learnt, a program is a set of instructions that we have written down in advance. Therefore all of the decisions that we want the Raspberry Pi to make, and what happens on the outcome of each one, has to be written into the program.

To make one of these decisions in a program we make use of the ‘if’ instruction, more commonly know as the ‘if’ statement. There are certain rules around how we write this into  a Python program and we’ll now look at this based on the program we have been creating.

  • Lets get driving…

At the end of the last driving lesson we finished with the following code.

If you don’t know how to get the code onto your Raspberry Pi, you can either copy it typing it into your text file. Or you can copy it in – instructions here.

import time, RPi.GPIO as GPIO

ON = 1
OFF = 0
FORWARDS=12
BACKWARDS=11
LEFT=13
RIGHT=15
PETROL_USED_PER_MOVE=20

#variables
petrolLeft=100
driversName="Michael"

GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(FORWARDS,GPIO.OUT)
GPIO.setup(BACKWARDS,GPIO.OUT)
GPIO.setup(LEFT,GPIO.OUT)
GPIO.setup(RIGHT,GPIO.OUT)

#Move car forwards
GPIO.output(FORWARDS,ON) #turn pin on
print ("Moving forwards after turning on forwards GPIO pin no = ", FORWARDS," Petrol Left = ",petrolLeft)
time.sleep(3)
GPIO.output(FORWARDS,OFF) #turn pin off
#make petrolLeft it's own current value less a fixed amount
petrolLeft = petrolLeft - PETROL_USED_PER_MOVE
print ("Current driver is ",driversName)

#Move car backwards
GPIO.output(BACKWARDS,ON)
print ("Moving backwards after turning on backwards GPIO pin no = ",BACKWARDS," Petrol Left = ",petrolLeft)
time.sleep(3)
GPIO.output(BACKWARDS,OFF)
petrolLeft = petrolLeft - PETROL_USED_PER_MOVE
print ("Current driver is ",driversName)

#Change the driver
driversName = "Minnie"
print ("New driver is ",driversName)

#Move the car left - remember we have to move forwards as well
GPIO.output(LEFT,ON)
GPIO.output(FORWARDS,ON)
print ("Moving left after turning on left GPIO pin no = ",LEFT," Petrol Left = ",petrolLeft)
time.sleep(3)
GPIO.output(LEFT,OFF)
GPIO.output(FORWARDS,OFF)
petrolLeft = petrolLeft - PETROL_USED_PER_MOVE
print ("Current driver is ",driversName)

#Move the car right - rememeber we have to move forwards as well
GPIO.output(RIGHT,ON)
GPIO.output(FORWARDS,ON)
print ("Moving right after turning on right GPIO pin no = ",RIGHT," Petrol Left = ",petrolLeft)
time.sleep(3)
GPIO.output(RIGHT,OFF)
GPIO.output(FORWARDS,OFF)
petrolLeft = petrolLeft - PETROL_USED_PER_MOVE
print ("Current driver is ",driversName)

print("Finished moving, petrol left = ", petrolLeft)
#remember to cleanup the GPIO pins
GPIO.cleanup()

Limitations of the current program 

Change the petrolLeft variable at the top of the file to be 50 instead of 100:

petrolLeft=50

Run the program and look at the print statements. It shows that the petrolLeft actually gets to a negative number but it keeps on instructing the car to keep going – not a very clever program.

Giving the program some intelligence with the if statement

To make the program better we can use an if statement to check before each time we move the Pi-Car whether there is any petrol left – if there is petrol left, move the car, if not don’t move it.

#Move car forwards if there is petrol left
if (petrolLeft > 0) :
        GPIO.output(FORWARDS,ON) #turn pin on
        print ("Moving forwards after turning on forwards GPIO pin no = ", FORWARDS," Petrol Left = ",petrolLeft)
        time.sleep(3)
        GPIO.output(FORWARDS,OFF) #turn pin off
        #make petrolLeft it's own current value less a fixed amount
        petrolLeft = petrolLeft - PETROL_USED_PER_MOVE
        print ("Current driver is ",driversName)

#Move car backwards
GPIO.output(BACKWARDS,ON)
print ("Moving backwards after turning on backwards GPIO pin no = ",BACKWARDS," Petrol Left = ",petrolLeft)
time.sleep(3)
GPIO.output(BACKWARDS,OFF)
petrolLeft = petrolLeft - PETROL_USED_PER_MOVE

You can see above we have used a symbol we have not seen before – the ‘>’ symbol. This symbol means ‘more than’.

So when the Raspberry Pi looks at the ‘if petrolLeft > 0’ instruction it will look at the current value of the variable petrolLeft and see if it is more than 0. We could have put any value where we put the 0 but we currently just want to check if it is more than 0.

You will see that after the ‘if petrolLeft > 0’ we also put a ‘:’ symbol. This tells the Raspberry Pi that if it has worked out that petrolLeft is currently more than 0 it should continue and  carry out the instructions that follow which have been indented. By indented we mean the lines that have some space to the left of them, this space is created by pressing the tab key when you write the instruction.

So in the code above if petrolLeft is currently more than 0 all of the instruction lines up until the #Move car backwards line will be completed.

Else can join an if

We may also want to do something if the Raspberry Pi has worked out that petrolLeft is 0, or less than 0. The code below shows how to do this:

#Move car forwards if there is petrol left
if (petrolLeft > 0) :
        GPIO.output(FORWARDS,ON) #turn pin on
        print ("Moving forwards after turning on forwards GPIO pin no = ", FORWARDS," Petrol Left = ",petrolLeft)
        time.sleep(3)
        GPIO.output(FORWARDS,OFF) #turn pin off
        #make petrolLeft it's own current value less a fixed amount
        petrolLeft = petrolLeft - PETROL_USED_PER_MOVE
        print ("Current driver is ",driversName)
else :
        print ("Sorry not enough petrol, petrol left=",petrolLeft)

#Move car backwards
GPIO.output(BACKWARDS,ON)
print ("Moving backwards after turning on backwards GPIO pin no = ",BACKWARDS," Petrol Left = ",petrolLeft)
time.sleep(3)
GPIO.output(BACKWARDS,OFF)
petrolLeft = petrolLeft - PETROL_USED_PER_MOVE

You can see that we used the word ‘else’ followed by a comma ‘:’ again. As with the if you need to let the Raspberry Pi know which instructions it should carry out, you do this by indenting the instructions you want it to execute.

You can only use an else after an if, you cannot use it on it’s own. Also remember that after an if or else only the instructions that are indented will be carried out. You can go ahead and put if and else statements in front of the rest of the code.

Petrol left should never be negative!

If you set the petrolLeft at the start to 30 and run the program you will notice that the petrolLeft can still get to a negative value. This is because we are currently only checking that the petrolLeft is more than 0. If it is only a little bit more then when the petrolLeft is reduced it can be reduced to less than 0.

To fix this we can check whether petrolLeft is more than the fixed amount that each movement takes:

#Move car forwards if there is petrol left
if (petrolLeft > PETROL_USED_PER_MOVE) :
        GPIO.output(FORWARDS,ON) #turn pin on
        print ("Moving forwards after turning on forwards GPIO pin no = ", FORWARDS," Petrol Left = ",petrolLeft)
        time.sleep(3)
        GPIO.output(FORWARDS,OFF) #turn pin off
        #make petrolLeft it's own current value less a fixed amount
        petrolLeft = petrolLeft - PETROL_USED_PER_MOVE
        print ("Current driver is ",driversName)
else :
        print ("Sorry not enough petrol, petrol left=",petrolLeft)

#Move car backwards
GPIO.output(BACKWARDS,ON)
print ("Moving backwards after turning on backwards GPIO pin no = ",BACKWARDS," Petrol Left = ",petrolLeft)
time.sleep(3)
GPIO.output(BACKWARDS,OFF)
petrolLeft = petrolLeft - PETROL_USED_PER_MOVE

We used the constant PETROL_USED_PER_MOVE to do this and check that petrolLeft is more than it. If you run the program again you should now see that the petrolLeft does not go beneath 0. The code should now look as follows:

import time, RPi.GPIO as GPIO

ON = 1
OFF = 0
FORWARDS=12
BACKWARDS=11
LEFT=13
RIGHT=15
PETROL_USED_PER_MOVE=20

#variables
petrolLeft=50
driversName="Michael"

GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(FORWARDS,GPIO.OUT)
GPIO.setup(BACKWARDS,GPIO.OUT)
GPIO.setup(LEFT,GPIO.OUT)
GPIO.setup(RIGHT,GPIO.OUT)

#Move car forwards if there is petrol left
if (petrolLeft > PETROL_USED_PER_MOVE) :
	GPIO.output(FORWARDS,ON) #turn pin on
	print ("Moving forwards after turning on forwards GPIO pin no = ", FORWARDS," Petrol Left = ",petrolLeft)
	time.sleep(3)
	GPIO.output(FORWARDS,OFF) #turn pin off
	#make petrolLeft it's own current value less a fixed amount
	petrolLeft = petrolLeft - PETROL_USED_PER_MOVE
	print ("Current driver is ",driversName)
else :
	print ("Sorry not enough petrol left, petrol left =",petrolLeft)

#Move car backwards if there is petrol left
if (petrolLeft > PETROL_USED_PER_MOVE):
	GPIO.output(BACKWARDS,ON)
	print ("Moving backwards after turning on backwards GPIO pin no = ",BACKWARDS," Petrol Left = ",petrolLeft)
	time.sleep(3)
	GPIO.output(BACKWARDS,OFF)
	petrolLeft = petrolLeft - PETROL_USED_PER_MOVE
	print ("Current driver is ",driversName)
else :
	print ("Sorry not enough petrol, petrol left =",petrolLeft)

#Change the driver
driversName = "Minnie"
print ("New driver is ",driversName)

#Move the car left if there is petrol left - remember we have to move forwards as well
if (petrolLeft > PETROL_USED_PER_MOVE) :
	GPIO.output(LEFT,ON)
	GPIO.output(FORWARDS,ON)
	print ("Moving left after turning on left GPIO pin no = ",LEFT," Petrol Left = ",petrolLeft)
	time.sleep(3)
	GPIO.output(LEFT,OFF)
	GPIO.output(FORWARDS,OFF)
	petrolLeft = petrolLeft - PETROL_USED_PER_MOVE
	print ("Current driver is ",driversName)
else :
	print ("Sorry not enough petrol, petrol left =", petrolLeft)

#Move the car right if there is petrol left - rememeber we have to move forwards as well
if (petrolLeft > PETROL_USED_PER_MOVE) :
	GPIO.output(RIGHT,ON)
	GPIO.output(FORWARDS,ON)
	print ("Moving right after turning on right GPIO pin no = ",RIGHT," Petrol Left = ",petrolLeft)
	time.sleep(3)
	GPIO.output(RIGHT,OFF)
	GPIO.output(FORWARDS,OFF)
	petrolLeft = petrolLeft - PETROL_USED_PER_MOVE
	print ("Current driver is ",driversName)
else :
	print ("Sorry not enough petrol, petrol left =", petrolLeft)

print("Finished moving, petrol left = ", petrolLeft)
#remember to cleanup the GPIO pins
GPIO.cleanup()

So you have now added your first bit of logic to your program which has made it more intelligent. We’ll go on to look at other bits of logic we can add in the next driving lesson, but before we do we’ll finish this lesson by looking at some of the other ways we can make decisions.

Other operators

In the code we added so far we have used the ‘>’ symbol to indicate ‘more than’ when checking if there was enough petrol left and the ‘-‘ symbol to reduce the petrol left after each time the Pi-Car moved. There are a number of other symbols like this we can use in a Python program -they are called operators. They can be used when setting variables. Some you will probably recognise already:

  • ‘+’ used for adding up e.g. petrolLeft = petrolLeft + 30
  • ‘-‘ used for subtracting e.g. petrolLeft = petrolLeft – PETROL_USED_PER_MOVE
  • ‘*’ used for multiplying e.g. timeTaken = 30 * 20
  • ‘/’ used for division e.g. movesLeft = petrolLeft / PETROL_USED_PER_MOVE

We have seen one of these already and will come on to use the remaining ones in the following lessons so don’t worry if you don’t understand how they would be used at the moment.

Other operators which you may not recognise if you have not done anything like this before are shown below. These are very useful for comparing the current value of a variable to another value like we did with the petrolLeft. They will often be used in if statements (and others that we will come onto look at).

  • ‘>’ used to check if the value on the left is ‘more than’ the value on the right e.g. if (petrolLeft > PETROL_USED_PER_MOVE)
  • ‘<‘ used to check whether the value on the left is ‘less than’ the value on the right
  • ‘>=’ used to check if the value on the left is ‘more than or equal to’ the value on the right
  • ‘<=’ used to check if the value on the left is ‘less than or equal to’ the value on the right
  • ‘==’ used when you want to check that two variables are the same
  • ‘!=’ used when you want to check that two variables are not the same. You can also use <> for this

Again we will come on to actually use these in future driving lessons so at the moment just be aware that they exist and you may be able to think of some ways you could use them in your program. There are in fact even more operators than this but for the time being these will be enough and help us make our programs much more powerful.

  • Driving Lesson review

If and else statements:

How to use:

1. Use the word ‘if’ followed by a statement you are checking.  If the thing you are checking is true then the lines after it which have been indented will be executed:

if (petrolLeft > 25) :
      print ("This will be printed if the value of petrolLeft is more than 25")

print ("This line will always be printed whether petrolLeft is more than 25 or not)

2. The thing you are checking will normally be a variable on the left compared to a value, or the value of a variable, on the right hand side.

3. You can also use the ‘else’ instruction to carry out some instructions if the thing you were checking turned out not to be true:

if (petrolLeft > 25) :
      print ("This will be printed if the value of petrolLeft is more than 25")

else :
      print ("This will only be printed out if petrolLeft is less than or equal to 25")

print ("This line will always be printed whether petrolLeft is more than 25 or not)

Why do they help?

1. Your program can now make decisions! It means that rather than just carrying out each instruction one after another, you can tell the Raspberry Pi to only do certain instructions in certain situations.

  • Gotcha’s

In any engineering things rarely work first time so don’t worry. Hopefully the list below will help. If not email us at info@pi-cars.com and leave a comment providing your code and what you tried to do, the solution will be obvious as soon as you see it!

  1. Remember after an if statement you need to have a colon and then indent the lines you want the Raspberry Pi to execute if the statement is true. You can indent by pressing the tab at the start of the line.

Next -> Driving Lesson #5 More logic – While loops and Emergency Stops

Previous -> Driving Lesson  #3 Variables and constants

 PDF Version 

PDF version of this article – Python if else statements – Driving Lesson #4 _ Pi-Cars

Advertisements

About Barnaby Kent

http://www.myactionreplay.com
This entry was posted in Uncategorized, Under the bonnet and tagged , , , , . Bookmark the permalink.

2 Responses to Python if else statements – Driving Lesson #4

  1. Pingback: Python variables and commenting – Driving Lesson #3 | Pi-Cars

  2. Pingback: Python while loops – Driving lesson #5 | Pi-Cars

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s