Welcome

In this section of the Nathan Tech website, it is our intension to provide you the ability to start from knowing absolutely nothing about programming, to being able to use python compitantly for any project you choose, simply by following these tutorials.
Each tutorial is roughly 15 minutes in length, and will walk you through step-by-step explanations, with frequent recaps of each part.
the tutorials are divided into two sections:
Each tutorial is available for download and may be freely distributed providing it is clear that we, Nathan Tech, are the owners of, and recorders of, the tutorial and that the tutorial remains unmodified and free.
Please provide feedback through our Contact Form.

Section 1: Learning.

1: Introduction

A quick introduction to the language, including downloading and installing.

Download
Text transcript>hello there, ladies and gentlemen.
My name is Nathan smith, and today I am going to be doing a hopefully extended set of tutorials on the python programming language.
For those who do not know, python is perhaps one of the easiest programming languages to learn to help make you a developer of software, server clients, games or pretty much anything.
It's flexible, it's pretty dynamic, and its easy to learn at the end of the day.
And that is what these tutorials are about Getting you on your feet, with python.
The first 6 episodes of this series are going to be focussed on learning the language itself, then in those following we will be talking about building a simple game.
So lets get started.
First of all, we are going to talk about how to obtain python.
Python can be obtained from python.org.
Nice and simple, go to their website, click download, job done.
There are two versions of python available at the time of this recording, python 2 and python 3.
We will be working with version 3, because as of January 2020, python 2 will no-longer be supported.
So, once you've downloaded python 3, you will...
In this recording we will be using the executable installer, there is a web one available, but we will walk you through the executable.
So up on my screen at the moment I have a question of "What items I want installed."
I have the following items checked:
documentation,
pip,
tcl and idle,
python test suite,
py launcher
and for all users.
I'm going to click next, it did come up by default but I'm not sure if that is due to me already having python.
So next, and now we have a screen in which it is asking some more questions.
You definitely want to associate .py files with python, create shortcuts you may want, and add python to environment variables you certainly want.
Compile prestate libraries is up to you, I personally check it.
So!
Click install and off it goes.
So while that installs, I'll just talk to you about these tutorials, what they mean, and what their intention is.
The tutorials are roughly 15 minutes long, and will basically hopefully be able to get you on your feet with programming.
Code samples will be provided, like in the next tutorial for instance, but they will also teach you how to think for yourself in these situations.
I'm just going to talk through how I think of the language, throwing in some little stories that hopefully should keep things interesting and make it easier on you.
This should help you visualise this language in an easy way.
Python is an object orientated programming language, for those who care about such things.
If you don't, I'll talk about it later, don't worry.
What else can I tell you.
So python has been around for quite a while, and is a tabbed language.
This means that indentation is very important, which is something we will cover later on.
These tutorials were made by a visually impaired person, that's me, and as of episode 7 will be targeted more at how to make an audio game.
We will touch, briefly, on visual elements, but our main emphasis will be on the audio aspects.
To that end, we will be focussing on pygame, which is a fully-featured gaming systems as of the 7th episode.
You may hear background music in the tutorial, which I claim no ownership for and is to help provide entertainment while I ramble on.
If you have any feedback about these tutorials, good, bad or otherwise, please let me know through the contact form.
You can find the form at https://nathantech.net/contact.php.
I am providing these tutorials for free, and to download should you wish and as long as you make it clear that I, Nathan smith of Nathan Tech, am the voice being heard, and you have not made me sound any more stupid than I do already, I have no problem with you playing them as and how you see fit.
beauty is in the ey eye of the beholder, and I can't see it, so we're all good!
If there are things that you would like these tutorials to cover that they do not already, please let me know!
These are for enspiring, or aspiring programmers who hopefully will be enspiring.
So the idea behind these tutorials is you can sit back, knowing nothing of programming, pick them up and get started.
to use python you will need a basic understanding of the command line however these tutorials will teach you that as soon as this installation finishes!
the command line is a windows built tool, I believe on mac it is called terminal.
You can open it on windows by pressing windows+r, then typing CMD.
you will get a window that looks a little like "C:\windows32\users".
It looks fancy, trust me on this!
you will do part of your innicial tests in this window, such as running uncompiled scripts from here, so it pays to know how to use it.
there are several ways o navigate this window, depending whether you are doing it visually or with a screen reader like JAWS or NVDA.
From my experience when using voiceover you interact with the window and then use voiceover left and right to review the text.
With NVDA, you use the NVDA cursor to navigate through the window.
For example, I use NVDA up and down arrow.
Don't be scared by the command line, it's nice and simple!
Lets talk about two basic commands you will use a lot.
Command number 1: cd.
Open up your terminal and type cd then hit enter.
CD stands for change directory.
This will just take you to the directory you are in, for intsance: "c:\users\bob."
If we wanted to go into documents, we'd do: "cd documents" and hit enter. If I can spell correctly.
You can go up one directly by typing "cd .."
Fancy!
It's a very useful command as it enables you to navigate to your scripts once they are made.
how do we test python is installed?
The most important thing for you to know is how to run python from the command line.
You do this by typing python in your command line window which for me, after a pause, showed "python 3.7.3" which was the version I used at the time of recording.
First time I was ever up-to-date in my life!
We're going to close that by pressing control z on windows, or command z on mac.
Congratulations, you have just launched your first python window!
Well done, I hope you feel warm and fuzzy.
So how do we close command line? type exit.
that pretty much concludes this introduction, I can't drag it on for 15 minutes.
All feedback is welcome.
thank you for listening, this has been Nathan smith of Nathan Tech.

2: Variables

We talk about the 6 most common variable types and the print command.
Download
code snippets print("hello");
name="Nathan"
print("hello "+name)

Text transcript>Hello there, ladies and gentlemen it is me, Nathan smith of Nathan Tech as you are no doubt expecting by now and welcome to the Learning to program in python tutorials, number 2.
In this tutorial we are going to be learning about variables, which are the fundamental of any programming language.
First of all what does the word variable mean/
Lets break it down.
in the word variable you have the word vary, and that is what we are going to focus on, because able is just so boring, and who wants to talk about Able anyway.
Vary means to change.
So a variable is a piece of data that can change.
for example, and the example we will use throughout this tutorial is a person, like my good self.
A variable about me might be my age, because that can change every second, of every minute, of every hour of every day. I try not to think about me getting old that fast though.
In this tutorial we will cover some of the most commonly used variable types, but not all of them. there are too many to name, but we will teach you the fundamentals.
Lets load up a python terminal in the way discussed in tutorial 1.
Lets talk about variable types:
you may have heard, if you have experience in programming the term data types, in other words, what a piece of data is.
they define what type of data you are working with.
In other languages you have to define what type of variable you are using, for example, if I wanted a number I might write:
int my_number=1;
In python however, you simply write:
number=1;
this is why python is so flexible and easy!
This however can also make it slightly dangerous, as you can accidentally change your variable type.
First of all lets cover numbers.
Numbers are split into two categories:
intigers
and what is commonly refered to as floating points, or decemal numbers.
As you may have guessed an intiger is a single, hole number like 1, 2, 3, 4 or 5.
To test this in python simply type:
number=1
you'll get a couple of greater than signs, and nothing much else.
To tell us about this variable though, and to make sure we've defined it, lets use a function called print.
Print is a built in python command, but don't worry too much about that you'll learn about those in a later episode.
For now though, simply type:
print(number)
Note the punctuation in the above line, it's very important!
the print statement does exactly what it sounds like. It will print something to the command line.
In our case, it tells us the number 1.
If you want to find out exactly how this is done, feel free to google it, delving into print further is above this tutorials purpose!
So moving swiftly on, we'll cover floats, or doubles.
Call them what you will, they're decemal numbers like 3.1.
Try making a float like this:
number=3.2
print(number)
All pretty simple!
When considering the subject of a person, perhaps one of the most important things about them is their name.
My name, for instance, is Nathan smith of Nathan Tech, though it doesn't say "of Nathan Tech" on my birth certificate!
This would be a string.
A string is a collection of characters. It can be one character, 10 characters, or a string as long as you like. providing you have the memory for it.
How long is a piece of string after all, right?
Insert awkward silence at bad joke.
So how do we define strings in python? Pretty simple, we use quotes like so:
name="Bob"
You could also do:
name='Bob'
Most programmers prefer the second way, due to things we will cover later.
print(name)
Hey look! It's Bob.
the final simple variable type that we are going to cover is boolean. Big fancy word!
Boolean means true or false.
Important! Python requires you to capitalise the words True and False.
Lets define a variable called boy:
boy=True
If we do print(boy) we get true.
If however we do:
boy=true
We get a traceback that says "name true is unknown."
this is python's way of telling us we refered to a variable that does not exist.
In the second part of the tutorial I would like to cover two slightly more complex variable types.
they're not complicated as such, just more interesting and fun.
the first of these is lists.
A list is defined with square brackets, like so:
l=[]
A list can contain other variables, like numbers or floats, or strings, or even other lists! Like so:
l=[1, 2, 3, 4, 5]
Commas, as you may have guessed, separate elements of a list.
Lets type:
print(l)
Now, using our variables from earlier, lets make a new list:
l=[number, name, 3, 4, 5]
print(l)
This may not seem complicated, and it really isn't, but now lets up it a step.
You can actually store lists in lists, these are refered to as multi-level arrays.
We won't really use these, but allow me to explain them to you anyway.
Imagine a room.
Inside this room you have boxes.
If this was in code form, the room would be the master list, the boxes the next list the stuff inside the boxes the next list, and so on.
Here is a visual representation, if it helps:
box1=["apples", "bananas", "carrots"]
box2=["chocolate", "more chocolate", "a lot of chocolate"]
box3=["chicken", "beef", "pork"]
room=[box1, box2, box3]
print(room)
[["apples", "bananas", "carrots"], ["chocolate", "more chocolate", "a lot of chocolate"], ["chicken", "beef", "pork"]]
Now you have a multi-level array.
Well done!
the final, and perhaps most interesting, of variables we are going to touch on is called a dictionary.
quite a lot of people have heard of this, but not many understand them and they can get quite scared of them, in fact.
It's my job to make sure you understand them, and can educate the masses!
I'm going to explain these in a way you can hopefully understand.
First, lets define an empty dictionary which is done in braces like so:
d={}
Now. Here is how I am going to explain dictionaries.
Imagine, if you will, this dictionary represents my good self. Or your good self.
What would this dictionary need?
Well for starters, a name, gender, age, obviously not a good looking state, as that would always be set to true. Obviously!
but lets go with that for now.
This is where python dictionaries come in handy.
Dictionaries contain a key and a value.
Remember those terms, key, and value.
Lets define our first piece of information in this dictionary:
We will do:
d["name"]="Bob"
note the punctuation.
What does this mean?
Well, we have d, which is our dictionary. then we have square brackkets, inside which is the string "name".
This is the key.
So here we have key = value.
And that is what makes up a python dictionary.
In this case, the key is "name" the value is "bob".
This is why so many people like python dictionaries, because they're easy to organise!
We can check the value of this, too!
d["name"]
this will show us the value for the key name. We can also do:
print(d["name"])
How useful is that?
Very!
Because now, we can also define age in the same way.
d["age"]="none of your business"
Absolutely fantastic.
Python can be used in many things, for example score boards.
Scoreboard={}
scoreboard["bob"]=10
Obviously this can be done in other ways, too, but it shows you at least an example!
this covers the fundamental variables you will use most often in python but as a last key term, lets run over a final use for print.
First of all lets define:
name="Bob"
Les do the following:
print("Hello "+name)
This produces "hello Nathan".
There are a few things to note about this though.
Try out the following:
print("hello "+123)
did you get a traceback/
Can not concatinate string and int objects.
This means it can not add an int to the end of your string.
However, if you do:
1+2
This gives us 3.
yes, python can be your pocket calculator.
there are some ways to do conversions in python, which are listed above this text in the snippets section.
Ultimately, once you know them, you know them and there's not much more to know.
As a final ending to this tutorial, lets do a little more variable manipulation.
age=10
age=age+10
Now why have we done this?
What does it do?
First of all, you have:
age+10
age is 10, 10 + 10 is 20.
So why do we have the age= part?
If we just wrote: age+10 python would not store the result.
It would lose it. what a loser!
by writing: age=age+10, we tell python to take the value of age, which is 10, add 10 to make 20, and store it back in the age variable!
You can now see, if you type:
print(age)
that age does indeed equal 20.
I've run out of time for this episode, but hopefully you found it useful and are now thinking of other ways that you can apply this knowledge.
I look forward to seeing you in part 3, and thank you for listening.
This was Nathan smith of Nathan Tech.


3, if, elif, and else

In this tutorial we go over the different ways to use the if statement.
Download
Code Snippet
number=1
if(number==1):
 print(number)

number=10
if(number>5):
 print("nice")
elif(number<3):
 print("rubbish")
else:
 print("not bad")

score=10
if(score<2):
 print("What game are you playing?")
elif(score>=2 and score<7):
 print("not too bad.")
elif(score>7):
 print("great score")

score=10
if(score>3 and score<5):
 print("not bad")
elif(score>=5):
 if(score==10):
  print("NICE!")
 else:
  print("not bad")
else:
 print("rubbish!")

Text transcript>
Hello there and welcome yes, it is I Nathan smith of Nathan tech, back again with another tutorial for learning python.
In this tutorial we intend to cover one or two things we missed out, ahem, in episode two, as well as a new funky statement.
Lets do a quick recap.
Last time, we touchd on variables and the variable types available.
We also experimented with print.
this time, lets start off with a personal coding technique of mine.
it's what I call, "How to use a text editor."
First of all lets talk about what a text editor is.
A text editor is a program you use to write text, like notepad, notepad++, word, wordpad, ETC.
Not all are suitable for writing code, however.
For example, word is probably not your best choice.
I personally choose notepad, but notepad++ is a specific code editor and what ever one you choose to use is up to you.
If you want, at this point, create a folder in your documents and call it something.
In this, put a file in here of your choice.
It should be noted, the file must be a .py extension, not a .txt.
you can do this by opening a new file, saving it, and in the name field put quote, main.py, quote.
"main.py"
that will save nicely, and you can continue onwards.
In this tutorial we are now going to talk about what it means to work with a tabbed programming language.
In my personal experience there are two types of language.
One is tabbed, one is not.
C, for example, uses one that is enclosed in braces.
In c, you'd define a function like this:void main() {
code
}.
In python however, this code looks like:
def main():
 indented code.
this sounds a little complicated, but it really isn't!
It actually helps keep track of what code is in what place, making debugging that bit easier!
It is important here as we are going to start the next bit, statements.
the if statement is a built in function of python.
We will touch on what that means later.
To that end, we call functions using parens.
You've seen this earlier with print.
print("hi")
The print statement is a builtin function.
As you can see, the word print is the name of the function, and the parens contain arguments.
Arguments tell functions what to do, pretty much.
If is another one of these functions.
this is where I recommend you use that file, because you will find it easier to keep track of indentation and such.
Before we continue, allow me to touch briefly on how to run a python file.
The way you do this is open up your terminal or command line.
then change to the directory your file is in, for example:
cd documents
then
cd tutorials.
to run a python file simply type python followed by the name of your file.
python main.py
so!
Back to our original topic.
Lets define a variable first.
number=1
First, lets write a very simple if statment.
if(number>1):
We've written if, which is the name of the builtin, left paren, so we're giving arguments, number>1. Is the number greater than 1? IE, if the value of number is greater than 1, then do the code that follows.
Python knows what code is related to this if function, because we indent it.
if(number>1):
 print("hello.")
If you are in the terminal, hit enter twice.
If not, run the file.
If you do so, you'll see nothing has happened!
Why?
Because numberis equal to 1, not greater than 1.
so how do we say in python, if number is equal to 1?
if we wrote if(number=1), python would get a bit confused.
Instead we use two equal signs, like so:
if(number==1):
 print("hello!")
Now run this code, and see what you get.
We got: "hello!"
This is why running is a file becomes useful, as you can quickly adjust your code without typing it out again.
Lets introduce another element to this code called else.
if(number==1):
 print("hello")
else:
 print("huh?")
Notice how the if statement and the else statement have the same indentation? this tells python that they are related to each other!
If this was a list of if statements, like this:
if(number>1):
 if(number==2):
Python needs to know which if statement the else refers to.
that's where the indentation comes in.
Feel free to play around with this and get used to it.
we're going to introduce a final element to this now called elif.
this literally means else if.
It would go something like this.
If I gave you an instruction, if number is 1, do this, else if it is 2, do this, else if it is 3, do this, if none of these? Don't bother.
Lets put this into python code:
if(number==1):
 print("1")
elif(number==2):
 print("2")
else:
 print("not 1 or 2.")
If you'd like to run this, and set your number variable to 1, you will see the end result is 1. If you set number to 2, the result is 2.
Where might this come in useful/
Here's an example!
score=10
if(score>10):
 print("Woohoo, great score!")
elif(score<5):
 print("What game are you playing?")
else:
 print("That's decent, I suppose.")
Why is the else statement important here?
Because we have if the score is greater than 10, or less than 5. But what if my score is 8? That's where else comes in.
Personally I think 10 is a great score, but that's just me.
Many things can be put into an if statment, but the fundamentals are:
== means the same as
>= meaning greater than or equal to
<= meaning less than or equal to
> meaning greater than
< meaning less than.
Lets put these into practice:
if(score==10):
 print("You got 10.")
elif(score>10):
 print("Niiiiice!")
elif(score<5):
 print("That's rubbish. what are you doing?")
elif(score>=5 and score<=10):
 print("not too bad.")
else:
 print("Decent. I guess...")
Lets talk about the and and or that we used in the above statement.
The and and the or allow you to define extra items of the if statement. Like this:
if(score==10 or score==11):
 print("Nice")
Here is another example:
if(score>=8 and score,=11):
 print("Nice.")
elif(score>11):
 print("Really nice!")
I hope you have enjoyed this tutorial and we will go over it a bit more in the next episode.
thank you for listening, this has been Nathan smith of Nathan Tech.

4: loops

In this tutorial, we introduce the for and while loop, as well as a couple of builtin functions. Download
Code Snippet
number=1
while(number<10):
 print(number)
 number=number+1

number=1
while(number<10):
 if(number==5):
  break
 print(number)
 number=number+1

l=[1, 2, 3]
length(l)
range(3)

l=["bob", "freddy", "jimmy"]
for x in l:
 print(x)

l=["bob", "freddy", "jimmy"]
print(l[1])
for x in range(len(l)):
 print(x)


l=["bob", "freddy", "jimmy"]
for x in (range(len(l)):
 print(str(x+1)+" "+l[x])

Text transcript>
Hello there ladies and gentlemen, it is indeed me, nathan smith of Nathan Tech back with another learning to code in python tutorial.
Lets quickly recap what was shown in the previous episode:
Last time we learned about the if statement, how to combine it with else, and elif, as well as touching briefly on indentation and why it is important.
We also spoke about the and, and or, of those statements.
First, lets define two variables:
name="bob"
boy=True
Note the capitalisation.
if(boy==True and name=="andrew"):
 print("Hello Andrew, you handsome lad.")
elif(boy==True and name=="bob"):
 print("hello bob, you handsome chap.")
else:
 print("Who on earth are you?")
If you run this code, you see an example of how the and statement can be used within code to change what happens, for example, if you change boy=True to boy=False, you will get a different output.
Recap over, lets talk about todays episode.
In this tutorial we will be covering for and while loops.
First of all we will cover the while loop, as it is slightly easier to do.
you declare a while loop very similarly to an if statement.
Be Careful!
It is very easy to create a loop that will never end. It's not really that good!
Lets define a new variable:
number=1
Now, lets look at a while loop:
while(number<10):
As you can see, the format is pretty simple to an if statement, and it is pretty obvious what it does. While number is less than 10, execute the code inside the loop.
LEts give it some code to do now:
while(number<10):
 print(number)
 number=number+1
What does this code do?
We can see a call to the print function, with arguments of our number, and then on the next line it increases the value of number by one.
Executing this code would give output of:
1
2
3
4
5
6
7
8
9
This is because while the numbers 1 to 9 are less than 10 the code executes, but the second it becomes 10, it stops and exits.
Now, lets up it a step and introduce an if statement:
number=1
while(number<10):
 if(number==5):
  break
 print(number)
 number=number+1
Make sure and include that last line, unlike me who forgot it in the recording and got spammed!
We have a new term in the above loop: break.
Break does exactly what it sounds like. If a statement is met in which break is called upon, it will break out of a loop.
In our above example, if you run it, you will see that the numbers 1 to 4 are printed, but when the code execution hits 5, because of this line:
 if(number==5):
The break keyword is met, and the loop stops execution.
Another way to do this is through the use of the return keyword.
return, unlike break, will both break out of the loop, and stop execution of the function your code is defined in.
We'll cover more on return later on in the episode on functions.
to stop a broken script for spamming you, like I had to, you can press control c on windows, or command c on mac.
Lets talk about the for loop, which is another type of loop.
For loops are a little bit different to whiles, as they work on... Kind of different bases.
Lets put it into a practical example.
there are two ways to define a for loop.
Method 1.
Lets define an array called l first:
l=["bob", "freddy", "jimmy"]
now we are going to use a for statement to print hello to each of these people.
A for statement is made up of two parts:
for something
in something.
Like this:
for x in l:
In the above line, x is a variable that refers to each item in the list l.
we quite literally tell python for each item in this list, assign it to the variable x, and execute the code inside the loop, like so:
for x in l:
 print("Hello "+x)
Obviously we can imbed if statements into this, like so:
for x in l:
 if(x=="bob"):
  print("Go away bob.")
 else:
  print("Hello "+x)
At this point, allow me to mention something I forgot in the previous tutorial.
We know that == means equal to something, for example:if(name=="bob")
Means if the variable name is equal to, or is set as, "bob".
But how do we say isn't equal to?
We put this: !=
if(name!="bob"):
Lets rewrite the loop above using this new knowledge:
for x in l:
 if(name!="bob"):
  print("Hello "+x)
You can play with that as much as you like!
Recommendation: Using this tutorial and the one before, see if you can figure out how to print a multi-level array.
Lets talk about the second type of for loop.
First though, I want to tell you about a builtin function called len.
len(l)
That returns 3.
Len means length, and will return the length of a list or string passed to it.
len(l)
Is 3 because our l variable has 3 elements.
I'm also going to introduce you to range.
range(3)
This produces output that is a little bit strange, but don't worry too much.
The point I want you to take from this is that it returns, in essence, the numbers 0, 1, and 2.
Like so:
for x in range(3):
 print(x)
In a large percentage of programming languages, they start a count at 0, not 1.
Lets put this in an applied term.
Take our list l from earlier.
As humans, we see:
element 1 is bob
element 2 is freddy
element 3 is jimmy.
The computer, however, sees the following:
element 0 is bob
element 1 is freddy
element 2 is jimmy.
Lets index into a list.
Wait, lets what now?
Big words! time! out!
Indexing into a list means to tell python to tell us an element in a list:
print(l[1])
Freddy! How nice.
print(l[0])
Hey Bob!
this becomes important when considering the following:
l[4]
Traceback! Range error.
this is unsurprising.
l[3]
Same thing. List index out of range, also known as a range error.
As discussed earlier, this is because computers start at 0.
So what this long-winded explanation boils down to is a practical example of range, like so:
for x in range(len(l)):
 print(l[x])
What does this do?
len(l)
Returns 3,
which we then parse to range:
range(len(l))
which returns the numbers 0, 1, and 2.
Our for loop handles this and prints out each element of the list.
Lets do a final for statement using some code from an above tutorial.
Str will convert an intiger to a string.
for x in range(len(l)):
 print(str(x+1) + ": "+ l[x])
What can we see in this?
First, l[x] will print the item in the list.
We also know that str(x+1) will be x, plus 1, as a string.
Our output is:
1 Bob
2 Freddy
3 Jimmy.
That concludes this tutorial however I fully recommend you play around with this until it's your bread and butter, as they're fundamental in knowing what to do in programming.
Be careful not to spam yourself out with the while loops, but if you do get stuck, just press that magic control c, command c, keystroke.
thank you for listening. this was Nathan Smith of nathan tech.

5: functions

We introduce how to use functions, and explain why they are useful.
Download
Code Snippet.
def test(x):
 print(x)
def sum(l):
 total=0
 for x in l:
  total=total+x
 return total
def inrange(px, ex):
 n=px-ex
 if(n<3):
  return 1;
 else:
  return 0

Text transcript>
Hello there and welcome, yes it is me Nathan smith of Nathan Tech back with another learning to code in python tutorial.
recap: Last time we touched on the while and for loops, which hopefully you understand now.
This time we are going to talk about one of the most important part of any programming language.
Functions.
Functions may seem scarey, but they're not!
Simply put, a function is a piece of code you wish to execute a lot.
Lets put this into a practical example.
If you were creating an audio game, chances are you'd want to play sounds a lot, right?
Now sure,you could write out the code to load, process, position and play a sound file over, and over, and over, and over again, or, you could just put the code into  funvtion, and call that each time!
By using functions, you save yourself time, effort, and wasted lines of code.
You've already seen some examples of a function such as when we used builtin functions like len, print, and range.
These sorts of functions are called built in functions, and come as part of python by default.
We are going to create one or two functions of our own.
First, how do we define a function?
A function requires two things:
1, a name
and 2, some arguments.
Not all functions take arguments, like this one below:
def test():
 print("Hello.")
Note the parens.
To call this function, we would type:
test()
Now lets make this a little more complicated:
def test(x):
 print("Hello "+x)
We now have told python that this function requires one argument, which it should assign to the variable x.
Now if we do:
test()
We get a traceback.
This is because test, as we just defined, now wants an argument.
So lets give it one:
test("bob")
As you can see our output is Hello bob.
Functions can have as many arguments as you want and are separated by commas.
def test(first_name, last_name):
 print("Hello "+first_name+", "+last_name)
Lets create a function called test, with our variable of test from earlier and make a more practical example:
def test(x):
 n=0
 while(n5):
  return 1
 else:
  return 2
In this function, if we called test and pass it a number greater than 5, the function would return 1.
What about a practical example:
def cube(number):
 return number*number*number
cube(3)
returns 27, because 3 cubed is, indeed, 27.
Sweet!
Functions can get highly complex, but they are ultimately your best tool when making dynamic programs.
Disclaimer: My coding is not usually as bad as it is in the recording!
Lets do a final function:
def sum(l):
 total=0
 for x in l:
  total=total+x
 return total
The name makes this function pretty obvious, but from a code perspective, we can see that we will loop through the items in l, add them to a running total, and return it.
Lets test:
l=[1, 2, 3, 4, 5]
sum(l)
And as you can see, our result is returned.
We could also store this in a variable, like so:
t=sum(l)
print(t)
Have a play and see if you can write a function to calculate the average of a set of numbers.
One example in which you might use this in a game setting is to write a distance function to work out if your enemy is within range of your player, or vice versa.
functions like play, and distance, are what I like to call utility functions.
they're functions that I use in most of my projects and often find myself copying across.
I've run out of time for this tutorial, but I hope you've found it useful and are now coming up with all sorts of ideas that you can do in the python programming language.
This has been Nathan smith of Nathan Tech.

6: Dir and getting help

This tutorial covers how to google your problems, how to understand tracebacks, and when not to ask silly questions.
Download
code snippet:
import time
dir(time)
time.sleep(1)

Text transcript>
hello and welcome back it is I, Nathan smith of Nathan Tech back with yet another episode in the how to code in python tutorials.
In this tutorial we will be looking at ways to get help when you get stuck.
Lets recap:
the first half of the series is nearly complete, and you only have one more episode after this to listen to before I would personally say you're ready to develop anything you can imagine in python.
So what have we learnt?
We've found out what a variable is, how to define them, the if elif and else statements, all about loops, and, of course, functions!
We've learnt a lot of stuff.
I'm impressed.
Sometimes, that's not enough. Python is always expanding and code is always changing.
This tutorial therefore is about getting help.
Far too easy these days it is to write on a forum or mailig list and say here's the code, tell me why it is not working.
It is my job, in this episode, to help you avoid that and hopefully make it so you do not damage your reputation in the process.
Sometimes, most times, it's okay to ask for help. I personally am always willing to ask questions.
But there's a difference between asking for help, and asking for a job to be done for you, right?
I personally do not turn away someone who is seeking genuine help. that's what these tutorials are all about after all!
First of all, lets set up our python terminal.
Into this, we are going to type:
x="hello"
x=x+1.5
As you see, this brings up a traceback.
This is your first port of call.
What does it say?
Can not concatinate string and float objects.
What does this mean?
concatinate means to bring together, to join.
So, in other words, you can not join a string and a float together.
Pretty obvious.
we mucked up!
print(x)
ah. x is a string.
That makes sense!
x=x+str(1.5)
print(x)
hello1.5
Well done. You've just debugged your first error.
If you don't know what a traceback means, just google it. no seriously.
Type into google can not concatinate string and float objects, and you'll get what that means.
Modern technology.
Now, if you are using a module, though, and you don't know what it does, how do you figure this out?
I'll touch on precisely what a module is later, and how to use them so don't worry about that too much.
Usually, and yet again, Google. Most modules have help pages.
There is another method though.
the dir function is a built in function for python that will tell you all about an object or module.
Here is a code snippet:
import time
dir(time)
Woo! what a lot of spam!
This output tells you, in a nutshell, what you can do with this module.
for example, one of the things dir has told us is sleep.
Sleep is a function that will suspend your program for a certain amount of time.
It's a bit like the wait function in other languages.
We could call this with:
time.sleep(3)
That covers the dir command for now, we'll do a bit more expansion on that in the next tutorial.
I have, however, now given you all of the knowledge you need to find out the answers to 99 percent of errors you will ever encounter.
Obviously the main flaw with Google is knowing how to phrase your question.
Google is a fantastic resource and should be your 1st to 5th ports of call, however, don't hesitate to ask someone.
At the end of the day as long as you ask politely, remember to thank them, and show you have tried to resolve it on your own, I can't see why people would not want to help you.
I myself, in fact, am always available through the contact form of this website if you would like to reach out.
that concludes this shorter tutorial, of which there is only one left in this section for you to do and I hope you have enjoyed it as much as I have.
Until then, keep coding this has been Nathan smith of Nathan Tech.

7: Modules

The final in the series, this tutorial covers modules, the import command, the pip command, and an example of the time module.
Download
Code Snippet
import time
time.time()
time.ctime()
pip install clipboard
pip uninstall clipboard
import clipboard
clipboard.copy("hello")

Text transcript>
Hello there, it is I Nathan smith in the final tutorial of the learning to code in python tutorials.
After this tutorial is complete, you will be able to compitantly and with, hopefully great success, be able to code anything you like in python.
In this tutorial I will cover three topics:
1. errors.
2. Modules.
3. Files.
So lets get started.
I'm only going to teach you briefly about error catching, as it is easy to fall into the trap of just throwing error catchers around everything and having a very unstable program.
I will teach you a try and except code block.
What this does is you say to python, try to execute this code, and if an exception comes up, do this code.
Like so:
try:
 x=1
 x=x+"bob"
except:
 print("Something went wrong...")
This, instead of raising an error and tracebacking, python excepts anything that happens in the first code block, stops working on that and instead goes to the except block and executes the code there.
That's all I'm really willing to teach you on exceptions, but if you wish to read further into it, have a look at the following page:
https://docs.python.org/3/tutorial/errors.html

Topic 2: modules.
first, the think I want to get through to you about python is that python is an object orientated language.
this means everything in python is an object.
strings are objects.
Modules are objects, everything is an object.
think of your house.
Inside you have objects, fundamentally everything is an object.
Like a person for example.
A person is an object who would have information about number of arms, legs, eyes, their name, age, and so on.
In python, everything is an object like this.
Objects can contain literally anything.
You can have functions on an objects, you can have variables on an object.
Variables on objects are called properties.
for example, an object for a person would have properties of legs, arms, nose, eyes ETC.
You can make your own objects, but that's a bit above this tutorial.
Modules are a collection of objects. sometimes just one object, sometimes many.
You can store objects in files for editing or distribution, which is what a lot of python developers do!
Python comes with a lot of modules already, one of which we will use now.
Remember the time module from the previous tutorial?
import time
This makes all of the properties, and values, and functions that are in the time module available to your code.
What can this do?
time.ctime()
here, we have called a function called ctime(), which is on the time module.
time.time()
Exactly the same.
This function shows you Unix time.
You can install new modules using the pip command, which is in your terminal window.
We'll install pygame in part two of our tutorials.
You can also uninstall a module in this exact way:
pip install clipboard
pip uninstall clipboard
If you did install the clipboard, lets see what we can do with it using the dir function.
dir(clipboard)
Hey look, there's a copy and paste function!
clipboard.copy("Hello, how are you?")
Now, if you have a way to view your clipboard, you can see we have "Hello, how are you?" on our clipboard.
Pretty easy, pretty simple. bish, bash, bosh.
Finally lets talk about files.
Python has a file object.
Surprise!
the basic things you can do with a file are reading and writing.
First though, we have to open one up.
the open function takes two arguments:
1, the name of the file
2, the mode.
Mode can be any of the following:
w: write. This opens a blank file and writes to it.
wb: write binary. same as write, but writing in binary mode rather than text mode.
r: read, this opens a file for reading.
rb: read binary, same as read but reading in binary mode.
a: this appends to a file.
Here is an example of opening a file for writing:
f=open("test.txt", "w")
Lets now write something to this file, and then close it.
f.write("Hello.")
f.close()
As you can see, the write and close functions are part of the file object which open returned, and we stored in the variable f.
You can read this file, like so:
f=open("test.txt", "read")
text=f.read()
f.close()
print(text)
Remember f.read() will return the entire content of the file, so you will want to assign it to a variable.
there are many other things you can do with files, you can read about those here:
https://docs.python.org/3/c-api/file.html
And that's it!
I can teach you nothing more, you are a python developer.
Congratulations.
Ultimately, you no longer need my help.
We will, in part two of these tutorials, apply some of this knowledge but you really don't need me, and I am looking forward to finding out how you applied this knowledge and indeed to your feedback about these tutorials.
Thank you very much for listening.

Section 2: Applying.

In this section we will talk you through making a simple Guess the Numbers Audio game.
This section of the tutorial is specifically windows only.

8: Plan and concepts

In this tutorial, we will talk about the concepts you need to understand, and our plan. Download
Code Snippet
pip install pygame

Text transcript>
Hello and welcome. this is the second part of the learning to code in python tutorials by Nathan Tech.
I am Nathan smith the voice for these tutorials and I will be talking you through the upcoming episodes.
this is episode 1 in which I will talk about what we plan to do and a few key concepts you will need to understand.
In the first part of these tutorials you learnt things to know when coding in python specifically that includes functions, variables and loops.
Now what we intend to do is apply that knowledge in the form of making a game.
And before we start, I want to iterate that there are many, many ways to make a game. At the end of the day there are many genres of games, many styles of coding and the methods we are going to teach you here are just one of those.
So lets get started!
First, what are we going to make?
We are going to make a number guessing game, it's a great little one to start with, it's like the hello world of audio games.
It gets you familiar with a few functions, in the case of python you will use a few modules and such, and we're also going to touch on how to build your first graphical user interface.
Now, I fail to remember if we touched on this before, so I'm going to do a quick recap about graphical user interfaces.
Key concept 1:
what is a graphical user interface?
When programming, you may have noticed that python is done in the command line for windows, or terminal for mac.
In that regard, everything appears in that box, there is no key strokes, mouse clicks or pictures.
A graphical user interface is what it souns like, it's a screen that we, the users, interact with that has graphics. for our purposes of creating an audiogame, these graphics will be nothing more than a blank screen with a title.
However, in such things like video games the graphics could be a character on the screen, a map, or a little sprite.
Lets talk about the second key concept:
Now when I first heard of event loops I got rather scared.they sound truly complicated, but they're actually not!
In that regard, I'm going to teach you even loops how I understand them.
First, we know what a loop is.
It's a piece of code that gets executed over, and over, and over again.
Put simply, an event loop is a loop that checks for, and acts upon, events. an example of these events might be that the user has quit the program, IE, when you press alt f4.
This would generate a quit event, which the event loop then notices and closes the program.
It's that simple!
I am going to provide a very basic event loop function for the game that we are making, which can be found on the web page of the tutorial.
You may want to copy and paste that into your prefered text editor, I will talk you through it line by line in the next episode.
These episodes will vary in length based on their content, for example this one is noticeably shorter as it is only an introduction and key concepts.
Not all of the code we speak about in these episodes will be provided. this is because I want you to apply the knowledge I give you constructively, encouraging you to not just copy what I do, but think for yourself.
While I may talk through certain lines, they will not all be shown here, or in the code snippets.
To do this tutorial you will need python and pygame.
That is what we will use as our main module.
We'll cover importing that module, and the others we will use, in episode 2.
For now what I would like you to do is open up your prefered terminal, in windows this is done with windows r, then type cmd.
After this, simply type:
pip install pygame
I do not personally provide support for pygame, as I do not develop it, but it is a very commonly used library for creating games in general.
there is plenty of support on the web.
You'll get a lot of text about it downloading and installing, and once it is done, you're ready for episode 2. I'll see you there!

9: Getting set up

We crack on with some code in this tutorial, getting you familiar with how to import modules, as well as the event loop. Download
Code Snippet
import pygame
import time
import sys
from random import randint
import globals
def event_loop():
   for event in pygame.event.get():
    if event.type == pygame.QUIT:
      pygame.quit()
      sys.exit()
      return
    if (event.type==pygame.KEYDOWN):
     globals.keypress=event.key


Text transcript>
Hello and welcome to episode 2 of learning to code in python, the second half.
In this episode we're actually going to crack on and make a game!
I intend to talk you through the first of your utility functions and explain to you the modules we will be using.
Lets start there, with the modules and, perhaps, the layout of your folder.
Many game developers have their own folder structure and you indeed will form your own style.
For now, here's mine:
I have a folder called guess the numbers.
In this I have a sounds folder,
a file we'll talk about a little later,
and a game file. the game file is called game.py.
Remember python files must be of .py extension.
You may want to at this point, pause, and set up this structure.
I have put the sounds I am going to use in the sounds folder already, you may want to record some in preparation!
We'll go over sounds in two episodes time.
Lets open the game.py file in your favorite editor, for me, notepad.
the first line of our python game is:
import pygame
Pygame as previously discussed is probably our  biggest library or module that we will use in this tutorial.
Pygame contains lots of functions and objects for games including graphics, playing video, playing sounds, handling keystrokes, handling mice clicks and more.
It is, of course, not the only graphical user interface library out there.
There's wx python, which I use for software, there's tkinter, and more!
We will be using pygame for the simple reason it contains pretty much everything we need.
In that regard, it also contains the ability to play sound files like .ogg and .mp3.
I am using .ogg for this project, but whether you do is up to you.
What other modules will we be using?
First, the time module:
import time
You can use this to do various functions in time, like checking it, suspending your program which is called sleep and is what we will use in our game.
Next comes sys.
import sys
short for system, we will use this to quit the program.
Finally, we have random:
from random import randit
Note how this module is imported differently?
Instead of:
import something
WE've put
from something import something
this is because we only need one function.
As you can see, we are importing the randint function, which is the only function I want in this module.
Randint takes two arguments,
1, the low number
2, the high number.
If we passed it 1 and 6, it would choose between 1, 2, 3, 4, 5 and 6.
that's fine for this game, as we're only going to use the numbers 1 to 9.
Arguably, we could also do this for the time module:
from time import sleep
The difference between:
import time
and
from time import sleep
Other than the obvious thing is that if we want to call the sleep function, we must do it in a different way, like so:
import time
time.sleep(1)
or
from time import sleep
sleep(1)
I use quite a few of the time functions in my programs, so by habit I simply import time, but it is up to you what way you do it.
Just remember so that later on you use the correct call to sleep!
In terms of the random module, here are the two ways we could import it:
import random
number=random.randint(1, 9)
or
from random import randint
number=randint(1, 9)
See if you can figure out how to do this for the exit function of the sys module.
Finally, we have:
import globals
this is going back to that file I created earlier:
globals.py
I have created, basically, my own module.
Why on Earth have I done this?
In the globals.py file, I am going to put all our global variables.
At this point that is one variable:
keypress=0
Why have I done this?
Why not put it at the top of the file like a global variable?
quite simply, it's a best practice.
In python you can define a variable, and then redefine it later on.
If I had a global variable called chosen, for example, and then later redefined it, python would not throw an error and instead would carry on and break.
As a best practice, I therefore put global variables in another file, which I then use as a module.
That way, if I want to refer to the global variable called chosen, I'd do:
globals.chosen=1
While if I had a local in-function variable called chosen, I could just do 
chosen=1
With no fear of overwriting.
It also makes your code more readable, I thoroughly encourage you to get into this great habbit.
As promised the other thing I will talk about is the event loop.
there are many ways to do an event loop, and as I will reiterate again, this is my way.
It may not be your way, and you may find a better way to do it, but this is the way I do things.
So, here's how we're going to handle our event loops.
Because I want to avoid using threading, which is a big explanation and is quite dangerous as you can screw it up easily, we're going to essentially create our own event loop.
First, lets create the function that contains the event loop:
def event_loop():
As we are now within a function we must now indent.
I have provided the code for this loop in the snippets section, and the code is also below.
I will walk you through each line after this block of code.
def event_loop():
   for event in pygame.event.get():
    if event.type == pygame.QUIT:
      pygame.quit()
      sys.exit()
      return
    if (event.type==pygame.KEYDOWN):
     globals.keypress=event.key
Lets go through this line by line:
   for event in pygame.event.get():
Break it down, first, you have get().
This is calling a function on the event module, which is part of the pygame library.
Hence, pygame.event.get() is just a function call!
Simple!
then all we have is the for loops we saw in part one of these tutorials,
for element in list
For each item in that is returned by pygame.event.get(), assign to the variable called event, and do something with it.
See? You know this stuff!
Now remember, everything in python is an object. even the variable event is an object.
    if event.type == pygame.QUIT:
First, notice the capitals!
What are we doing here?
First, it is an if statement, if something is equal to something.
Second, we are refering to properties on an object, variables on an object.
We are saying if the type property of the event object is the same as the quit property of the pygame object.
that's all!
      pygame.quit()
Pretty obvious!
      sys.exit()
Exits our program completely.
      return
Stops execution of the loop and the function.
This may not necesasrily be needed, but I like to put it there just in case.
    if (event.type==pygame.KEYDOWN):
Another if statement.
Remember the one above?
this one does exactly the same!
     globals.keypress=event.key
this line simply stores the value of event.key, which is a property on the event object, onto our global variable in globals.keypress, which we'll need later on.
So what does this event loop do?
1. It checks for events.
2. It looks at each one and says is it a quit event? do this. Is it a keydown event? do this.
If it is none of these, I don't care.
congratulations, you have just written the most important part of your event loop.
We'll turn this into a loop later on but for now, that concludes this tutorial!
I look forward to seeing you in the next episode, where we'll talk about sounds and keystrokes.

10: Sounds and Keystrokes

We write our next two utility functions as well as talk about how to handle keystrokes and the playing of sounds.
We also talk about the sounds you will need for this game. Download
Code Snippet
def play(sound_name, channel, wait):
 sound_object=pygame.mixer.Sound(sound_name)
 pygame.mixer.Channel(channel).play(sound_object)
 if(wait==1):
  while(pygame.mixer.Channel(channel).get_busy()==True):
   event_loop()
   time.sleep(0.1)
def key_pressed(key):
 if(globals.keypress==0):
  return 0;
 if(globals.keypress==key):
  globals.keypress=0;  
  return 1;
 return 0;

Text transcript>
Hello and welcome to episode 3 of part 2 of the learning to code in python tutorials in which we are learning to make a guess the numbers game.
So far, we've touched upon some utility functions as well as some very interesting things about events.
Before we get down to brass tacks and do some coding, lets talk about sounds we'll need for this game.
I like to have a basic plan for projects I do, I may not always follow them, and sometimes I screw them up and throw them in the trash, but at least with a plan I have a basic idea of what I want.
With this game for example, here is a list of the sounds I came up with:
1. A voice saying 1 to 9
2. A voice saying higher or lower.
3. a voice saying play the game
4. a voice saying exit.
5. A win and a lose sound.
for most of these I just recorded myself saying the required text!
Were you releasing this game, you might want a voice section telling you how many guesses they have, and an introduction, or something similar.
they are the sounds we are going to need.
Lets talk about the function we're going to use to play these sounds.
Pygame comes with a built in way to play sounds, in fact there are a few ways! Depending on whether you want to play music, a single sound, multiple sounds and so on.
I am going to teach you how to use pygame.mixer. The mixer is an object of pygame, and so we access it through pygame.mixer.
the reason I chose this specific method is because it comes in useful when you want to play multiple sounds at once, which the mixer supports.
The way it does this is when you play a sound it assigns it to a channel. you start off with 8 channels, but you can change this if you look.
check out Google for how to do that.
Think of these channels like TV channels.
On channel 1, you might have a cheering croud.
On channel 2, you might have the booing croud.
While channel 1 is playing the cheer sound, if I then tell it to play the boo sound it would stop playing the cheer, assign boo to channel 1, and play it.
That's basically what you need to know for the mixer so far.
So, lets crack on!
The first utility function we are going to make, and one of the ones we will use the most, is the play function.
Remember we use utility functions to make it easier on us, the coders.
Because sure we could write the code out for playing a sound a million times, but why bother! Just write it into a function and call the function.
I've called my function play:
def play(sound_name, channel, wait):
1. Sound_name is the name of the file we want to play
2. channel is what channel we want it on,
3. Wait is whether we want to wait for the sound to complete or not.
Next line:
 sound_object=pygame.mixer.Sound(sound_name)
In this line, we create a sound object, which we assign to the variable name sound_object, because why not, right?
the sound object, a part of pygame.mixer, takes the argument of sound_name, which is the name of the file we want to play.
 pygame.mixer.Channel(channel).play(sound_object)
We have two things going on here, so lets break it down.
first we have:
  pygame.mixer.Channel(channel)
All this does is ask pygame to return the object associated with a channel, I.e the channel object.
If our channel variable was set to 1, it would return the channel 1 object.
then we have:
 .play(sound_object)
Pretty simple, on the channel object we asked for, we are calling it's play function, and giving it the sound we want it to play.Next line is an easy one:
 if(wait==1):
Do I need to explain this to you?
Lets move on.
  while(pygame.mixer.Channel(channel).get_busy()==True):
Remember to break it down to make it easier to understand.
What's familiar?
Well first, it's a while loop, so while something, execute some code.
We can also see we're asking pygame for the channel object, if channel variable was set to 1, we're asking it for the channel 1 object, and then we're calling the get_busy function.
In simple terms, we're asking, is channel 1 busy? If it is, do the code below!
   event_loop()
   time.sleep(0.1)
First, then, we have our call to event_loop to make sure our program continues to process events while it waits for the sound to finish and does not crash.
Then we call time.sleep, which suspends our program for a moment.
there are a few other ways you can write this function, Apply your knowledge and see if you can figure it out!
Note the capitalisation in the function calls, it's very important!
LEts say we want to stop playing the sound.
How would you go about doing this?
Channel 1 is playing our sound, so we're simply going to tell channel 1 to stop playing it.
See if you can figure out how to do it!
You can do many other things with the pygame mixer, just have a look at this website:
https://www.pygame.org/docs/ref/mixer.html
Lets talk about our second, other commonly used utility function which is nice and simple:
def key_pressed(key):
 if(globals.keypress==0):
  return 0;
 if(globals.keypress==key):
  globals.keypress=0;  
  return 1;
 return 0;
This function is really simple!
It's just a bunch of if statements.
First, is globals.keypress set to a key that has been pressed?
If not, return 0.
If it is set to something that was pressed, then, is it the one we're asking about?
If it is, return 1, otherwise, return 0.
In other words: Is the key the user just pressed, the one we want.
Is it key number 1? do this.
Is it left control? Shoot the gun, blow up the tutorial, end of story.
Can you see the two lines that don't actually need to be in this function?
Note the indentation for this function, otherwise the returns don't make sense!
So, final question: Why are we setting globals.keypress to 0 after we have identified that it is the key the user pressed?
Imagine the situation, you're in your game loop, and you press 1.
The game says, hey! He pressed 1, great! Lets play the cheer sound.
It does the rets of the loop, goes back to the top and says, hey. He still pressed 1! Lets play cheer again. And again. and again. and again.
So we set globals.keypress to 0 so that when the loop iterates again and asks, did he press 1? the computer says, not yet, and we only get one cheer sound.
that concludes this tutorial, and we only have one more on utility functions before we get into making the game itself.
I look forward to seeing you soon.
this was Nathan smith of Nathan Tech.

11: menu

We write our menu function. Download
Code Snippet
def menu(items):
 position=0
 while 1:
  event_loop()
  if(key_pressed(pygame.K_UP)):
   if(position>1):
    position=position-1
   play("sounds/"+items[position-1], 1, 0)
  if(key_pressed(pygame.K_RETURN)):
   return position

Text transcript>
Hello there and welcome to learning to code in python tutorials in which we are making a guess the numbers game.
I am, of course, Nathan smith of Nathan Tech and in this episode we are going to write your menu function.
LEts get stuck in straight away.
For this game, I am only writing a bare-bones menu function, for example, when I define it, I will only give it, as arguments, a list of sounds.
In a real situation, you may want to have arguments of the background music to play, the introduction sound of the menu, the list of sounds and so on.
For now though, lets simply define:
def menu(items):
This defines us a menu function, and puts our items into an items variable.
 position=1
now, you could set position equal to 0, which would make computer logic sense, or you could set it to 1, and adapt your code accordingly.
We are going to do the latter, simply to act as a recap about arrays.
 while 1:
Be extremely careful! While 1 is an infinite loop!
Do not define an infinite loop without also coding a way to get out of it.
Luckily, we will.
  event_loop()
this is pretty standard by now, we don't want our program crashing, after all.
  if(key_pressed(pygame.K_UP)):
Well, the first thing to note here, we have ourselves an if statement, lovely!
Next up, we're calling our key_pressed function, but what are we passing it? pygame.K_UP? What is this nonsense?
First, it's a variable on the pygame module.
K_UP, note the capitalisation, is the variable for the number that represents the up arrow key.
pygame.K_DOWN would be down arrow,
pygame.K_LEFT would be left.
pygame.K_1 for number 1.
Interestingly however, for alphabetical letters, like the letter a, the variable is:
pygame.K_a
So, in simple terms we're checking has up arrow been pressed.
   if(position>1):
Pretty simple, only do this code if our position variable is greater than 1.
    position=position-1
Decrease the variable position by 1 and then...
   play("sounds/"+items[position-1], 1, 0)
Break this one down to make it easier on yourself.
First you are calling the play function from the previous episode, which, if you remember takes the arguments of sound_name, channel, and wait.
We take 1 from the variable position because, in computer speak, items in an array start at 0. You do not need to do this if your position variable is 0!
We then want to obtain the item which is now selected, which we do through items[position]. It is a sound name, and our sounds are in our sounds folder.
Therefore any sounds we wish to play must first have sounds/ in front of them, to get to the correct path!
What we end up with, after the computer has done the work, is, as an example:
   play("sounds/play.ogg", 1, 0)
the 1 represents the channel we play the sound on, and the 0 represents that no, we do not want to wait until the sound is finished playing.
Of the code I have provided you, there are only two lines left:
  if(key_pressed(pygame.K_RETURN)):
   return position
the purpose of these, one assumes, are obvious:
if the enter key is pressed,
Return the value of the variable position.
Here's a little job for you!
Using the code above, see if you can figure out how to code the down arrow keystroke for your menu.
I have faith you can do it, good luck!
Once you have done that, you are officially ready to start coding the game itself!
I'll see you in the next episode, where we'll crack on straight away and get this thing done!
This has been Nathan smith of Nathan tech, see you soon!

12: The main menu

We write our main menu. Download
Code Snippet
def mainmenu():
 while 1:
  items=["play.ogg", "exit.ogg"]
  choice=menu(items)
  if(choice==1):
   game()
  else:
   pygame.display.quit()
   sys.exit()
   return

Text transcript>
Welcome back you guys, we're nearly there!
We've nearly made the game, isn't it exciting?
In this tutorial, which is a bit shorter than the rest, we're going to create the main menu function.
Originally I was going to put both the game and main menu function into one tutorial, but after long deliberation, at least 10 seconds! I decided to separate them up and spend more time on each.
So what can I tell you about main menu/
Well, it's a function, that is not taking arguments.
Do not argue with this guy.
def mainmenu():
Line 1, is while 1:
Be careful with these while loops, as discussed in the previous episode, they can break easily and bla bla bla. You're boring us, Nate. Move on!
Next up we form ourselves a nice array:
  items=["play.ogg", "exit.ogg"]
These are the sounds of our menu.
  choice=menu(items)
Hey look!
It's a call to that utility function we created, that's awesome!
  if(position==1):
   game()
  else:
   pygame.display.quit()
   sys.exit()
As there are only two items in this menu, we can get away with just an if and an else statement, but usually I do ifs and elifs.
Item 1, which is play the game, we launch the game function.
the other item, item 2, we quit the program.
   pygame.display.quit()
this line calls the close function on the display object of pygame.
Rather predictably in this regard, it shuts the window.
   sys.exit()
this closes out the program entirely.
In the code snippet, I have then put:
   return
this is not, strictly, necesary, but I put it there just in case.
It's up to you if you want to!
Now, you may be wondering, Why haven't you included our event_loop?
It's true.
You could, if you wanted to, but it's unnecessary.
After all, the only  things that will sit there for a while are the menu functions and the game functions.
menu already handles the event_loop, and so will game.
That's our main menu.
that's it!
Well done!
It's important to check your capitalisation and punctuation, but ultimately this is very simple.
thank you for listening, and I'm really excited to see you in the next episode!
This has been Nathan smith of Nathan Tech.

13: The game!

We write our game function, as well as another utility function! Download
Code Snippet
def game():
 chosen_number=randint(1, 9)
 globals.guesses=3
 while 1:
  if(key_pressed(pygame.K_1)):
   if(handle_number(1, chosen)==1):
    return
  if(key_pressed(pygame.K_ESCAPE)):
   return

Text transcript>
Hello again and welcome back, you're almost there.
WE have two episodes to go and then we are officially done!
This one is going to be the longest, not because it's complicated, simply because there's a lot to cover and because I have what you might call a teaching ethic.
I am not here to tell you how to do something.
I am here to teach you how to think your way through a problem.
I'm not going to give you sheets and sheets of code, I will simply give you examples of how things can be done, and expect you to apply that knowledge.
this, in my opinion, is the best way to learn.
So we're now going to code our game function.
This function will handle the playing of the game itself.
First of all, lets talk about this for a second, lets think about it.
What do we want it to do?
1. Choose a random number between 1 and 9.
2. Make the user guess that number.
Lets say our number is 3, and they enter 6. We also want to tell our user to go lower or go higher.
I'm thinking here, guys. A game where you just choose a number is pretty boring. After all, I could just do 1, 2, 4, 5, 6, 7, 8, 9, 3 and win every time.
Where's the fun in that?
That tells me we need to give the user 3 guesses.
We want to do:
has the user pressed the key?
Is it a number?
If it is, is it the correct one?
If so, do something,
if not, is it higher? If so tell user to go lower,
if not, tell them to go higher.
First things first we need to check okay, if(key_pressedKEY_1)),
is it number? Is it higher or lower?
if(key_pressed(KEY_2))
is it higher? is it lower? is it our number?
if(key_pressed(KEY_3))
is it higher? is it lower? is it our number?
Hold on a second! We're repeating ourselves!
time for a utility function guys.
This is why I say utility functions are very important.
I am not going to write this function, it's your turn.
I'll talk you through it, but I'm not giving you code.
Think first, what should this utility function do?
We want to be able to pass it a number and for it to:
1. Check is it our number? If so, do win sequence.
2. Is it higher than our number? If so tell user to go lower and increase guesses by 1.
3. Is it lower than our number? If so tell user to go higher and increase guesses by 1.
4. Has the user run out of guesses? Do the lose sequence.
There are several ways you can go about doing this, either through variables stored in our globals file, or through arguments given to the utility function.
However you do it is up to you!
Lets get on to writing our game function.
def game():
Pretty straight forward.
Now lets generate our random number.
Either you could do:
 number=randint(1, 9)
Or you could do:
 globals.number=randint(1, 9)
Remember randint takes two arguments, the lower number and the highest number.
Just remember, which ever method you choose to use you'll have to adjust your utility function accordingly!
Next up, lets reset the guesses.
 globals.guesses=0
Now we start our infinite loops, which remember we must be careful with, as long as we break out of it somewhere we will be fine!
 while 1:
  event_loop()
As you can see, we also have our call to event_loop which keeps everything running nice and smoothly.
  if(key_pressed(pygame.K_1)):
This is where things get interesting.
If our player has chosen the correct number, or if our player has lost the game we'll want this game function to stop.
The only quick and easy way to tell our game loop about this is by making our utility function return something.
For example, if our utility function returns 1, that means stop the loop, game over.
So that is why we have:
  if(key_pressed(pygame.K_1)):
   if(handle_number(1, chosen)==1):
    return
As you can see in my example I've chosen to pass what number the user chose, as well as what the number should be.
You'll want to repeat those lines for the keys 1 to 9.
There is one other keystroke that is very important, no matter what game you make.
Escape!
The escape key should just break the loop, exit the function and kick us back to our main menu.
  if(key_pressed(pygame.K_ESCAPE)):
   return
Note: There are other methods to writing this function out and if you come up with a better way, good on you! that means you're progressing nicely as a developer.
I've left it up to you how you want to handle retries and such, which I'm sure you have figured out yourself by now.
Tip: globals.guesses=0 is one method!
You may be wondering, why did we return rather than going to the main menu through a function call?
Have a look back at our code for the main menu.
It's a loop!
If we called main menu, we'd go from main menu to game to main menu to game to, Yawn.
That's it for this lesson and you can now move on to the final of this tutorial.
I hope you have found this lesson helpful and look forward to seeing you soon!
This was Nathan smith of Nathan Tech.

14: The main function.

We write our final function, the main function and tidy up to finish. Download
Code Snippet
def main():
 pygame.init()
 pygame.mixer.init()
 DISPLAYSURF = pygame.display.set_mode((400, 300))
 pygame.display.set_caption('Guess the Numbers. By Nathan Tech.')
 mainmenu()
main()

Text transcript>
Hello and welcome back to the final part of these tutorials.
I am, of course, Nathan smith of Nathan tech, if you can't recognise me by now, something has gone wrong!
By this point, you hopefully have a file, or set of files, that contain 99 percent of the work you need to have done to get your first python game off of the ground.
Hopefully you've been following along.
We only have one thing to do which is write our main function.
The main function is pretty straight forward, and you're welcome to just up and copy this from the tutorial if you like, but it is best to listen in so you know what each line does and you can make your own, less simple one, in the future.
Here goes!
def main():
We should know what this does by now.
 pygame.init()
This sets up the pygame module and gets it ready for use. A bit like giving pygame a cup of coffee. Yum. coffee.
 pygame.mixer.init()
this sets up the mixer for use. Check out that coffee, mixer!
 DISPLAYSURF = pygame.display.set_mode((400, 300))
This creates us a nice blank screen for our b=project.
 pygame.display.set_caption('Guess the Numbers. By Nathan Tech.')
This gives our screen a nice little title. Feel free to change that string to what ever you like. For example: "Nathan is amazing." or, "Thanks Nathan Tech for making these tutorials." or, if you were feeling really adventurous, "Guess the numbers game."
At this point it is worth noting you could draw your logo on the screen, draw a happy face, or do any other innicial graphics you want to do.
 mainmenu()
Ah, and here we have launched into our game. fantastic!
The final line of our file is to put a call in to the main function, launching the entire thing when the game is opened.
main()
Now, there is another method of writing the main function which relates to creating modules that can also function as products.
There is a brilliant explanation to this which goes into detail a lot better than I could ever do, though I have done in the voiced tutorial.
Check it out here:
https://stackoverflow.com/questions/419163/what-does-if-name-main-do
And that concludes this series. It feels like the end of an era, or perhaps, the end of a prison sentence...
Just kidding!
I hope you found these ramblings useful and will now go and create great things with your python coding knowledge.
Just remember me when you make the big buks!
This has been Nathan smith of Nathan tech.
Thank you for listening.