Site Index Intro Learning to Program Python Programs Tutorials Links

Links

Various links that should aid you in your quest of beeing a programmer

<PYTHON>

<INTRO>
First thing first, when starting to program without having any glue, about anything, some fundamentals should properly be explained. Computers only think in numbers, and was never really built for word-processing. Therefore when you write a program you will need to clarify what kind of object (a number or text and more) you are dealing with. This might sound tedious or even tough, but python is very helpful with this e.g. when you want to clarify that what you are typing is text you simply need to enclose your sentence with quotes, like this: "Hello everybody, I am a text object!". As stated python has an interactive prompt which is good for testing.
<text>
So open up python and enclose a sentence with quotes (these can be either single quotes ['] or double qoutes ["] but remember Python notices the kind of quote you start with and the next one like it ends the sentence). If you are unsure of what to write, then let me tell you that there is some long tradition whereby the first program you make displays 'Hello World!'. You might notice that on the next line where the sentence gets displayed, that it's enclosed with a set of single-quotes, this is because you never really told python what to do with it, you just created an object and python returned it so you could see it (this only happens in the interactive python prompt). Normally you would want to display a sentence, in python this is done by typing print (in lower case) in front of what you want displayed. So lets try that.

>>> print "Hello world!"
Hello world!
If you did this you would notice that the single-quote signs did not appear this time. Text like this is called strings in programming, so that is what we will call it from here on end.
</text>
<numbers>
As stated earlier computers were made with the intension of number crunching, so they are very good with numbers, and thus python is also very good at calculating numbers. Before we get to that though, it is a bit important to realise that there are different kinds of numbers! Since computers see everything in 1's and 0's they do not handle decimal values very well, so when handling decimal numbers this again needs to be specified to the computer. Again in python this is really simple, as python will automatically detect it! Now the reason for me to go over this is when python detects if the number is a decimal or not, by it self, is because YOU need to be aware of it e.g. if you want to divide 5 with 2, then everybody (hopefully) knows this to be 2.5. However Python valuate both numbers to be integers so it will only return an integer back as a result! Lets try (in the interactive prompt):

>>> 5/2
2
The reason the result is 2 and not 3 (normally 2.5 would be rounded up) is for the same reason when you started dividing in 3 grade (guess!) is the closest result is 5/2 = 2 with a remainder of 1(that's how I started learning division, at least).
As I said before Python automatically detects decimal numbers, so if you were to calculate a simple division like this one you should specify at least one of the numbers as a decimal:

>>> 5.0/2
2.5
As you can see we add a point zero [.0] to 5 so it becomes 5.0, this makes Python aware that we are using decimal numbers, but because it cannot divide (or multiply or... compute) two different kinds of objects, it than changes the 2 to 2.0 (this is done automatically). This is called widening.

Decimal numbers are in computer terminology called floats, short for floating numbers, and whole numbers are called integers. Thus from now on I will too :-).

There is one more kind of number. Complex numbers are also supported by Python I do not know much about these so I'll leave you to experiment... One thing to point out is that python uses j or J as the imaginary number. If I'm not mistaken i or I is the traditional mathematical way of describing the imaginary number, but not so in python. I shall give a little example to complex numbers anyway.

>>> import cmath
>>> cmath.sqrt(-9)
3j
>>> 3J**2
(-9+0j)
>>> 3i**2
SyntaxError: invalid syntax
In the example I just show that you cannot use i on the last line, and also if you want to work with complex numbers you should import the cmath module as I did on the first line.
</numbers>
<list; tuples>
A list... hmm? Hmm, it's hard to describe. What is a list to you? Well to me a list is simply a list of things, e.g. a wish list. A list contains a lot of things and maybe even more lists! For example in your wish list for Christmas you might say you want: a bike, a Nintendo, and also the stuff on your birthday wish list. See in a list there can be another list, the same goes for a programming list, where you can put in both strings and integers and lists and more integers etc. etc. you clarify a list by embracing the contents with square brackets [ [] ]. Let's try to make a list:

>>> ["this is a string", 'that --> is a number', 5, []]
['this is a string', 'that --> is a number', 5, []]
As you can see not much change here, but just to clarify it: First we have the this-string then the that-string, 5 and finally we have a list and just to show it, a list can be empty. In programming-speak we start counting with zero, so to the objects within our list are called the zero'th (0'th), the first, second, third, fourth, etc. if that makes sense. For now it's not really that important, but soon, you will need to pick out the individual values. I'll get back to clarify this though.

A tuple is more or less the same as a list, but the objects inside the tuple cannot be changed, this is what is called immutable. In a list it is done easily, but we'll get back to this when we get to variables.
A tuple is made with parenthesis [( )]
</lists; tuples>
<variables>
Now that we have covered the basic objects its time to make them useful, we do this by introducing variables. Variables are much what they sound like: Something that changes, i.e. you change them. It is a reference to an assigned object. This might sound more difficult then it actually is, and is properly best described with an example:

>>> a = "Hello World!"
>>> a
'Hello world!'
>>> print a
Hello world!
As can be seen when 'a' is assigned (using an equal-sign [=]) to the string 'Hello World!" it works much like the string we tried above, in that when we just type 'a' and press Enter Python returns the object and if we write 'print a', Python displays the sentence without any quotes.

You could say that you are storing an object in a variable. And you can use all kind of objects, but there are a few reservations on what you variable name can be, for starters it cannot be numbers as numbers by themselves are objects. A variable's name must start with a letter (a, b, c... z) or an under score [_], after that you can use both letters, underscores and numbers [0, 1, 2...9], and can be any length you desire (I think; at least they can be quite long). A general use of thumb is to keep the variable name short yet descriptive. One thing to note is that Python is case sensitive so a ≠ A and vice versa. Generally you should just keep to lower case to stay out of trouble.

When you assign numbers to variable you can just use the variable name if you want to calculate them, as the variables work just like the number it is assigned to:

>>> five = 5
>>> two = 2
>>> print five * two
10
>>> five * 5
25
No problems there. Variables are changed easily as well or if you want to can be deleted:

>>> a = 6
>>> print a
6
>>> a = "Hi there"
>>> print a
Hi there
>>> del(a)
>>> print a
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in ?
    print a
NameError: name 'a' is not defined
After 'a' was deleted we tried to print it anyway, but Python could not find the variable 'a' so therefore it tells us that some thing is wrong by giving us a traceback of what Python believes is the mistake and from the last line we must admit that it is correct.

Now lets move back to the lists, as I said it was very easy to change one of the lists objects, let me show you:

>>> lst = ["hello World!", 25, 6.7]
>>> print lst
["hello World!", 25, 6.7]
>>> lst[2] = 6
>>> print lst
["hello World!", 25, 6]
What I did here, was to assign a list to 'lst', but I wanted the last object to be 6 instead of 6.7, so I needed to count though the list (and remember what I said about counting from 0), the first object 'hello World!" is the 0'th, the second object '25' is the 1'st and the third '6.7' is 2'nd. Therefore when I need to change the 6.7 I need to specify that it is in the 2'nd position, by writing the variable name with a set of square brackets with the position of the object inside, i.e. lst[2] and then assigning the new object to this location.

<Indexing>
Actually that way of writing variable names with the square brackets can be used all the other objects we have covered until now, well except numbers. It is called indexing and is pretty standard, once you get to grips with it. However it's not as flexible as it is with list, but just to give an example:

>>> x = "Hello"
>>> print x[0]
H
>>> print x[-1]
o
>>> print x[4]
o
>>> print x[5]
Traceback (most recent call last):
  File "<pyshell#44>", line 1, in ?
    print x[5]
IndexError: string index out of range
Here I just show how it works for strings x[0] is the first position of the string so the first letter 'H' is printed. In the second example I play around a bit as I want to print the minus first position of the string, which is a clever way of printing the last letter, likewise I could have typed -5 which in this example would print the first letter, finally I show what happens if you use a to high number.
All this indexing might be a bit tough to comprehend, but I guarantee that once you find a use for it you will learn instantly, so you should play around with it. I will try to make up some exercises about it later.
</Indexing></varables>
This has been an introduction to the fundamentals. But now we should move on to some real(er) programming. This means we need to make choices depending upon the situation (or given values).
</INTRO>
<CONTROL FLOW>
For some more advanced things we need to make branches off in different directions. In other words we need to give the user choices and then depending on that do the things the user wants to do. For now when we are making a program Python reads through our script line by line until it reaches the end and then it quits. But depending on what the user wants done we might not want Python to read all our code.
<if; elif; else>
Now there are three different commands that you will have to use in order to do that, these are: if, elif and else. They work like this: Let us say for example that we are making a program that calculates an area of a given shape, then we would have the user select the shape he wants calculated. So >if< the user wants to calculate a square our program should go in that direction.

The following examples should be typed into a new window from the file menu in IDLE
When making a program like that we would need to present a menu for the user this we could by making a bunch of print statements:

print "Shape 1: Square"
print "Shape 2: Rectangle"
print "Shape 3: Triangle"
shape = input("Type the number of the shape to calculate: ")

if shape == 1:
    side = input("What is the length of any side? ")
    print side**2

elif shape == 2:
    length = input("What is the length? ")
    width = input("What is the width? ")
    print length * width

elif shape == 3:
    height = input("What is the height? ")
    width = input("What is the width? ")
    print 0.5 * height * width
Ok so I introduced something new here all of a sudden, input(), if you have not guessed it input() is what lets Python know what the user wants to do, notice that we assign that value to a variable that is called 'shape'. input() only works with numbers if you in the future want the user to enter a string you should use raw_input(). When getting input from the user you need to use those parenthesis', as I have typed a couple of times now, even if you do not make use of the prompt. Inside them you can type a prompt, which is something that tells the user what he should do. In our case we used this string: "Type the number of the shape to calculate: ". Users input is typed right at the end of the prompt that is why I put a space between the colon [:] and the quote ["], (it looks better that way).

This above example might be a little big, but as it is mostly made up of repeating code I let it slip by.
The first three lines are simple print statements, followed by the input() line, which is covered above, and then there is the if lines. First of all notice that there is two equal signs next two each other, this is actually Python-speak for an equal sign (one equal sign in Python is used for assignment, remember).

So what we need to do is evaluate what our variable shape is (we asked the user to enter 1, 2 or 3). So >if< the user types '1' we know that the shape he wants to calculate is a square, etc.

Notice the lines like this one:    if shape == 1:
What would say it means? It should be obvious, as it is just like English, 'if' is a statement that Python recognises the meaning of, 'shape' is a variable that the user define, '==' means equal, so that if 'shape' equals 1, and the colon specifies that you want Python to look at the indented lines below. Actually the colon is a clever syntax now that I describe it this way, try to look at my writing style. Almost all the time I make an example code, I use a colon the same way. I just realised that now. However when I do it in writing you as the reader need to guess when my example ends. You need to specify it clearly when you are programming, though. In most programming languages this is done by using parenthesis' or specific statements (like 'BEGIN' 'END' or similar). Python however wants you to indent the paragraph.

Python also needs to know what you are testing, it needs to know if you are still trying to figure out what shape is or if you have moved on to something else. That is why you need to use 'if' for the first test, and 'elif' for all the other values 'shape' might have.
This last thing might sound strange as if do try to make the same program using only 'if' statements instead of elif it will still work, but that is because the script is so simple, when doing more advanced things you might get some conflicts and strange behaviour from your program. I will try to make an example of this later on.

What about 'else' I hear you mutter, well else is different; it needs to be the placed after if or any elif's you have been using. You do not need to do any testing when using an else, because it covers all things you have not tested for.

>>> if 1 == 2:
        print "And pigs fly!"
else:
        print "No.. Not really!"

No.. Not really!
Here we make a test to see if 1 equals 2, well 1 is not the same as 2 and pigs don't fly, and since that makes no sense, and 'else' represents all other possibilities Python prints the No... Not really line. You could just as well have used an elif statement, like this one:

>>> if 1 == 2:
        print "And pigs fly!"
elif 1 == 1:
        print "No.. Not really!"

No.. Not really!
Therefore I prefer to use an else statement only in case the user presses a wrong key, e.g. in the shape calculation above, the user types 8, the program just ends. Without any reason why, because Python just looks through the options and because it says nothing about shape being 8, Python just continues to the next agenda, which is nothing in this example!
So you could add these lines:

else:
    print "The number you have typed does not match (1,2,3)"
    print "You entered:", shape
So know the user would at least know why nothing happened, instead of just scratching his head and think the software is buggy.
Also I think I did something new just now, in the second print line; notice that I make a string and use a comma, this is a way to let python know you want more on the line. I want shape next to the string to show the user what he entered, which is the variable shape. The comma makes a space on the line so you do not need to make a space in the end of the string. You cannot use several commas next to each other, if you need a certain space you will need to make extra strings e.g. just do this: print "Hello", "", "you" (for a double space).
</if; elif; else>
<loops>
Well up until now it's been rather straightforward, however I have been pretty confused about loops, especially while loops. And for-loops seemed to restrictive to do anything meaningful with, but I persevered. I have since learned to use them but here is my advice: Do lots of exercises with loops, and suddenly they are so simple.
For now let me just introduce them one at a time.
<for-loop>
The for-loops will loop through a given sequence and do what you want it to do with every item in that sequence. You execute a while loop like this:

>>> a = "hello world!"
>>> for item in a:
        print item


h
e
l
l
o
 
w
o
r
l
d
!
In this example the sequence is a string ('hello world!') so when we write 'for item in a:' we automatically create a variable named item, so Python now goes to the first letter (item) in the sequence ('h') it then assigns it to item. Then it checks to see what it should do with the item after the colon, where it says print item, which it then does. Then as it is a loop python will now jump back to the start of the code block and assign the next letter of the sequence to the variable item (so item is now 'e') and prints, then loops back etc, until there are now more letters to assign to item, and the loop finishes. That is about it for the for-loop. It is fairly simple in fact it is so simple that when you find a new way to use it you will be amazed of your own geniality. This is because a for-loop will often span only two lines (as above) and look like pure genius compared to the while-loop.

Counting to ten.
Man is usually lazy, so why should we type 1 to 10 if we can make a computer to do it for us.

>>> for i in range(1,11):
        print i

    
1
2
3
4
5
6
7
8
9
10
As explained above a for-loop iterates over a sequence and do with every element what it is told, so when we need the for-loop to count to ten, we actually needs to give it a sequence, that is what the range() function is for, it actually makes a list from and including the first number to and excluding the second number.

For-loops should primarily be used if you want to repeat code a certain amount of times.
</for-loop>
<while-loop>
The while-loop is a different kind of beast altogether, whereas a for-loop will iterate over a sequence until the sequence ends the while-loop will continue >while< some condition is true. Therefore inside a while-loop you will often see a variable change its value until it doesn't fit in the condition given, and this I was really confused at because it is usually written like this:

(When a variable (i) is changed)
>>> i = 0
>>> i = i + 1

I could see what was going on but it just didn't make sense to me because how could i be equal to i + 1, well it isn't, Python just look at the right side of the equal sign first and evaluate that i.e. i (or 0) + 1 which equals 1 (if there was ever any doubt!) and assigns that to the variable i.
Lets try an example:

>>> a = "Hello World!"
>>> i = 0
>>> while i < len(a):
        print a[i],
        i = i + 1

        
H e l l o   W o r l d !
Notice that i is defined as zero before we start the while-loop, if we did that inside the while-loop i would be reset to zero all the time, and that would defy the purpose.
By now I am sure you are wondering about len(), it is of course a function again notice the parenthesis. len() lets you count the number of items in a sequence, this could be a list, a tupple or in this case a string. It cannot be a number.
And as you can see you can use a trailing comma to make the text appear on the same line, and saves a bit of space ;-).

While-loops should be used when you want to loop through your code an unknown amount of times, e.g. you might want to repeat program until the user wants to quit.
</while-loop>