The Power of Python
Finding Python's place in the world
To start off, let's take a look at what Python is, what it is used for in the real world, and what we can gain from learning it.
What is Python?
Python is a programming language. It's a very flexible language, which is why it is often taught to beginners.
Python Loves:
Readability of Code
Simple Syntax
Basic Scripting
Complex Applications
It has a strong focus on readability of code and simple syntax. It can be used for either scripting, or for writing applications.
Install Python > Create Script > Make Magic
Easy as that!
You install it on your computer and you are then able to run Python programs. Python program file names end with a .py extension.
Python 3
is the latest greatest Python
There are many versions of Python available. Today we are using version 3 which is the latest version.
Version 2.7 is often used too, and although there is not a huge amount of difference between them, it is important to be aware of. There are differences which could cause your program to be incompatible across versions.
Many Python educational books and websites still use Python 2.7, so keep an eye out for it!
Meanwhile, we'll launch into the future...
Python in the Real World
What is it actually used for?
Although it's a great language for beginners, Python is actually very popular in real-world applications.
Python is everywhere!
It can be used in data analysis, web development, hardware programming, game development and a bunch of other things.
Github's Top 5
JavaScript
Ruby
Java
PHP
Python - woohoo!
In 2013 it was number 5 on GitHub's list of most-used languages, behind JavaScript, Ruby, Java and PHP.
Benefits of Learning Python
Why not learn something else?
So why are we learning Python. Why did YOU choose to learn Python, instead of another language?
Python teaches us many
Common Concepts
Although its syntax is fairly simple, structurally it is very similar to most other common programming languages. It makes an excellent stepping stone, and what you learn can easily be applied elsewhere.
Solve Real-World Problems
using hardware as well as software
Python can be used to solve real-world physical problems as well as purely software-based solutions. The Raspberry Pi uses Python as its main programming language. Using Raspberry Pi you can build pet feeders, radios, arcade machines, all kinds of cool physical projects.
A Valuable Skill In Any Career
pop it on your next job application!
Python is a valuable, employable skill set.
Most companies make use of Python or very similar languages, even if it's not their main focus.
It is also useful in any career path where data and automation is valuable - it's not just for full-time programmers.
Workshop Goals
What will we achieve today?
Today is all about learning some of the basics of Python through a hands-on project. We'll be playing with some code snippets to explore how Python code works, then we'll be building a text-based game.
We're Here To Make Cool Stuff
Not to do a crash course in programming theory
This workshop is not a crash course in Python, in that we don't cover a lot of depth or theory. Instead we cover a broad range of concepts with a goal in mind of an application you can actually take home at the end and show off to people.
Our hope is that you will feel comfortable enough with the code you have written during this course to be able to go away and expand on it, continue learning, continue tinkering, and even feel confident introducing others to it.
Most of all we want you to have fun. If you're struggling, ask for help. Programming is about making cool stuff, and that's what we are all here for. To learn how to make cool stuff.
The Power of Python
is wide and varied.
Python is a really interesting language with a wide number of uses.
Language Basics
A Whirlwind Tour of Variables, Conditionals, Loops and Functions
Without further ado, let's get to some actual coding.
Getting Started is Easy
Starting out with Python is as simple as writing a line of code in a text file, saving it with a .py extension, and then running that file in Python.
Code Snippets
snippets.zip
The code snippets we will be working with are available from the link on this slide. If you downloaded them to a USB stick earlier, they'll be in the Snippets folder.
Komodo Edit
or IDLE as an alternative
Komodo Edit is what we call an IDE, which stands for Intergated Development Environment.
All that means is it's a place to write your code, and a place to run it.
You may have used other code editors like Notepad++ or IDLE. Komodo is much the same, but a bit prettier. It is cross-platform, and it's free.
To work through these examples, we are going to open up the whole folder in Komodo so that we can see all the files at the same time.
Komodo Projects
Open Komodo
Create a new project
Select folder "Snippets"
Click "Open"
A Komodo project is just a folder with a bunch of files inside. We're going to open up our Snippets folder as a Project, which will allow us to see all the files at once.
Although we will be able to see all the files at once, we are going to run each one individually.
Open Komodo, create a new project... select the folder called "Snippets" and click the "Open" button. You should see a list of all the snippets down the left-hand side of your Komodo window.
Running Scripts
Go to Tools > Run Command...
Enter %(python) -u %F
Tick "Add to toolbox"
Done!
Open the first file, `00-hello-world.py`
This is our good friend the `print` function. We'll be using print a lot in our text-based Python programs, because it's how we make words appear the screen.
To run the file, we'll set up an action. Go to Tools > Run Command... and enter `%(python) -u %F`
Hello World
Using the print() function
Run your first script by double clicking the program launch code you just created. It'll be a button on the right side of your screen, in your toolbox.
The words "Hello World" should show up in a special area at the bottom of your Komodo window.
Got that working? Excellent!
Now try changing the message to say hello to you, using your name.
Variables
are like named boxes where you can store information
username = "pythongeek93"
topScore = 81000500
First up, variables!
Variables are like named boxes where you can store information.
They can be used to store numbers, words, sentences, all sorts of things. They are usually used to store information which you would like to access from many different places in your program.
Good examples of variables you might like to create could be `score` which would be a number, or `username` which would be a word, or `reminderMessage` which would probably be a sentence.
When creating a variable in Python you need a name for the variable, and a sensible starting value.
Playing with Variables
Make the program to say hello to you by name!
Can you combine a string variable and a number variable
to print out "Welcome to 2014"?
Pro Tip: to convert a number to a string, use
str(numberVariable)
Open up `01-string-variable.py` and take a look.
On the first line we can see a variable called `welcomeMessage` is being given the value `Hello world!`.
On the second line we can see the variable being passed to the print function. This is saying "Hey print function! Please print out the value stored in `welcomeMessage`".
**Challenges:**
- Change the value of `welcomeMessage` to say hello to you by name.
- Make the program print out "Welcome to 2014" by combining a string variable and a number variable.
Dictionaries and Arrays
store sets of related data values
Dictionaries let us look things up by their name.
Arrays let us look things up by their position in the array.
Dictionaries are associative structures. They associate one value with another.
An example of this would be looking up information on a person using their name.
Arrays are non-associative. They are just collections of pieces of data which are related to each other.
Arrays may be ordered, eg. from lowest value to highest, or alphabetically.
Dictionaries are not ordered as they have no need to be. You reference values by name, not by their location in the data set.
Experiment with Dictionaries and Arrays
Add your own name and score to the dictionary!
Can you print out everyone's name and score?
Open up `03-dictionaries-and-arrays.py` for a look.
The first piece of code is a dictionary storing user scores by their name.
The second piece of code is storing user names and user scores in two individual arrays.
**Challenges:**
- Add your own name and score to the dictionary, plus print it out.
- Change the array print functions to print out Betsy's name and score.
- Print out the name and score of every person in the format "Anita: 100" using three print functions.
Loops
Let you run the same piece of code many times
Loops allow you to run the same piece of code many times in a row.
Instead of writing a similar piece of code over and over many times, we can put that code inside a loop and then tell the loop how many times to run it.
Play with loops
Can you make the loop print out the numbers 1 to 10?
What about printing the 10 times tables?
Open up the file `03-loops.py`.
Try running it to see what happens.
**Challenges:**
- Print out the numbers 1 to 10.
- Change the code so that it prints out multiples of 10 instead.
- Make the loop to count from 10 to 100 in steps of 10? (10, 20, 30...)
- Print out the ten times tables in full (2 x 10 = 20)
Conditionals
If this, then that
Conditionals are like switches which only turn on under certain circumstances.
They can basically be boiled down to pieces of code which represent an approach of "if this, then that".
In the example, `itIsRaining` is a variable, but it is not text or a number as we looked at previously.
The variable `itIsRaining` is what we call a "boolean". Boolean variables can only have a value of true or false.
Notice how the code describing the action to take is indented from the left edge. This signals to the computer that the indented piece of code is "inside" or "housed by" the line above it.
You can create that indent using the "tab" key on your keyboard.
Play with Conditionals
Can you add support for a bronze trophy?
The award should be given if the player's score is over 600.
Open up `04-conditionals.py`
All conditional statements are made up of combinations of `if`, `elif` and `else`, in that order.
The word `elif` is short for "else if". In plain English, you might say it means "otherwise, if this other test is true...".
The tests `if` and `elif` both need boolean tests attached, to figure out whether the code they house should be run.
The `else` part of a conditional statement houses code which should only be run if none of the other tests work out to a value of true.
**Challenges:**
- Add support for a bronze trophy awarded when your score is over 600 points. You can change the value of `score` to test your code.
Functions
are named pieces of reusable code
Functions allow you to define reusable pieces of code under sensible names.
We put a piece of code in a function when we want to be able to use it many times, often from different places in the same program.
Playing with Functions
Said hello? Now say goodbye!
See if you can multiply by ten instead of two.
Open up `05-functions.py`
**Challenges:**
- Make another function called `sayGoodbye` and have it print an appropriate message.
- Call the `sayHello` and `sayGoodbye` functions one after the other.
- Change the `multiplyByTwo` function to `multiplyByTen` and update the code so it correctly multiplies by 10.
Classes
Classes can be used to represent real-world objects
Classes are awesome.
Open up `animals1.py` and allow Hayley to explain.
Multiple Classes
You'll probably need more than one class
Classes get even more awesome.
Open up `animals2.py` and have a play.
Class Inheritance
Classes can even be mixed together!
You can do some super crazy stuff with classes.
Open up `animals3.py` for a look.
The Language of Python
is made up of just a few different parts.
We've covered some of the major code structures included in the Python language. Applications are made up of combinations of these concepts, brought together in different ways to create different results.
Creating Python Programs
Bringing together Python code into a full program
So far we have looked at pieces of the Python language and how to run basics scripts, but how do you combine all these ideas into a more complex program?
Let's get started!
Python Programs
What we have been doing so far is working with "Python scripts".
Scripts are usually just a single file, and solve a problem in a fairly linear fashion.
A more complex Python program may pull together many different pieces of code from different files, each with a different purpose.
A Python program could be a website, a desktop application, or a command line program. We will be building a command line program.
Our Program
The Python program we will be building throughout this workshop will be a text-based game, run on the command line.
The player will need to navigate a series of rooms and find a key to unlock the door at the end of the game.
To create this program we will be using all of the concepts we looked at earlier, as well as classes and how to combine multiple python files into a single program.
By the end you will have your own complete and playable text-based game.
Starter Code
AdventureWorld.zip
To save some time (and your typing fingers!), we've provided a set of starter code.
You can download a zip of the files from here.
Project Tour
game.py
adventureworld.py
objects:
- backpack.py
- door.py
- item.py
rooms:
- room.py
- alleyway.py
Open up the folder in Komodo, and let's have a quick tour.
Our main folder contains 3 files and two folders.
_tour existing code_
- What do each of the files do?
- What are the folders for?
- What is the purpose of that weird underscore file?
- What is the starting point for the program.
First Run
Welcome to my Adventure Game
You wake to find yourself in a dark, dirty alleyway. Night is falling. Your head hurts and you can't remember how you got here.
So what happens when we run the program?
To run your program, you need to have the file `game.py` open, and then click the "run code" button.
You will need to do this every time you want to run your program.
Rooms
Our game is going to be structured around a series of rooms. The player will move between those rooms via doors.
Open up the file `alleyway.py` in the `rooms` folder.
This is what we call a `class`. A `class` is usually created to represent an object of some kind. It contains variables and functions which are related to that object.
The `Alleyway` class contains all the information we need about the Alleyway, which is the first "room" our player will enter.
Add alleyway to the game
Import Alleyway
class at the top of adventureworld.py
:
import sys
from rooms.alleyway import Alleyway
Add the Alleyway to the list of available rooms:
def createRooms(self):
self.rooms = {
"The Alleyway": Alleyway()
}
Let's make our game automatically put our player into the alleyway at the start of our game.
The first step is to add the alleyway to the list of rooms available in the game. Although we have a class which represents the alleyway, we haven't actually included it in our game yet.
Open up `adventureworld.py` and find the `createRooms` function.
You can see we already have a dictionary of room set up, but the dictionary is empty.
Start by adding the Alleyway to the rooms dictionary.
Try running your program to make sure there are no errors.
Enter Alleyway
def start(self):
print("")
print("Welcome to my Adventure Game")
print("You wake to find yourself in a dark, dirty alleyway. Night is falling. Your head hurts and you can't remember how you got here. ")
print("")
room = self.rooms["Alleyway"]
print(room.name)
print(room.description)
Now we need to have the player actually enter the alleyway.
Find your game introduction text, in the main `adventureworld.py` file.
Underneath your introduction, we want to get the information about the Alleyway and print it our for the user.
Run the game to check that it works!
Door options
# print out the options
print("Options:")
# list the door options
for door in room.doors:
print ("[" + door.button + "] " + door.name)
So the player is in the Alleyway, now we need to give them some options.
We need to list all of the available doors.
We'll add the code to show the door options immediately after the room decription.
First we'll print out a heading which says "Options", and then use a loop to print out each of the doors along with the key to press to go through them.
Run your program :) Happy? Onwards!
Game Loops
Running the same code over, and over, and over...
Programs are a bit boring when they just run and then finish.
Let's look at how we can smartly structure our code to keep running the same core task from a reusable piece of code.
Loop Identification
Set Up Game
Introduction
Enter Room
Describe Room
Offer options
Choose option
End Game
So we've come across our first instance of having to repeat some pretty serious code.
If we take a closer look at what we are trying to achieve with our game, we see that there is a good chunk of it in the middle which will actually be repeated for every move the player makes.
The steps of "describe room", "offer options" and "choose option" occur for every room in the game.
So, let's identify the code which does those steps, and split it out into its own function where we can reuse it over and over.
Loop Definition
def enterRoom(self, roomName):
room = self.rooms[roomName]
print(room.name)
print(room.description)
# print out the options
print("Options:")
# list the door options
for door in room.doors:
print ("[" + door.button + "] " + door.name)
# ask the user to make a choice
print("")
buttonPressed = input("What next? ")
So let's take everything we've added so far and move it to a new function called `enterRoom`.
Don't forget to create a function parameter called `roomName` so we know which room to enter!
Also make sure to use the generic `roomName` in place of our old hard-coded `"Alleyway"`.
Enter Room
self.enterRoom("Alleyway")
Now, calling the `enterRoom` function and passing it the name of the room to enter should print out all the information for the given room.
Call the `enterRoom` function to enter the Alleyway immediately after the introduction has been printed.
Run your game to check that it still works the same as before, despite the code rearrangement!
Other Rooms
Now would be an ideal time to create and test all the other rooms we want to use in our game.
For every room in the game:
- Import the new room at the top of your main adventureworld file.
- Add the room to the rooms dictionary
- Test that the room has been set up correctly by entering that room as the first room of the game.
Once you've tested that every room is printing out the correct information, we can move on to the next step!
Navigating Rooms
# try to find a door associated with that button
chosenDoor = room.getDoorByButton(buttonPressed)
self.enterRoom(chosenDoor.leadsTo)
Now that all our rooms are set up, we should be able to navigate between them.
After your player has pressed a button, find the room associated with that button and enter the room.
Victory Condition
So our game loop is working fantastically, we can navigate through the rooms pretty much forever... but where's the fun in that?
It's time to add a way to win our game.
The way it's set up currently is so that if you manage to find your way into the tool shed, you win. Let's implement that.
When we enter a room, we want to print the description of the room, and then IF the room we are in is the tool shed, end the game.
Pro Tip: Function length
# enter a specific room
def enterRoom(self, roomName):
room = self.rooms[roomName]
# describe the room
print("")
print(room.name)
print(room.description)
print("")
if room.name == "Tool Shed":
self.end()
else:
self.askWhatToDo(room)
While we're here, let's take a closer look at our `enterRoom` function.
When functions are longer than about 10 lines, it pays to look closely at them and see if the code might be doing more than the function name describes.
Is there some functionality we can group and split off into another function with a sensible name?
At the moment, this function:
- Prints the name and description of the room
- Prints out all the door options for the room
- Prompts the user to make a choice
Ask What To Do
def askWhatToDo(self, room):
# print out the options
print("Options:")
... all the lines between ...
self.enterRoom(chosenDoor.leadsTo)
If we move all the code which lists the room options and asks the user what to do into its own function, it becomes a lot easier to read our `enterRoom` function and to see what it actually does.
Create a new function called `askWhatToDo` and move the related code to it.
Make sure to call the function from the code's original location, and to pass the room information!
Simplified enterRoom
def enterRoom(self, roomName):
room = self.rooms[roomName]
print(room.name)
print(room.description)
if room.name == "Tool Shed":
self.end()
else:
self.askWhatToDo(room)
After refactoring our code, it is much easier to see that after we enter a room, we print out its details and then if it's the tool shed end the game, otherwise ask the player what to do next.
Much tidier!
Hide Key
In cellar.py:
# create all the items you can interact with in the room
self.items = [
Item("k", "Key")
]
Just finding your way to a room is a bit easy. Let's put a lock on the door.
This is what our `items` array is for in each of our room classes.
I'm going to hide my key in the cellar.
Print Room Items
# list the door options
for door in room.doors:
print ("[" + door.button + "] " + door.name)
# list the item options
for item in room.items:
print ("[" + item.button + "] " + item.name)
Hiding a key is one thing, but we need to tell our player that the key exists in the room too.
We'll do this by adding any items in the room to the list of options we're already printing.
This means that every time you enter a room, your options will be a list of doors and items for you to choose from.
In our `askWhatToDo` method, add another loop which prints the room's items the same way it prints the room's doors.
You can copy the code for the doors and modify it to print items instead.
Run your game and find the key to check that it works.
Picking Up Items
Cool, we can see the key! Now how do we pick it up? Hmm.
For this part we will need to:
- Set up a backpack
- Check the user's button press against the list of available items
- Remove the item from the room
- Add the item to our backpack
Backpack
self.backpack = Backpack()
In our adventureworld's init function, when we create the room, we also need to create a backpack.
If you take a look inside the backpack class, you'll see that it is a fairly simple object.
It contains an `items` array to hold the items, and a function for retrieving items by name.
Make sure to import the class!
Maybe this should actually be a dictionary...
Take Item
# add an item to your backpack
def takeItem(self, item, room):
room.removeItem(item)
self.backpack.items.append(item)
print("Added " + item.name + " to backpack.")
Set up a function to remove the item from the room and put it in your backpack.
Item to Backpack
# act based on the door or item selected
if chosenDoor != None:
self.enterRoom(chosenDoor.leadsTo)
elif chosenItem != None:
self.takeItem(chosenItem, room)
self.askWhatToDo(room)
Instead of plain old `self.enterRoom()` we need something a little more complicated now.
Lock Door
In gardens.py
, modify the Shed Door:
# create all the doors leading out of the room
self.doors = [
Door("g", "Glass Door", "Dining Hall"),
Door("s", "Shed Door", "Tool Shed", "Key")
]
We want to lock the door from the garden side, so in `gardens.py` we need to add a required item to the tool shed door.
Take a look at `Door.py` to see how the `requiredItem` parameter is optional.
The item name we add needs to exactly match the name of the item we added to the cellar.
Respect Lock
Instead of just:
# act based on the door or item selected
if chosenDoor != None:
self.enterRoom(chosenDoor.leadsTo)
We need to do:
# act based on the door or item selected
if chosenDoor != None:
self.openDoor(chosenDoor, room)
It's not enough to just add a required item to the door. We need to actually check for that item when the player tried to enter the room.
If a door has a required item, we shouldn't be able to enter unless we have that item in our backpack.
To add in this functionality, we'll add an extra step before entering a room - "open door". At the end of the open door function, if we managed to open the door, we will _then_ enter the room.
Open Door
# try to open the chosen door
def openDoor(self, door, room):
if door.requiredItem == None:
self.enterRoom(door.leadsTo)
else:
item = self.backpack.getItem(door.requiredItem)
if item != None:
print("Used " + item.name)
self.enterRoom(door.leadsTo)
else:
print("It looks like you need a " + door.requiredItem)
self.askWhatToDo(room)
If the door has no required item, we can enter the room without trouble.
Otherwise... try to get the required item from our backpack.
If we have the item, use it, and enter the room.
If we don't have the item, print an error and ask the user what to do next.
Play your game again. Can you open the locked door without the item?
Once you pick up the key, can you then open the door?
NCSS Challenge
6-week programming challenge
working with other students and mentors
plus you could earn a trip to Sydney!
Congratulations!
You're now officially a Python Developer!
Before you go, click through to the last link of the day:
http://tiny.cc/gather