Personal tools
 
Document Actions

A few words of Python

The basic grammar to speak Python.

Se

This tutorial will demonstrate in an entertaining way how to start programming. The tutorial shows how to program Tux Droid with a simple but powerful language: Python.
Page 4 of 6.

Once "tuxsh" is started, it's useful to know about some of the basic constructions in Python.


Assigning a variable

Here we will assign the variable [name] with the text string 'John'. Like this:
>>> name = ’John’
>>> print name
John
>>>
Of course you can try this with your own name.

Strings

The next code will display the variable in a more fluent way:
>>> print ’My name is %s.’ %name
My name is John.
>>>
The character [%s] indicates that the displayed variable value is a string.

Functions

The above line of text is not very convenient to retype every time. The solution is to make it a function. This is done like this:
>>> def display(n):
... print ’My name is %s.’ %n
>>>

Note that [print] is more indented to the right than the first line of code. This means that the instruction [print] is located within the function [display]. This is done with the "tab" key. This approach is very important in Python because it is part of the basic grammar rules. With this method we have defined the function [display]. This function will use the variable [n] that needs to be given when executing the command:

>>> display('John')
My name is John.
>>> display('David')
My name is David.
>>>

Loops

An important construction in every programming language is the loop. For example:
>>> for number in range(10) :
... print ’%d’ % number

You read the instructions like this:

"For the value of the variable [number] we count from 0 to 10, display the value in decimals." The result:

>>> for number in range(10) :
... print ’%d’ % number
0
1
2
3
4
5
6
7
8
9

Conditions

Another important construction is the condition. This will execute a code as long the condition is met. The following lines of code describe the function [test] with the variable [x] as a parameter. It will check if [x] has the value [5], and if so it will display a message.

>>> def test(x):
... if x == 5 :
... print ’x has value 5’
... else :
... print ’x has not value 5 !’
...
>>>

What happens if we try to execute this function with [test(4)]? Try it!

>>> test(4)
x has not value 5 !
>>>


Conclusion

If you have reached this point, you know some of the basic Python constructions and you can start to program Tux Droid.

 
by Se last modified 2007-06-01 16:12
You are here: Home Documentation Tutorials Programming Tux Droid with Python A few words of Python

Powered by Plone CMS, the Open Source Content Management System