A few words of Python
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’Of course you can try this with your own name.
>>> print name
John
>>>
Strings
The next code will display the variable in a more fluent way:>>> print ’My name is %s.’ %nameThe character [%s] indicates that the displayed variable value is a string.
My name is John.
>>>
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.