Wednesday 21 October 2009

Tutorial 02 - Numbers and strings

Numbers
If you type Python into your command line interface you will get the python interpreter appear - that you can dirrectly type commands into and get feedback from.

Looking at numbers you can use python as a calculator using its command line interface - typing the following will produce some numerical outputs.

>>> 10-5
5
>>> 2*4
8
>>> 6/2+1
4

Try typing in some mathematical functions of your own and see what output you get.

Sometime you will need to work with fractional numbers. What happens when you type 3/2?

In order to fix this behaviour you need to declare that your are using floating point numbers. To do this simply write

>>>3.0/2
1.5

By adding in the decimal point, python now knows that we are using fractional numbers.


Strings
Strings are used to represent text that you might want to display on the screen. You might want to store text in different sections, or generate some text strings on the fly - such as a frames per second counter.

Strings are represented using double quotes or single quotes.

"Hello World!"
'Hello World!'

By deliminating your string using 1 set of quotes, you deny yourself the ability to use those quotes in your sentences - unless you use escape characters. You can also use the other type of quote in your sentance instead.

"Jack said "Hello" to everyone" - This is INVALID
"Jack said 'Hello' to everyone" - This is VALID
'Jack said \'Hello\' to everyone' - This is VALID

There are 2 ways to concatenate strings, the first way is to seperate the strings and other elements by commas, and the other way is to us the + symbol to add them together.

"Frames per Second: ", FPSCounter
"Frames per Second: " + str(FPSCounter)

The first one would not work when written within a function call, as it would cause the function to think that you were sending additional data instead of concatenating the string. The second one requires the str() function call, as our FPSCounter is a number that needs to be converted to a string before we can concatenate them.

There are a variety of string related functions available - you can look them up at http://docs.python.org/tutorial/introduction.html#strings

Tutorial 01 - Running Python

In order to start programming in python - you first need to be able to run python scripts.

You can download python from www.python.org

Once you have python installed you can access it through a command line interface to run your files.

In windows XP you can click start and then run - and enter cmd into the run box to bring up the command line interface.

In Vista you can click on the start menu and in the start search box - type cmd to bring up the same window.

With python installed you can now run python files by typing in python, followed by the location and name of the file - or just the name of the file if you have navigated the command line interface to the location where your files .

e.g. c:>Python pythonfile.py