Tuesday, June 9, 2009

Python - Loops - IV

Introduction

(Our final lesson before we get into interacting with human input. Can't wait, can you?)

Just imagine you needed a program to do something 20 times. What would you do? You could copy and paste the code 20 times, and have a virtually unreadable program, not to mention slow and pointless. Or, you could tell the computer to repeat a bit of code between point A and point B, until the time comes that you need it to stop. Such a thing is called a loop.

The 'while' loop

The following are examples of a type of loop, called the 'while' loop:

Code Example 1 - The while loop
a = 0
while a < 10:
a = a + 1
print a

How does this program work? Lets go through it in English:

Code Example 2 - plain-language while loop
'a' now equals 0
As long as 'a' is less than 10, do the following:
Make 'a' one larger than what it already is.
print on-screen what 'a' is now worth.

What does this do? Lets go through what the computer would be 'thinking' when it is in the 'while' loop:

Code Example 3 - while loop process
#JUST GLANCE OVER THIS QUICKLY
#(It looks fancy, but is really simple)
Is 'a' less than 10? YES (its 0)
Make 'a' one larger (now 1)
print on-screen what 'a' is (1)

Is 'a' less than 10? YES (its 1)
Make 'a' one larger (now 2)
print on-screen what 'a' is (2)

Is 'a' less than 10? YES (its 2)
Make 'a' one larger (now 3)
print on-screen what 'a' is (3)

Is 'a' less than 10? YES (its 3)
Make 'a' one larger (now 4)
print on-screen what 'a' is (4)

Is 'a' less than 10? YES (its 4)
Make 'a' one larger (now 5)
print on-screen what 'a' is (5)

Is 'a' less than 10? YES (its 5)
Make 'a' one larger (now 6)
print on-screen what 'a' is (6)

Is 'a' less than 10? YES (its 6)
Make 'a' one larger (now 7)
print on-screen what 'a' is (7)

Is 'a' less than 10? YES (are you still here?)
Make 'a' one larger (now 8)
print on-screen what 'a' is (8)

Is 'a' less than 10? YES (its 8)
Make 'a' one larger (now 9)
print on-screen what 'a' is (9)

Is 'a' less than 10? YES (its 9)
Make 'a' one larger (now 10)
print on-screen what 'a' is (10)

Is 'a' less than 10? NO (its 10, therefore isn't less than 10)
Don't do the loop
There's no code left to do, so the program ends

So in short, try to think of it that way when you write 'while' loops. This is how you write them, by the way (and a couple of examples:

Code Example 4 - while loop form, and example
while {condition that the loop continues}:
{what to do in the loop}
{have it indented, usually four spaces}
{the code here is not looped}
{because it isn't indented}

#EXAMPLE
#Type this in, see what it does
x = 10
while x != 0:
print x
x = x - 1
print "wow, we've counted x down, and now it equals", x
print "And now the loop has ended."

Remember, to make a program, you open IDLE, click File > New Window, type your program in the new window, then press F5 to run.

Boolean Expressions (Boolean... what?!?)

What do you type in the area marked {conditions that the loop continues}? The answer is a boolean expression.

What? A forgotten concept for the non-math people here. Never mind, boolean expression just means a question that can be answered with a TRUE or FALSE response. For example, if you wanted to say your age is the same as the person next to you, you would type:

My age == the age of the person next to me

And the statement would be TRUE. If you were younger than the person opposite, you'd say:

My age <>

And the statement would be TRUE. If, however, you were to say the following, and the person opposite of you was younger than you:

My age <>

The statement would be FALSE - the truth is that it is the other way around. This is how a loop thinks - if the expression is true, keep looping. If it is false, don't loop. With this in mind, lets have a look at the operators (symbols that represent an action) that are involved in boolean expressions:

Table 1 - Boolean operators
Expression Function
< less than
<= less that or equal to
> greater than
>= greater than or equal to
!= not equal to
<> not equal to (alternate)
== equal to

Dont get '=' and '==' mixed up - the '=' operator makes what is on the left equal to what is on the right. the '==' operator says whether the thing on the left is the same as what is on the right, and returns true or false.

Conditional Statements

OK! We've (hopefully) covered 'while' loops. Now let's look at something a little different - conditionals.

Conditionals are where a section of code is only run if certain conditions are met. This is similar to the 'while' loop you just wrote, which only runs when x doesn't equal 0. However, Conditionals are only run once. The most common conditional in any program language, is the 'if' statement. Here is how it works:

Code Example 5 - if statement and example
if {conditions to be met}:
{do this}
{and this}
{and this}
{but this happens regardless}
{because it isn't indented}

#EXAMPLE 1
y = 1
if y == 1:
print "y still equals 1, I was just checking"

#EXAMPLE 2
print "We will show the even numbers up to 20"
n = 1
while n <= 20:
if n % 2 == 0:
print n
n = n + 1
print "there, done."

Example 2 there looks tricky. But all we have done is run an 'if' statement every time the 'while' loop runs. Remember that the % just means the remainder from a division - just checking that there is nothing left over if the number is divided by two - showing it is even. If it is even, it prints what 'n' is.

'else' and 'elif' - When it Ain't True

There are many ways you can use the 'if' statement, do deal with situations where your boolean expression ends up FALSE. They are 'else' and 'elif'.

'else' simply tells the computer what to do if the conditions of 'if' arent met. For example, read the following:

Code Example 6 - the else statement
a = 1
if a > 5:
print "This shouldn't happen."
else:
print "This should happen."

'a' is not greater than five, therefore what is under 'else' is done.

'elif' is just a shortened way of saying 'else if'. When the 'if' statement fails to be true, 'elif' will do what is under it IF the conditions are met. For example:

Code Example 7 - The elif statement
z = 4
if z > 70:
print "Something is very wrong"
elif z < 7:
print "This is normal"

The 'if' statement, along with 'else' and 'elif' follow this form:

Code Example 8 - the complete if syntax
if {conditions}:
{run this code}
elif {conditions}:
{run this code}
elif {conditions}:
{run this code}
else:
{run this code}

#You can have as many or as little elif statements as you need
#anywhere from zero to the sky.
#You can have at most one else statement
#and only after all other ifs and elifs.

One of the most important points to remember is that you MUST have a colon : at the end of every line with an 'if', 'elif', 'else' or 'while' in it. I forgot that, and as a result a stack of people got stumped at this lesson (sorry ;) ).

Indentation

One other point is that the code to be executed if the conditions are met, MUST BE INDENTED. That means that if you want to loop the next five lines with a 'while' loop, you must put a set number of spaces at the beginning of each of the next five lines. This is good programming practice in any language, but python requires that you do it. Here is an example of both of the above points:

Code Example 9 - Indentation
a = 10
while a > 0:
print a
if a > 5:
print "Big number!"
elif a % 2 != 0:
print "This is an odd number"
print "It isn't greater than five, either"
else:
print "this number isn't greater than 5"
print "nor is it odd"
print "feeling special?"
a = a - 1
print "we just made 'a' one less than what it was!"
print "and unless a is not greater than 0, we'll do the loop again."
print "well, it seems as if 'a' is now no bigger than 0!"
print "the loop is now over, and without furthur adue, so is this program!"

Notice the three levels of indents there:

  1. Each line in the first level starts with no spaces. It is the main program, and will always execute.
  2. Each line in the second level starts with four spaces. When there is an 'if' or loop on the first level, everything on the second level after that will be looped/'ifed', until a new line starts back on the first level again.
  3. Each line in the third level starts with eight spaces. When there is an 'if' or loop on the second level, everything on the third level after that will be looped/'ifed', until a new line starts back on the second level again.
  4. This goes on infinitely, until the person writing the program has an internal brain explosion, and cannot understand anything he/she has written.

There is another loop, called the 'for' loop, but we will cover that in a later lesson, after we have learnt about lists.

Monday, June 8, 2009

Python - Programs in a file, and variables - III

Introduction

Well, we can make one-liner programs. So What? You want to send programs to other people, so that they can use them, without knowing how to write them.

Editing in Notepad

Writing programs in python to a file is VERY easy. Python programs are simply text documents - you can open them up in notepad, and have a look at them, just like that. So, go and open notepad. Type the following:

Code Example 1 - mary.py
#A simple program.
print "Mary had a little lamb,"
print "it's fleece was white as snow;"
print "and everywhere that Mary went",
print "her lamb was sure to go."

Keep this exactly the same, down to where the commas are placed. Save the file as 'mary.py' - and make sure notepad doesn't add .txt to the end of the filename - You will have to tell it to save as any file, to avoid this. Turn off 'Hide known file extensions' in Windows Explorer, if it makes it easier.

Using the IDLE Environment

Now, open up the Python IDLE program (should be in your start menu). Click 'File > Open' and find mary.py and open it. if you cant find mary.py, set the open dialogue to 'Files of type: All Files (*)'. A new window will open, showing the program you just wrote. To run your program, click 'Run>Run Module' (or just press F5). Your program will now run in the main Python screen (Titled *Python Shell*) and will look like this:

Code Example 2 - mary.py output
Mary had a little lamb,
it's fleece was white as snow;
and everywhere that Mary went her lamb was sure to go.

You can also use IDLE to create Python programs, like what you did in notepad. Simply click 'File > New'. We will be writing all of our programs now in the python IDLE program - the notepad thing is just a demonstration to tell you that a .py file is just a simple text file, which anyone can see.

There are a couple of things to notice here:

  • First of all, the comment wasn't shown. That is good, because remember - comments aren't compiled. (try compiling it after removing the # - it comes out messy)
  • Second, is that the 3rd and 4th line got joined. This is because there is a comma just outside the inverted commas that surround the text. In the 'print' command, this stops the program from starting a new line on the screen when showing text.
  • You can also run the program from your command line program (e.g. MSDOS) - Open the prompt up, type 'cd path\to\your\file' then type 'python mary.py'. Your program will now execute in the command line.

Variables

Now lets start introducing variables. Variables store a value, that can be looked at or changed at a later time. Let's make a program that uses variables. Open up IDLE, click 'File>New Window' - a new window now appears, and it is easy to type in programs. Type the following (or just copy and paste - just read very carefully, and compare the code to the output that the program will make):

Code Example 3 - Variables
#variables demonstrated
print "This program is a demo of variables"
v = 1
print "The value of v is now", v
v = v + 1
print "v now equals itself plus one, making it worth", v
v = 51
print "v can store any numerical value, to be used elsewhere."
print "for example, in a sentence. v is now worth", v
print "v times 5 equals", v*5
print "but v still only remains", v
print "to make v five times bigger, you would have to type v = v * 5"
v = v * 5
print "there you go, now v equals", v, "and not", v / 5

Strings

As you can see, variables store values, for use at a later time. You can change them at any time. You can put in more than numbers, though. Variables can hold things like text. A variable that holds text is called a string. Try this program:

Code Example 4 - Strings
#giving variables text, and adding text.
word1 = "Good"
word2 = "Morning"
word3 = "to you too!"
print word1, word2
sentence = word1 + " " + word2 + " " +word3
print sentence

The output will be:

Code Example 5 - String output
Good Morning
Good Morning to you too!

As you see, the variables above were holding text. Variable names can also be longer than one letter - here, we had word1, word2, and word3. As you can also see, strings can be added together to make longer words or sentences. However, it doesn't add spaces in between the words - hence me putting in the " " things (there is one space between those).



Bookmark and Share

Sunday, June 7, 2009

Python - Very simple 'programs' - II

Very simple 'programs'

Introduction

OK! We have python installed, now what? Well, we program!

And it is that simple (at least for now). Python makes it easy to run single lines of code - one-liner programs. Lets give it a go.

Opening IDLE

Go to the start menu, find Python, and run the program labelled 'IDLE' (Stands for Integrated Development Environment.

Now you are in the IDLE environment. This is the place you will be spending most time in. Here you can open a new window to write a program, or you can simply mess around with single lines of code, which is what we are going to do. Type the following and press enter: (don't type >>> as it should already be there)

Code Example 1 - Hello, World!
>>> print "Hello, World!"

What happened? You just created a program, that prints the words 'Hello, World'. The IDLE environment that you are in immediately compiles whatever you have typed in. This is useful for testing things, e.g. define a few variables, and then test to see if a certain line will work. That will come in a later lesson, though.

Math in Python

Now try typing the stuff in bold. You should get the output shown in blue. I've given explainations in brackets.

Code Example 2 - Maths
>>> 1 + 1
2

>>> 20+80
100
>>> 18294+449566
467860
(These are additions)
>>> 6-5
1
(Subtraction)
>>> 2*5
10
(Multiply, rabbits!)
>>> 5**2
25
(Exponentials e.g. this one is 5 squared)

>>> print "1 + 2 is an addition"
1 + 2 is an addition
(the print statement, which writes something onscreen)
>>> print "one kilobyte is 2^10 bytes, or", 2**10, "bytes"
one kilobyte is 2^10 bytes, or 1024 bytes
(you can print sums and variables in a sentence.
The commas seperating each section are a way of
seperating clearly different things that you are printing)

>>> 21/3
7
>>> 23/3
7
>>> 23.0/3.0
7.6666...
(division, 2nd time ignoring remainder/decimals,
3rd time including decimals)
>>> 23%3
2
>>> 49%10
9
(the remainder from a division)

As you see, there is the code, then the result of that code. I then explain them in brackets. These are the basic commands of python, and what they do. Here is a table to clarify them (because tables look cool, and make you feel smarter ;) ):

Table 1 - Python operators
command name example output
+ Addition 4+5 9
- Subtraction 8-5 3
* Multiplication 4*5 20
/ Division 19/3 6
% Remainder 19%3 5
** Exponent 2**4 16

Remember that thing called order of operation that they taught in maths? Well, it applies in python, too. Here it is, if you need reminding:

  1. parentheses ()
  2. exponents **
  3. multiplication *, division \, and remainder %
  4. addition + and subtraction -

Order of Operations

Here are some examples that you might want to try, if you're rusty on this:

Code Example 3 - Order of Operations
>>> 1 + 2 * 3
7
>>> (1 + 2) * 3
9

In the first example, the computer calculates 2 * 3 first, then adds 1 to it. This is because multiplication has the higher priority (at 3) and addition is below that (at lowly 4).

In the second example, the computer calculates 1 + 2 first, then multiplies it by 3. This is because parentheses (brackets, like the ones that are surrounding this interluding text ;) ) have the higher priority (at 1) and addition comes in later than that.

Also remember that the math is calculated from left to right, UNLESS you put in parentheses. The innermost parentheses are calculated first. Watch these examples:

Code Example 4 - Parentheses
>>> 4 - 40 - 3
-39
>>> 4 - (40 - 3)
-33

In the first example, 4 -40 is calculated,then - 3 is done.

In the second example, 40 - 3 is calculated, then it is subtracted from 4.

Comments, Please

The final thing you'll need to know to move on to multi-line programs is the comment. Type the following (and yes, the output is shown):

Code Example 5 - comments
>>> #I am a comment. Fear my wrath!

>>>

A comment is a piece of code that is not run. In python, you make something a comment by putting a hash in front of it. A hash comments everything after it in the line, and nothing before it. So you could type this:

Code Example 6 - comment examples
>>> print "food is very nice" #eat me

food is very nice

(a normal output, without the smutty comment,
thankyou very much)

>>># print "food is very nice"

(nothing happens, because the code was after a comment)

>>> print "food is very nice" eat me

(you'll get a fairly harmless error message,
because you didn't put your comment after a hash)

Comments are important for adding necessary information for another programmer to read, but not the computer. For example, an explanation of a section of code, saying what it does, or what is wrong with it. You can also comment bits of code by putting a # in front of it - if you don't want it to compile, but cant delete it because you might need it later.


Bookmark and Share

Thursday, June 4, 2009

The Python Tutorial - Introduction - I

Python is an interpreted programming language. For those who don't know, a programming language is what you write down to tell a computer what to do. However, the computer doesn't read the language directly - there are hundreds of programming languages, and it couldn't understand them all. So, when someone writes a program, they will write it in their language of choice, and then compile it - that is, turn it in to lots of 0s and 1s, that the computer can easily and quickly understand. A windows program that you buy is already compiled for windows - if you opened the program file up, you'd just get a mass of weird characters and rectangles. Give it a go - find a small windows program, and open it up in notepad or wordpad. See what garbled mess you get.

But that windows program is compiled for windows - no other machine can run that program, unless it has windows. What Python is, is a language which is never actually compiled in full - instead, an interpreter turns each line of code into 0s and 1s that your computer can understand this. And it is done on the fly - it compiles the bits of the program you are using as you are using them. If you were to quit the program and come back another day, it would compile the bits you are using, as you are using them, again. Seems a waste of time? Maybe, but the fact is that when you come back another day, you might be using a Windows instead of a Mac. You might send the program to a friend, who uses another type of computer. Or you might post your program on the internet, where everyone using all different types of systems might download it. That is the wonder of an interpreted programming language - it is like a language that EVERYONE can understand.

How to install python

  1. First download Python-2.4.1.exe by following this link. If you are a dialup user, keep in mind that the file is around 10MB
  2. Run the file you just downloaded, and follow the prompts.

OK! Hopefully now everything is good! Now, to test if that just worked, type this in your DOS window:

Code Example 1 - Testing the installation
python -V

If you forgot a CAPITAL V, you will accidental load python in verbose mode. Give it a go, see what happens. Just press CTRL-D to quit, or type 'quit' for quit instructions.



Bookmark and Share