For this edition of LPI Linux Essentials for the Raspberry Pi we take the time to introduce ourselves to Python programming. When writing code in Python the idea is to stick to the 20 Zen rules of Python, the 20th is never spoken. To display this rules from a Python prompt you can type:
import this
We can start a Python prompt from the command line of the Raspberry Pi by entering the command:
python3
Note: Running just python we start python version 2.7 not version 3.
The interactive Python shell is known as the REPL:
- Read
- Evaluate
- Loop
We can run simple arithmetic operations:
8 * 3
And so on. For more complex mats we can import a Python module:
import math math.sqrt(144)
The result of the evaluation will be printed, I think it is 12.
Python uses significant white space to help define code blocks rather than braces that are often used in other languages. The lack of braces should aid readability by forcing the need to indent code. The standard is to use 4 spaces for an indent level. We see this in the video with a simple for loop:
for name in 'bill', 'jo', 'jack': print("=====") print(name) print("We are out of the loop")
The end of the for statement and the start of the code block is identified by the : . Each line of code that makes up part on the loop is then indented 4 spaces. The final line is not indented and so is not part of the loop.
If we wanted to print the name in upper case (upper) or proper case (capitalize) we can use methods from the string. The variable name once created is immutable, ot cannot be changed. When we convert it to upper case we create anew string, this means that we can use the original string if we need;
for name in 'bill', 'jo', 'jack': print("=====") print(name.upper()) print(name.capitalize()) print(name) print("We are out of the loop")
To leave the REPL interactive shell on the Pi use the keys Control + D