Home » PythonPi Introductory Course » PythonPi: Lesson Seven

PythonPi: Lesson Seven

Today we will be learning about lists and defining function. This will allow us to build up to the final piece of coursework in lesson 8 in which you will be building a roleplaying text game!

To progress through the game, you will need to make use of every single lesson you have learned and try and win the game. First of all, in the previous lecture, we mentioned lists. Lists are known as a data structure. They can contain data. Simple as that.

Lists can contain a combination of data for example:

listPi = [‘python’, ‘java’, 22, 23]
listPy = [‘raspberry’, ‘pi’, a, b]

As mentioned before, a list always begins at location zero. In the above lists, python and raspberry are in the location zero.

If you wanted to print a part of the list you would do something like:

print listPi[0]

That will print the word python. We can use lists for while loops as shown in the last lecture and for using if statements on. We will use them in the final project for the introduction course.

You could also try printing like this to get each variable in the list on a new line:

print '\n'.join(listPi)

Defining Fucntions

Functions are important in coding when you want to recycle code often. In our role playing game, we will want to re-use the function that checks how many lives a player has. If a player has less than 1 life, we need to tell them it’s game over and then quit the application. This will have to be used after almost every input.

To define a function we use the word “def” in python.

Here is an example of how def might work.

def numberOfSweets():
print ‘There are some sweets in a bag’;
listSweets = [‘sherbet lemon’, ‘refresher’,’drumstick’];
for sweets in listSweets:
print sweets
numberOfSweets(); 

The above code is a function. That means that the code can be used multiple times by calling it, or asking for it to be run. If you’d like call the function, you just type the name of it and the brackets. The brackets are there in case you would like to take a variable from another function or part of the code and allow the function to use it. For example, if you would like to pass how many lives a player has each time you check to see if it is game over.

 


Leave a comment

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