Getting started with Python
Python is a high-level general-purpose programming language. It supports multiple programming paradigms, such as object-oriented programming, imperative programming, functional programming, procedural programming, aspect-oriented programming, and metaprogramming. It has a dynamic type system, automatic memory management, and a large standard library to carry out various tasks. It emphasizes code readability, and its syntax allows you to carry out tasks in fewer lines of code than other programming languages, such as C or C++.
Python was conceived and implemented by Guido van Rossum at CWI in the Netherlands as a successor to the ABC language, capable of exception handling and interfacing with the Amoeba operating system platform. Van Rossum is Python's principal author, and he continues to have the central role in deciding the direction of Python. He has been endowed with the title benevolent dictator for life (BDFL) by the worldwide Python community.
The core philosophy of the Python programming language is mentioned in this URL: https://www.python.org/dev/peps/pep-0020/; its first few lines are as follows:
"Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts."
Python is the preferred programming language for the Raspberry Pi family of computers. Its interpreter comes preinstalled with Raspbian, and there is no need for any additional installation to get started with code. It is recommended that you have chapter wise directories for the code examples presented in this book, as shown in the following diagram:
Let's get started with Python. Open Raspbian's Command Prompt LXTerminal. It is located as a shortcut on the taskbar. Alternately, we can find it by navigating to Menu | Accessories | Terminal. We can start Python in interactive mode by typing python
in the prompt and then pressing the Enter key. It will take us to the Python interactive shell, as follows:
Now type the following lines and press Enter:
print "Hello World!"
The output will be as follows:
Python 2.7.3 (default, Mar 18 2014, 05:13:23) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print "Hello World!" Hello World!
Congrats! We have started with Python programming. The interactive mode of Python is suitable for small programs. Press Ctrl + D to exit the interactive shell. For large and code-intensive projects, it's recommended that you use Python in script mode. In this book, we will be using Python in script mode unless specified explicitly. Let's look at how to use Python in script mode.
Create a subdirectory, book
, in the /home/pi
directory for the code examples in this book. We can do this with mkdir book
(by default, we are be in the /home/pi
directory). Then, navigate to this recently created directory with the cd book
command. We can verify our current directory with the pwd
command. It returns the current directory as follows:
pi@raspberrypi ~ $ mkdir book pi@raspberrypi ~ $ cd book pi@raspberrypi ~/book $ pwd /home/pi/book pi@raspberrypi ~/book $
As discussed earlier, we need to keep the code of each chapter in separate directories for better organization. Now, create the chapter01
directory for this chapter in the current book
directory using mkdir chapter01
. Navigate to this with cd chapter01
. At the beginning of each chapter, we are required to create a directory for the chapter under /home/pi/book
for the code examples of that chapter.
We will now create a script file for our code and run it.
Use the Nano text editor to create and edit script files. If we type nano prog1.py
, then Nano will open prog1.py
for editing if it already exists in the current directory; otherwise, it will create a new file with the name prog1.py
. You can exit the Nano editor by pressing Ctrl + X.
Note
You can find more information about nano at http://www.nano-editor.org/.
Alternatively, you can use the Leafpad text editor. We can find it by navigating to Menu | Accessories. Or, we can invoke it from Command Prompt with the leafpad prog1.py
command.
Finally, you can also use vim
, but you will need to install it by running the following command:
sudo apt-get install vim
Note
This is the link for an interactive tutorial on vim
: http://www.openvim.com/.
Let's write the same Python code and run it as a script. Write the following code with Nano, Leafpad, or vim, and save it as prog1.py
:
print "Hello World!"
To run the preceding program, use the python prog1.py
command, and the output will be as follows.
We will run all the other Python programs in this book in the same way.
Let's try some more examples to have more hands-on Python.
The following is the iterative program to calculate the factorial of a given positive integer:
def fact(n): num = 1 while n >= 1: num = num * n n = n - 1 return num print (fact(10))
In the preceding program, def fact(n)
is a user-defined function that accepts an argument. The logic used to calculate the factorial of a positive integer follows the definition and the function returns a calculated factorial. The last line of the program calls the factorial function and prints the returned output as follows:
pi@raspberrypi ~/book/chapter01 $ python prog2.py 3628800
The following is an iterative program for the Fibonacci series:
def fib(n): a=0 b=1 for i in range(n): temp=a a=b b=temp+b return a for i in range (0,10): print (fib(i))
The preceding program prints the first 10 numbers in the Fibonacci series. A more "Pythonic" way of writing the same program, which eliminates the use of a temporary variable, is as follows:
def fib(n): a,b = 0,1 for i in range(n): a,b = b,a+b return a for i in range(0,10): print (fib(i))
The output of both of the preceding programs is the same and is as follows:
pi@raspberrypi ~/book/chapter01 $ python prog4.py 0 1 1 2 3 5 8 13 21 34
Turtle programming with Python
Turtle graphics is one of the best ways to learn programming for beginners. Originally, it was part of the Logo programming language, which was primarily used to introduce programming in schools. Python has the turtle
module, which is an implementation of the same functionality provided by the original turtle. We can write programs with this module in a procedural as well as object-oriented way.
In Python, when we need to access a module that is not part of the current code, we need to import it. Over the course of the book, we will be importing various modules as and when needed, which will provide us with specific functionalities.
Let's get started with importing the turtle
module, as shown here:
import turtle
The following code creates objects for turtle and the screen classes, respectively:
t=turtle.Turtle() disp=turtle.Screen()
We will use the t.color()
function with which we can set the pen and fill color, as follows:
t.color("black","yellow")
We will call the t.begin_fill()
and t.end_fill()
functions to have our shape filled with a fill color:
t.begin_fill() t.end_fill()
The code to draw an actual shape we need will be in between these two function calls, as follows:
t.begin_fill() while 1: t.forward(100) t.left(190) if abs(t.pos())<1: break t.end_fill() disp.exitonclick()
In the preceding code, t.forward()
is used to move the turtle forward a specified distance, and t.left()
is used to rotate the turtle left by 190 degrees. t.pos()
returns the current coordinates of the turtle.
Finally, we use disp.exitonclick()
to close the current output window when we click on the exit button.
Note
At the start, the turtle cursor is at (0,0) and is pointed toward the positive direction of the x axis (facing right).
The output of the program will be a cursor drawing the desired shape progressively, and it helps the programmer understand how the program is actually working. The final output of the preceding program is as follows:
Note
Detailed documentation for the turtle API can be found at https://docs.python.org/2/library/turtle.html.
Next, we will learn the concept of recursion. In terms of programming, recursion means calling the same block of code within itself. For a procedural and modular style of programming, this stands for calling a function or method within itself. Usually, this is done to break a big problem into similar problems with smaller input sizes and then collect the output of all these smaller problems to derive the output of the big problem. One of the best ways to see recursion at work is to visualize it using a turtle. We will now write a program to draw a fractal tree using recursion.
First, we start by importing the required libraries, as follows:
import turtle import random
We need the random
library for the randint()
function, which returns a random integer in the provided range. This is needed to make our generated tree seem different every time. Then, we will define a function to draw a part of the tree recursively:
def fractal_tree(b_len,t): if b_len > 5: temp=random.randint(1, b_len) temp_angle = random.randint(1, 25) t.forward(temp) t.right(temp_angle) fractal_tree(b_len-10,t) t.left(2 * temp_angle) fractal_tree(b_len-10,t) t.right(temp_angle) t.backward(temp)
In the preceding program, we are calling the same function twice in order to draw the further branches of the tree. If the b_len
parameter is less than or equal to 5, then it will be a leaf (which means that the function will not be called again); else, the recursion will continue. We are randomizing the angle and length of the movement of the turtle while drawing the branches here; otherwise, the tree will be symmetrical, which is very unlikely in real life. The combination of t.forward()
, t.backward()
, t.left()
, and t.right()
ensures that at the end of each function call, the turtle cursor is at the same position as where it started.
Finally, we write the routine to call this recursive function:
t=turtle.Turtle() disp=turtle.Screen() t.left(90) t.up() t.backward(100) t.down() t.color("green") fractal_tree(120,t) disp.exitonclick()
The cursor does not draw the movements between the t.up()
and t.down()
function calls. In the preceding code, we are moving the cursor downward by 100 positions so that the tree should fit in the turtle graphics window. When we call fractal_tree()
with 120
as the argument, it takes more than 30 minutes due to the high degree of recursion. The output of the preceding program is as follows: