Home » PythonPi Introductory Course » PythonPi: Lesson Five

PythonPi: Lesson Five

In the last lesson we introduced you to logic. In this lesson we will be building you up towards a final assignment in which you use what you have learned throughout the introductory course to produce a game that uses input from a user to determine a result or an output.

Else-if statements are similar to if statements however they carry out multiple comparisons. We can use an else if statement for checking an input for a user. Consider a shopkeeper. A customer asks him if he has any bread. If he does have bread he will say yes. Else if he has no bread he will say no. This is an else if scenario.

Lets us imagine that the shopkeeper checked his system, his system is a raspberry pi running python. His code would for his bread checking program would be as follows:

pythonpi2

 

This is fairly useless as someone will always have to update the stock variable and therefore whoever did that will know weather it’s in stock but it’s a great metaphor for learning if statements.  Notice the indentation, with Python, it’s awfully particular about indentation and won’t work unless the indentation is correct.  In python instead of writing the words else if, we go with the much simpler ‘elif’.

Using an else if statement will allow us to print out something related to the original if statement however it will have a different comparison, usually based on the same variable or input.

Moving on from IDLE3:

So far in this course we have used IDLE3 to show you some simple tricks. From here on out, we will not be using IDLE3 to write our code as our code will start to become more complex, we will need to write programs in an editor. You obviously have access to the Virtual Programming Lab in Classroom however we would expect you to do most of this on your raspberry pi using a python editor.

pythonpi3

 

Above we have use an else if to check if there is bread in stock. If there is no bread, the program politely asks the user to order some new bread. If there is bread in stock, the software thanks the user for updating the stock status. The varInput uses the input function of python to find out from the user. As you can see in the running program below the code, when the word no was typed, the code that ran was from the else if or elif section of the code and the print from yes was completely skipped over.

Hint: Python on your Raspberry Pi maybe version 3. Version three slightly differs from the version used in classroom. For input we use raw_input. Make sure you do this for your input for maximum grade in the lab.


Leave a comment

Your email address will not be published. Required fields are marked *