© Wolfram Donat 2018
Wolfram DonatLearn Raspberry Pi Programming with Pythonhttps://doi.org/10.1007/978-1-4842-3769-4_3

3. Introducing Python

Wolfram Donat1 
(1)
Palmdale, California, USA
 

You may remember from the first chapter that the impetus behind the creation of the Raspberry Pi was to make programming more accessible for everyone, particularly kids. To that end, the creators wanted to release a relatively powerful computer that wouldn’t cost a lot of money and that anyone could simply connect to a keyboard, mouse, and monitor and start programming.

Another facet of that creation was to make programming easier, and for that reason Eben Upton and his companions decided to include Python as an integral part of the Pi’s operating system. Python, they reasoned, was a powerful language, yet it was simple enough for someone without any programming experience to pick up quickly.

In this chapter, I’ll give you a quick-and-dirty introduction to Python, walking you through the process of creating a few scripts, running them, and along the way learning some of the basics of this powerful language. I’ll assume that you have at least a passing knowledge of what Python is and perhaps a slight bit of knowledge of programming, but no more than that, because—let’s face it—that’s why you bought this book.

Scripting Versus a Programming Language

Python is a scripting language. Some may quibble over whether it’s a programming language or a scripting language, but to keep the strict technocrats happy, we’ll call it a scripting language.

A scripting language differs from a true programming language in a few ways. As you read the following comparisons, take note of the italics:
  • Programming languages are compiled, unlike scripting languages. Common languages like C, C++, and Java must be compiled by a compiler. The compilation process results in a file of machine code, unreadable by humans, that the computer can read and follow. When you write a program in C and compile it, the resulting .o file is what is read by the computer. One of the side effects/results of this is that programming languages may produce faster programs, both because the compilation only happens once and because the compiler often optimizes the code during the compilation process, making it faster than it would be as originally written.

    Scripting languages, on the other hand, are read, interpreted, and acted upon each time you run them. They don’t produce a compiled file, and the instructions are followed exactly as written. If you write sloppy code, you get sloppy results. For this reason, scripting languages can result in slower programs.

  • Programming/compiled languages most often run directly on top of the hardware on which they are written. When you write and compile a program in C++, the resulting code is executed directly by the processor on your desktop machine.

    Scripting languages most often run “inside” another program, one that takes care of the compiling step just mentioned. PHP, a common scripting language, runs inside the PHP scripting engine. Bash scripts run inside the bash shell, to which you were introduced in the previous chapter.

  • Programming languages tend to be more complex and difficult to learn. Scripting languages can be more readable, less syntax-strict, and less intimidating to nonprogrammers.

    For this reason alone, scripting languages are often taught in introductory programming courses in schools, and students are not introduced to stricter languages like C or Java until they have mastered the basics of programming.

However, the lines between the two have become so blurred in the past few years as to almost completely make the distinctions between the two disappear. To enumerate:
  • While it is true that strict programming languages are compiled and scripting languages are not, advances in processor speeds and memory management in today’s computers have almost made the speed advantages of compiled languages obsolete. A program written in C and one written in Python may both carry out the same task with almost negligible differences in speed. Certain tasks may indeed be faster, but not all.

  • Yes, scripting languages run inside another program. However, Java is considered a “true” programming language because it must be compiled when run, but it runs inside the Java virtual machine on each device. This, in fact, is why Java is so portable: the code is transferable, as long as a version of the virtual machine is running on your specific device. C# is also a compiled language, but it runs inside another programming environment.

  • Okay, I can’t really argue with the fact that programming languages tend to be more complex and difficult to learn, and scripting languages do tend to be easier to read and learn, with fewer syntax rules and more English-like context. Take, for example, the following two ways to print “Hello, world!” to the screen.

    In C++, you would write:

    #include <iostream>
    int main()
    {
    std::cout << "Hello, world!" << std::endl;
    return 0;
    }

    In Python, you would write:

    print "Hello, world!"

    Of course, there are exceptions; I have seen Python scripts that were almost illegible. Likewise, there are some very readable C programs floating about. But, in general, scripts can be easier for the novice programmer to learn, and they can be just as powerful as compiled code.

    Yes, you can program the Pi in C, C++, and even Java or (if you’re particularly masochistic) in assembly language. But now that you know and have seen the difference between programming and scripting languages, wouldn’t you much rather use Python?

    Using Python to program the Pi means that many people who would otherwise never dream of programming a computer can pick up a Raspberry Pi and do something really cool with it, like building one of the projects presented in this book, without learning a difficult language. That is, after all, why the Pi exists—to make programming accessible to more students—and for that reason Python comes preinstalled on the Pi.

The Python Philosophy

In the world of scripting languages, Python is a relative newcomer to the scene, though it is not as new as many people believe. It was developed in the late 1980s, perhaps 15 years after the conception of Unix.

It was implemented in December 1989 by its principal author, Guido Van Rossum. He has remained active in Python’s development and progress, and his contributions to the language have been rewarded by the Python community, which gifted him with the title Benevolent Dictator for Life (BDFL ).

Python’s philosophy has always been to make code readable and accessible. That philosophy has been summed up in Python’s “PEP 20 (The Zen Of Python)” document, which reads 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.

  • Special cases aren’t special enough to break the rules.

  • Although practicality beats purity.

  • Errors should never pass silently.

  • Unless explicitly silenced.

  • In the face of ambiguity, resist the temptation to guess.

  • There should be one—and preferably only one—obvious way to do it.

  • Although that way may not be obvious at first unless you’re Dutch.

  • Now is better than never.

  • Although never is often better than right now.

  • If the implementation is hard to explain, it’s a bad idea.

  • If the implementation is easy to explain, it may be a good idea.

  • Namespaces are one honking great idea—let’s do more of those!

In addition to these commandments, Python has a “batteries included” mindset, which means that whatever strange task you need to do in Python, chances are good that a module already exists to do just that, so you don’t have to reinvent the wheel.

Getting Started with Python

Let’s get started. There are three ways to run Python on your Pi: using the built-in interpreter IDLE, in a terminal window, or as a script. We’ll begin by using IDLE.

Running Python Using IDLE

The IDLE interpreter is a sort of “sandbox” where you can work with Python interactively without having to write whole scripts to see what they do. The name IDLE stands for “Integrated DeveLopment Environment,” but it also pays homage to Eric Idle, one of the founding members of the British comedy group Monty Python. (See the sidebar “Get Me a Shrubbery!”)

Because it’s the most user-friendly way of trying out code, let’s use IDLE first. You can find it by clicking the Raspberry icon at the top left of the menu bar and then opening the Programming submenu (see Figure 3-1). Select the Python 2 (IDLE) option, as we’ll be doing all of our Python programming in Python 2 (see the sidebar). You should be greeted by a window like that shown in Figure 3-2.
../images/323064_2_En_3_Chapter/323064_2_En_3_Fig1_HTML.jpg
Figure 3-1

Finding the IDLE interface

../images/323064_2_En_3_Chapter/323064_2_En_3_Fig2_HTML.jpg
Figure 3-2

The IDLE window

To follow the great programming tradition, let’s start with the first program a programmer ever writes in any language. At the prompt, type

>>> print "Hello, world!"

and press Enter. You should immediately be greeted with

Hello, world!

This is Python’s print statement, whose default option is to the screen. Now type

>>> x=4

and press Enter. The prompt will return, but nothing happens. What has actually happened is that Python’s interpreter has now associated x with 4. If you now type

>>> x

you’ll be greeted with

4

Likewise, if you type

>>> print x

you’ll again be greeted with

4

This illustrates another cool aspect of Python: dynamic typing. In languages like C, you must define a variable’s type before you declare it, like this:

string x = "This is a string.";

or

int x = 5;

Note

See the “Strings” section later in this chapter for more information on strings.

Python “knows” that x is an int (integer) when you tell it that x = 4.

Despite being dynamically typed, Python is strongly typed. This means it will throw an error rather than allow you to do things like add an int to a string. You can also define your own types using classes; Python fully supports object-oriented programming (OOP). I’ll touch on that later, but in short it means you can create an object that may be a mix of integers, strings, and other types, and that object will be its own type. Python has several built-in data types: numbers, strings, lists, dictionaries, tuples, files, and a few others (like Booleans). We’ll visit each of these briefly later in the chapter.

Moving forward, let’s try playing with some variables and operations inside of IDLE. Typing

>>> print x+5

will return 9; however, typing

>>> x + "dad"

results in an error. In this vein, however, typing

>>> "DAD" + "hello"

gives you

'Dadhello'

because, to Python, adding strings is the same as concatenating them. If you’d like to make a list, enclose it in square brackets:

>>> y = ['rest', 1234, 'sleep']

Also, a dictionary—a type of file made up of associated keys and key values—must be enclosed in curly braces:

>>> z = {'food' : 'spam', 'taste' : 'yum'}

Note

Keys and key values are an integral part of Python dictionaries. They’re just linked pairs of values. For example, in the z dictionary in the preceding code example, 'food' and 'spam' are a key and a key value, respectively. Likewise, 'taste' and 'yum' are a key and a key value. To use a dictionary, you input its key, and the associated key value is returned.

Get Me a Shrubbery!

Python is not named after the snake; rather, its creator, van Rossum, named it after the BBC comedy troupe Monty Python, of whom he is a huge fan. As a result, Monty Python references abound in the language. The traditional “foo” and “bar” used to illustrate code in other programs become “spam” and “eggs” in Python examples. You’ll see references to “Brian,” “ni,” and “shrubbery,” all of which should make perfect sense to you if you are a fan of Monty Python. Even the interpreter, IDLE, is named after M.P. member Eric Idle. If you are not familiar with their work, I urge you to put down this book and go watch some of their sketches. I heartily recommend “The Dead Parrot Sketch” and “The Ministry of Silly Walks.” It’s not necessary to be familiar with their work to learn the language, but it may help increase your enjoyment of it.

Python 2 Versus Python 3

Python is somewhat unique among programming languages in that there are two current, working, supported versions: version 2 and version 3. The former is at version 2.7.14 and Python 3 is currently at version 3.6.4. Python 3 was released in 2008; 2.7 was released in 2010 and will see no more major releases (i.e., there will be no version 2.8). Python’s creator decided to “clean up” the language with version 3, with less regard for backward compatibility than you would expect.

The most drastic improvement is how Python 3 handles Unicode, and several aspects of the language have been made to be more user friendly for beginners. Unfortunately, because there is limited backward compatibility, there is a lot of Python software written in Python 2 that simply won’t run in Python 3 without some serious overhaul that, quite frankly, is just not very tempting to do, especially since Python 2 is still supported.

My advice, such as it is, is to concentrate on learning Python 2, since 3 is not that much different. In this book, I'll be using Python 2, but feel free to translate into Python 3 if you feel the urge.

Running Python Using the Terminal

Let’s quickly visit another way of using Python, which is to use the terminal. Open the terminal on your Pi’s desktop and type python at the prompt. You’ll be greeted with the same introductory text as that which opens the IDLE window and the same interactive >>> prompt. At this point, you can issue the same commands as discussed in the preceding section, “Running Python Using IDLE,” and get the same results.

Running Python Using Scripts

The problem with both IDLE and the terminal is that you can’t write true scripts. As soon as you close the window, any variables you’ve declared disappear, and there’s no way to save your work. The last method of writing Python, in a text editor, addresses that problem. You can write a full-length program, save it with a .py extension, and then run it from a terminal.

Let’s write a very short script using the Pi’s default text editor. Open it from the Accessories menu (Figure 3-3).
../images/323064_2_En_3_Chapter/323064_2_En_3_Fig3_HTML.jpg
Figure 3-3

Accessing Text Editor

In the resulting window, type the following:

x = 4
y = x + 2
print y

Save it to your desktop as test.py. Now, open a terminal and navigate to your desktop by typing

cd ~/Desktop

You can now run your script by typing

python test.py

You should be greeted with the number 6. Congratulations! You’ve just written, saved, and run your first Python script!

When you write the scripts in this book, feel free to use any text editor you wish. If you’re comfortable using the default text editor, by all means use it. I tend to use nano or emacs, the terminal-based editors, because I often log in to my Pi remotely, and the default editor can’t be run in a remote login session. For that reason, I’ll often tell you to edit a file like so:

sudo nano spam-and-eggs.py

Use whichever editor you wish.

Next, let’s look at each data type briefly and see what you can do with each.

Exploring Python Data Types

As mentioned earlier, Python provides you with several built-in data types. In the following sections, you’ll learn about numbers, strings, lists, dictionaries, tuples, and files.

Numbers

Numbers seem self-explanatory, and indeed, if you have any programming experience you’ll recognize Python’s number types: integers, shorts, longs, floats, and others. Python has expression operators that allow you to perform calculations on such numbers; these include +, -, /, *, and %; comparison operators such as >, >=, and !=, or, and and; and many others.

All of these operators are built in, but you can import others by using another of Python’s great characteristics: importing modules. Modules are extra libraries you can import into your script that add to Python’s native functionality. In this respect, Python is much like Java: if you want to do something, chances are very good that a library exists to make it easier. For example, if you want to parse text, such as web pages, you can check out the Beautiful Soup module. Need to log in to a remote computer (and you will with some projects)? Import the telnetlib module, and everything you need is available. And for numbers, the math module has all sorts of mathematical functions that add to Python’s number functionality. You can try it for yourself. In an IDLE session, type

>>> abs(-16)

and you should get the result 16. That’s because the absolute value function (I discuss the topic of functions in its own section later in this chapter) is already contained in Python’s default libraries. However, typing

>>> ceil(16.7)

will return an error because the ceiling function is not in those default libraries. It must be imported. Now type

>>> import math
>>> math.ceil(16.7)

and the terminal will return 17.0—the ceiling of x, or the smallest integer greater than x. While you may not need to use the ceiling function, simply importing the math module will give you all kinds of extra functionality, such as logarithmic and trigonometric functions and angular conversions, all with just one line of code.

Strings

In Python, a string is defined as an ordered collection of characters used to represent text-based information. Python doesn’t have a char type like C and other languages do; a single character is simply a one-character string. Strings can contain anything viewable as text: letters, numbers, punctuation, program names, and so on. This means, of course, that

>>> x = 4

and

>>> x = "4"

are not the same thing. You can add 3 to the first example of x, but if you tried it with the second example, Python would give an error—that x points to a string with a value of 4, not an integer, because the 4 is enclosed in quotes. Python does not distinguish between single and double quotes; you can enclose a string in either, and it will be recognized as a string. This has a nice side effect: you can enclose a quote character of the other type inside a string without having to escape with a backslash as you would have to in C. For example:

>>> "Brian's"

gives you

"Brian's"

without any escape characters needed.

There are some basic string operations you will probably use many times in your Python career, such as len (the length of a string), concatenation, iteration, indexing, and slicing (Python’s equivalent of the substring operation). To illustrate, type the following bits of code into an IDLE session and note that the results match the output of what you see here:

>>> len('shrubbery')
9
'shrubbery' is 9 characters long.
>>> 'spam' + 'and' + 'eggs'
'spam and eggs'
'spam', 'and', and 'eggs' are concatenated.
>>> title = "Meaning of Life"
>>> for c in title: print c,
(hit Enter twice)
M e a n i n g  o f  L i f e

For every character in ‘title’, print it. (Note the comma after print c; it tells the interpreter to print the characters one after another, rather than in a downward column.)

>>> s = "spam"
>>> s[0], s[2]
('s', 'a')

The first ([0]) and third ([2]) characters of “spam” are ‘s’ and ‘a’.

>>> s[1:3]
'pa'

The second through the fourth characters are ‘pa’. (When naming a range of characters in a string or other array, the first parameter is inclusive, the second is not.)

You can also convert to and from string objects for those times when you have an integer that is currently typed as a string, like "4", and you want to perform an operation such as squaring it. To do that, it’s as simple as typing

>>> int("4") ** 2
16

You can convert to and from ASCII code, format with escape characters like %d and %s, convert from uppercase to lowercase, and a whole host of other operations, just with Python’s built-in string library.

Lists

Lists, along with dictionaries, are arguably the most powerful of Python’s built-in data types. They are actually collections of other data types and are incredibly flexible. They can be changed in place, grow and shrink on demand, and contain and be contained in other kinds of objects.

If you have experience with other programming languages, you might recognize Python lists as being equivalent to arrays of pointers in, say, C. As a matter of fact, lists are actually arrays in C inside the Python interpreter. As such, they can be collections of any other type of object, since their contained pointer objects can be pointing to literally any other data type, including other lists. They are also indexable—as fast as indexing a C array. They can grow and shrink in place like C++ and C#’s lists; they can be sliced, diced, and concatenated—pretty much anything you do with strings, you can do with lists.

To create a list, declare it with square brackets ( [] ) like so:

>>> l = [1, 2, 3, 4, 5]

or

>>> shrubbery = ["spam", 1, 2, 3, "56"]

After declaring them you can play all sorts of games with them, like concatenating and so on:

>>> l + shrubbery
[1, 2, 3, 4, 5, 'spam', 1, 2, 3, '56']
>>> len(shrubbery)
5
>>> for x in l: print x,
...
1 2 3 4 5
>>> shrubbery[3]
3

(You may also notice here that lists, like arrays, are indexed starting from 0.) By using index and slice operations, you can change lists in place as a combination delete and insert:

>>> cast = ["John", "Eric", "Terry", "Graham", "Michael"]
>>> cast[0:2] = ["Cleese", "Idle", "Gilliam"]
>>> cast
['Cleese', 'Idle', 'Gilliam', 'Graham', 'Michael']

Lists also allow you to use function calls that are associated with and specific to them, like append, sort, reverse, and pop. For an updated list (no pun intended!) of list’s functions, type

>>> help(list)

Note

Python’s help function is extremely useful. If you don’t know how to do something or what’s available or how to use a specific function, typing help(<confusing object>) at the prompt can aid you immensely. (See the sidebar “Python Help.”)

Python Help

If you ever get stuck in Python, its online documentation is a very useful resource. Point your browser to http://docs.python.org/2/library/stdtypes.html to read about all of the standard data types available to you and how to use them. Likewise, http://docs.python.org/2/library/functions.html will show you all of the functions that are available to you to use. Its built-in help function is also very thorough. To try it, in an IDLE session type

>>> import string

and then

>>> help(string)

You’ll be rewarded with everything you ever wanted to know about strings. Similarly, typing

>>> help(string.capitalize)

will show you how to use the capitalize function.

Dictionaries

Like lists, Python dictionaries are extremely flexible collections of objects. Dictionaries differ in that, unlike lists, they are unordered; you can access items of a list by their index, but items in a dictionary are accessed by key. In other words, dictionaries contain key–value pairs; requesting the key will return the value associated with that key. For example, in the following dictionary, the value ‘spam’ can be accessed by its key, ‘food’:

>>> dict = {'food': 'spam', 'drink': 'beer'}
>>> dict['food']
'spam'

Like lists, dictionaries can be nested:

>>> dict2 = {'food': {'ham': 1, 'eggs': 2}}

This means that the key ‘food’ has an associated key value of {'ham': 1, 'eggs': 2}, which is itself a dictionary.

Dictionaries have certain method calls specific to them:

>>> dict.keys()
['food', 'drink']

This lists all of the keys in dict.

>>> dict.has_key('food')
True

This returns True if dict contains the key ‘food’ and returns False otherwise.

Dictionaries can be changed in place:

>>> dict['food'] = ['eggs']
>>> dict
{'food': ['eggs'], 'drink': 'beer'}

This changes the key value of ‘food’ from ‘spam’ to ‘eggs’. (Here, you’ll notice that ‘eggs’, aside from being a normal item, is also a one-item list.)

Note

Keys do not always need to be strings, as you’ve seen here. You can use any immutable objects as keys; if you happen to use integers, the dictionary behaves more like a list—that is, is indexable (by integer key).

Tuples and Files

The last major data types I’ll mention here are tuples and files. Tuples are collections of other objects that cannot be changed, and files refer to the interface to file objects on your computer.

Tuples are ordered collections of objects. They are very much like lists, but unlike lists they can’t be changed in place and are written with parentheses, not square brackets, like this:

>>> t = (0, 'words', 23, [1, 2, 3])

Here, t contains two integers, a string, and a list. You can nest tuples, index them, slice them, and do pretty much anything else you can do with a list, except change them in place.

So, why are there tuples if they’re almost exactly like lists? The most commonly accepted answer to that is because they’re immutable—they can’t be changed. By declaring a collection of objects as a tuple rather than a list, you ensure that that collection won’t be changed somewhere else in your program. It’s sort of like declaring something as a const in C—if you try to change it later, the compiler will give you an error.

Recall that I talked about files in Chapter 2, so the notion should be familiar to you. Python has a built-in function, open, that creates a file object that links to a file sitting in your computer’s memory. File objects are a bit different than the other types, as they are really nothing more than a collection of functions that can be called on those external files. Those functions include read, write, open, close, and various parsing functions for text files. To illustrate, the following lines open a file test.txt (or create it if it doesn’t exist already) for writing, write a line of text to it (complete with a newline escape character), and then close the file:

>>> myfile = open('test.txt', 'w')
>>> myfile.write('Hello there, text file! ')
>>> myfile.close()

All of this happens within whatever directory you happen to be in when you execute the commands.

Note, however, that as written, if test.txt already exists, its contents will be overwritten by the myfile.write() call. If you want to append to the file rather than overwrite it, use an ‘a’ flag when you open it rather than a ‘w’.

Once you have a file open, you can read from and write to it, bearing in mind that you can only read string objects from file objects. This simply means that you must convert all objects in the file to their “real” data types before you perform any operations on them; if myfile.readline() returns ‘456’, you must convert that 456 to an integer with int() if you want to perform calculations on it.

File operations are very useful because they allow you to create and write to text files, but they’re a bit beyond the scope of this introductory chapter. We’ll revisit them later as we use them in projects.

As you can see, Python’s built-in data types can do anything a “true” programming language can do—sometimes more easily and more economically. By combining the types, you can do some truly powerful processes with Python, as you’ll see next.

Programming with Python

Now that you’ve seen the data types, let’s investigate how to use them in actual programs. To create a Python program, you must exit the interpreter and open a text editor, such as emacs or the Pi’s Leafpad. After you create the program, save it with a .py extension. You’ll then be able to run it by typing

$ python myprogram.py

Python is unique among programming languages in its syntax in that it blocks out code using whitespace or indentation blocks. Languages like C enclose a block of code such as an if statement within curly braces; Python uses a colon and indentation to delineate the block.

Code in C looks like this:

if (x==4)
{
    printf("x is equal to four ");
    printf("Nothing more to do here. ");
}
printf("The if statement is now over. ");

The same code in Python looks like this:

if x == 4:
    print "x is equal to four"
    print "Nothing more to do here."
print "The if statement is  now over."

You may notice two additional details about the Python program. First, the parentheses in the if statement are not necessary. In Python, parentheses are optional, but in most cases it’s considered good programming practice to use them, as it enhances your code’s readability. You’ll also notice that most other languages end their lines of code with a semicolon; Python does not. This may take some getting used to, but it is a nice change to not have a program fail to compile because you’ve got a misplaced or missing semicolon somewhere in it. In Python, the end of the line is the end of the statement—that simple.

You’ve seen statements already, such as

x = 4
y = "This is a string."

As mentioned earlier, Python doesn’t require declarations telling it that x is an integer and y is a string—it just knows. These statements are known as assignments, where the value on the right is assigned to the variable on the left. There are various variable-naming conventions in different languages, but the best advice I can give you is to just pick a convention and stick with it. If you prefer Pascal case (ThisIsAVariable), use it; if you prefer camelback (thisIsAVariable), use that one. Just be consistent—you’ll thank yourself later. In any case, an assignment does just that: assigns a value to a variable, whether that variable is a number, string, list, or something else. It’s the simplest of the programming functions.

IF tests

The next programming functionality we’ll look at is the if statement and its derivatives—elif and else. Just as you’d expect, if performs a test and then selects from alternatives based on those test results. The most basic if statement looks like this:

>>> if 1:
... print 'true'
...
true

1 is the same as the Boolean true, so the preceding statement will always print true.

Note

When you type the if statement at the Python prompt in your terminal (or IDLE) and end it with a colon, the next prompt will always be the ellipsis (...), meaning Python is expecting an indented block. If you’re done with the indented block, just press Enter again to end it. If you’re writing a program in a text editor, make sure you indent the blocks you need to indent.

From here on, I’ll format the code as if it were in a text editor and print the output as if you had run the script.

A more complicated test uses elif and else, such as the following:

x = 'spam'
if x == 'eggs':
    print "eggs are better when they're green!"
elif x == 'ham':
    print 'this little piggy stayed home."
else:
    print "Spam is a wonderful thing!"

Obviously, this code outputs “Spam is a wonderful thing!” When the program is executed, the computer checks the first if. If that statement is determined to be true, it executes the indented block directly after it. If that statement is false, it skips the indented block and looks for an elif, which it then evaluates. Again, if it’s determined to be true, or if there is no elif, the computer executes the following block; if not, it skips that block and looks for another elif or an else.

Three points here are important enough to mention. First, remember that if an if statement is determined to be false, nothing in the following indented block is executed—the computer jumps straight to the next unindented line.

Second, Python, like other languages, uses the double equal signs to indicate a test for equality. A single equal sign is used for assignments; a double is a test. I mention this because every programmer—and I do mean every programmer—has, at some point, used a single equal sign in an if statement, and their program has done all sorts of funky, unexpected things as a result. You’ll do it too, but I hope to save you at least a little exasperation ahead of time.

Third, Python ignores blank lines and spaces (except at the interactive prompt and indented blocks, of course) and comments. This is important because it frees you to make sure your code is readable to other programmers, even if that other programmer is you at a later date.

Note

Comments in Python are preceded with a #; the program ignores anything on that line after it.

Readability in your code is a big deal; expect me to drum that into your head regularly. Would you rather attempt to debug the preceding program or something like this:

x='this is a test'
if x=='this is not a test':
    print"This is not "+x+" nor is it a test"
    print 89*2/34+5
else:
    print x+" and I'm glad "+x+str(345*43/2)
print"there are very few spaces in this program"

While you can certainly read the second one, it’s no fun, and after hundreds of lines of code with no spaces, blank lines, or comments, your eyes will thank you—trust me. Look at the difference just in the second-to-last line if you use spaces:

print x + " and I'm glad " + x + str(345 * 43 / 2)

You’re allowed to use white spaces, so use them liberally!

The last part of the if statement I want to mention is the Boolean operators. In a truth test, X and Y is true if both X and Y are true. X or Y is true if either X or Y is true, and not X is true if X is false. Python uses the words, rather than C or C++’s &&, ||, or ! operators. Learn these operators; they’ll come in very handy.

Loops

Normally, a program is executed from top to bottom, one line at a time. However, certain statements can cause the program execution to jump all over the place; these control-flow statements include if/thens and loops.

The simplest loop is probably a block of code, executed a fixed number of times, such as

for x in range (0, 10):
    print "hello"

This simply prints

hello
hello
hello
hello
hello
hello
hello
hello
hello
hello

You can also use for loops to iterate through iterable items, such as a string or even a list:

for x in "Camelot":
    print "Ni!"
Ni!
Ni!
Ni!
Ni!
Ni!
Ni!
Ni!

Or, to iterate through and print the characters themselves:

for x in "Camelot":
    print x
C
a
m
e
l
o
t

Although the for loop’s syntax is a bit different than that of C or Java, once you get used to it, using the syntax becomes second nature.

The other loop statement is the while statement. This statement evaluates a condition and continues to execute the indented block as long as that statement is true:

x = 0
while (x < 10):
    print x
    x = x + 1
0
1
2
3
4
5
6
7
8
9

Unlike what you may have expected, this code never prints “10,” because x is incremented after it’s printed. On the tenth iteration, the interpreter prints “9” and then increments x to 10. At this point, the while condition is no longer true, so the code inside the block is never executed.

while statements are useful if you’re waiting for a particular event to happen, like a keypress or a user pressing “Q” to exit. An example of this follows:

while True:
    var = raw_input("Enter something, or 'q' to quit):
    print var
    if var == 'q':
        break

Two details to note about this script: first, in Python 2.x, the command raw_input is used to get input from a user. In Python 3.x, that command has changed to simply input. Second, remember the break command. This command literally breaks you out of the loop you happen to be in. So, in this case, the while portion of the loop makes it go forever, but if the check var == 'q' returns true, the script breaks out of the loop and ends the program.

Functions

Functions allow you, the programmer, to reuse code and to be more efficient. In general, if you find you need to perform a specific task in your code more than twice, that task is a likely candidate for a function.

Suppose you write a simple program that computes the area and perimeter of a rectangle. It asks the user to input the rectangle’s height and width and then performs the necessary calculations. One of the simplest ways to do this is to create a function that takes as input parameters the rectangle’s height and width. It then prints the rectangle’s area and perimeter and returns to the program. To do this, we use a compound statement block, beginning with the def assignment. The def assignment is how we define a function, with the syntax def functionname (firstparameter, secondparameter):

def AreaPerimeter (height, width):
    height = int(height)
    width = int(width)
    area = height * width
    perimeter = (2 * height) + (2 * width)
    print "The area is:" + area
    print (The perimeter is:" + perimeter
    return
while True:
    h = raw_input("Enter height:")
    w = raw_input("Enter width:")
    AreaPerimeter (h, w)

This little program simply takes the numbers you feed it and returns the calculations. While this may not be the best example (you could just calculate on the fly with less code), it illustrates the idea of code reuse. With this function, no matter where in the program you need to calculate area or perimeter, all you need to do is call AreaPerimeter with the two parameters of “height” and “width” and it’s done for you.

One point to note here: raw_input always returns a string, even if you enter numbers. That’s why the height and width variables in AreaPerimeter must be converted to ints before any calculations can be performed.

Python’s functions are slightly different from the methods, functions, and procedures found in other languages, if you’re familiar with other languages. For one thing, in Python all functions are call-by-reference. Without getting too deep into programming-speak, this means that when you pass a parameter to a function, you really only pass a pointer to a variable, not the variable itself. This has the effect of tending to make Python more memory friendly—you’re not copying entire lists willy-nilly and passing them back and forth to functions, for example. Instead, if a function takes a list as a parameter, you pass it the memory location of the first item of the list, and it does what it needs to based on that location and item.

Another interesting aspect of functions is that they are executable statements. This means that a function definition can actually be declared and called within an if statement, for example. While not normal, it’s legal (and sometimes useful) to be able to do this. defs can be nested inside loops, other defs, and even lists and dictionaries.

We’ll visit functions again as we go through the projects; for now, be aware that they exist and are extremely useful parts of any program you write.

Objects and Object-Oriented Programming

Another important item I want to address in this Python introduction is its native ability to run object-oriented code. While object-oriented programming (OOP) can be an advanced topic and is probably beyond the scope of this book, it’s an important enough topic to brush over lightly, methinks.

OOP is a paradigm in which program data is split up into a mix of objects and functions or methods. An object is a data type—normally a collection of other data types, like integers, strings, and so forth. Objects are normally part of classes, which have associated methods that can act on members of that class.

Perhaps the easiest way to illustrate this is with an example using shapes. In this example, a shape is a class of objects. That class has associated values, such as name and numberOfSides. That class also has associated methods, like findArea or findPerimeter.

The shape class has subclasses, which are more specific. A square is a shape object, with the value shapeType equal to square and numberOfSides equal to 4. Its findArea method takes the lengthOfSides value and squares it. Meanwhile, a triangle object has different values for name, shapeType, and numberOfSides, and its findArea method is different.

This example, while a quick introduction to objects, also illustrates the concept of inheritance, an integral part of OOP. The triangle object inherits its name, numberOfSides, and findArea parts from its parent class, shape (though those parts have different values and implementations). If an object inherits from the shape class, it will also inherit those parts. It may not necessarily use those parts, but it has them. It may have additional parts (the circle object may have a radius value, for instance), but it will always have those parts.

If you start to use classes in your programming, Python is simpler to understand than its counterparts, like C++ or Java. You can pretty much name any object or method with the syntax object.attribute, whether that attribute is an object or a method. If you have a circle object named holyGrail, its radius is holyGrail.radius. A square named unexplodedScotsman has an area defined by unexplodedScotsman.findArea.

Like I said, OOP is beyond the scope of this book. Like functions, however, it can be extremely useful, especially in longer, more intricate programs. Feel free to investigate further as you progress in your Python studies. You’ll find that Python is a very versatile language as well, even allowing you to perform functional and other advanced programming tasks.

Summary

In this chapter, I gave you a brief but practical introduction to Python, starting with a little of its history and then continuing with how to interact with the Python prompt, helping you learn some of its data types, and then showing you a little bit of script writing using an editor. Don’t worry if you can’t take all this information in at once. There’s a lot to learn here, and I’ll explain what I’m doing as we progress through the projects in the book. In the meantime, there are literally thousands of books and courses available on Python, so if you want to learn more, feel free to dig around the Web and your local bookstore.

In the next chapter, we’ll take a look at Electronics 101. You’re going to be building projects, after all, and before you do, you should have a basic grasp of the concepts of electricity, power, and various electronic parts and gizmos.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.115.120