Learning Python with Raspberry Pi - Alex Bradbury - E-Book

Learning Python with Raspberry Pi E-Book

Alex Bradbury

0,0
18,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

The must-have companion guide to the Raspberry Pi User Guide!

Raspberry Pi chose Python as its teaching language of choice to encourage a new generation of programmers to learn how to program. This approachable book serves as an ideal resource for anyone wanting to use Raspberry Pi to learn to program and helps you get started with the Python programming language. Aimed at first-time developers with no prior programming language assumed, this beginner book gets you up and running.

  • Covers variables, loops, and functions
  • Addresses 3D graphics programming
  • Walks you through programming Minecraft
  • Zeroes in on Python for scripting

Learning Python with Raspberry Pi proves itself to be a fantastic introduction to coding.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 324

Veröffentlichungsjahr: 2014

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



This edition first published 2014

© 2014 Alex Bradbury and Ben Everard

Registered office

John Wiley & Sons Ltd, The Atrium, Southern Gate, Chichester, West Sussex, PO19 8SQ, United Kingdom

For details of our global editorial offices, for customer services and for information about how to apply for permission to reuse the copyright material in this book please see our website at www.wiley.com.

The right of the author to be identified as the author of this work has been asserted in accordance with the Copyright, Designs and Patents Act 1988.

All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, except as permitted by the UK Copyright, Designs and Patents Act 1988, without the prior permission of the publisher.

Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.

Designations used by companies to distinguish their products are often claimed as trademarks. All brand names and product names used in this book are trade names, service marks, trademarks or registered trademarks of their respective owners. The publisher is not associated with any product or vendor mentioned in this book. This publication is designed to provide accurate and authoritative information in regard to the subject matter covered. It is sold on the understanding that the publisher is not engaged in rendering professional services. If professional advice or other expert assistance is required, the services of a competent professional should be sought.

Trademarks: Wiley and the Wiley logo are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates in the United States and/or other countries, and may not be used without written permission. Python is a registered trademark of the PSF (Python Software Foundation). Raspberry Pi and the Raspberry Pi Logo are a registered trademark of the Raspberry Pi Foundation, which is a UK registered charity. Minecraft is a trademark of Mohang. Mac OS, iPad, and iPhone are registered trademarks of Apple Inc. Pi Cobbler is a trademark of Adafruit. All other trademarks are the property of their respective owners. John Wiley & Sons, Ltd. is not associated with any product or vendor mentioned in the book.

A catalogue record for this book is available from the British Library.

ISBN 978-1-118-71705-9 (paperback); ISBN 978-1-118-71703-5 (ePub); 978-1-118-71702-8 (ePDF)

Set in 10 pt and ChaparralPro-Light by TCS/SPS

Printed simultaneously in the United States and the United Kingdom

To Kat for her continuing support, Mum and Dad for encouraging me to learn to program on the Commodore 64, Zappa for coping with continual disruption, and every single free and open source software developer for being awesome.

—Ben

Publisher’s Acknowledgements

Some of the people who helped bring this book to market include the following:

Editorial and Production

VP Consumer and Technology Publishing Director: Michelle Leete

Associate Director–Book Content Management: Martin Tribe

Associate Publisher: Chris Webb

Executive Commissioning Editor: Craig Smith

Project Editor: Kezia Endsley

Copy Editor: Kezia Endsley

Technical Editor: Paul Hallett

Editorial Manager: Jodi Jensen

Senior Project Editor: Sara Shlaer

Proofreader: Linda Seifert

Editorial Assistant: Annie Sullivan

Marketing

Marketing Manager: Lorna Mein

Marketing Assistant: Polly Thomas

About the Authors

BEN EVERARD is a Linux geek with a penchant for writing. He’s a founder and director of Linux Voice (http://linuxvoice.com), and his musings can be found on the pages of their magazine and in their podcast. Previously, he’s worked as a technical editor at Linux Format, and as a country manager for NoPC, where he oversaw the testing and deployment of computers to schools in Tanzania. Once upon a time, he was an IT consultant, but that was so long ago he can’t remember it.

He’s moved house and country so many times in the past six years, he’s practically nomadic, although these days he can usually be found in the West Country, England. This is his first book.

ALEX BRADBURY is a compiler, hacker, Linux geek, and Free Software enthusiast. His involvement with the Raspberry Pi started when the first alpha boards were produced. He quickly got sucked in, leading Linux software development efforts for the platform. Still a steady contributor, he’s currently focusing on finishing his PhD at the University of Cambridge Computer Laboratory on compilation techniques for a novel many-core architecture. He’s on Twitter as @asbradbury, or else you can email him at [email protected].

Acknowledgments

Many people have helped make this book possible. At Wiley, Kezia Endsley and Craig Smith saw the book through from its inception. Thank you also to Erin Zeltner for making the words look fantastic and making sure they fit on the pages properly.

There are so many more people that also deserve a huge thank you. There couldn’t be a programming book without a programming environment. Python on the Raspberry Pi is the work of literally thousands of programmers, many of them unpaid. They all deserve acknowledgment, but because of space, we’ll only mention three—Guido van Rossum, Linux Torvalds, and Richard Stallman.

Of course, the software needs hardware to run on, so we’d also like to extend thanks to Eben Upton and the entire Raspberry Pi Foundation.

Any and all mistakes are, of course, the sole responsibility of the authors.

Learning Python® with Raspberry Pi®

Table of Contents

Introduction

What Is Programming?

Why the Raspberry Pi?

How Does this Book Work?

Chapter 1: Getting Up and Running

Setting Up Your Raspberry Pi

Solving Problems

A Quick Tour of Raspbian

Using LXDE (Lightweight X11 Desktop Environment)

Using the Terminal

Changing Configurations with Raspi-Config

Installing Software

Python 3

The Python Interpreter

Running Python Programs

Summary

Chapter 2: A Really Quick Introduction to Python

Drawing Picture with Turtles

Using Loops

Conditionals: if, elif, and else

Using Functions and Methods to Structure Code

A Python Game of Cat and Mouse

Understanding Variables

Defining Functions

Looping Through the Game

Summary

Chapter 3: Python Basics

Variables, Values, and Types

Values Have Types

Storing Numbers

Keeping Text in Strings

Boolean: True or False

Converting Between Data Types

Test Your Knowledge

Storing Values in Structures

Non-Sequential Values in Dictionaries and Sets

Test Your Knowledge

Controlling the Way the Program Flows

Moving Through Data with for Loops

Going Deeper with Nested Loops

Branching Execution with if Statements

Catching Exceptions

Making Code Reusable with Functions

Optional Parameters

Bringing Everything Together

Building Objects with Classes

Getting Extra Features from Modules

Summary

Solutions to Exercises

Exercise 1

Exercise 2

Chapter 4: Graphical Programming

Graphical User Interface (GUI) Programming

Adding Controls

Test Your Knowledge

Creating a Web Browser

Adding Window Menus

Test Your Knowledge

Summary

Solutions to Exercises

Chapter 5: Creating Games

Building a Game

Initialising PyGame

Creating a World

Detecting Collisions

Moving Left and Right

Reaching the Goal

Making a Challenge

Making It Your Own

Adding Sound

Adding Scenery

Adding the Finishing Touches

Taking the Game to the Next Level

Realistic Game Physics

Summary

Chapter 6: Creating Graphics with OpenGL

Getting Modules

Creating a Spinning Cube

Vectors and Matrices

Bringing It All Together

Let There Be Light

Making the Screen Dance

Building the 3D Model

Calculating the Sound Level

Taking Things Further

Adding Some Texture

Summary

Chapter 7: Networked Python

Understanding Hosts, Ports, and Sockets

Locating Computers with IP Addresses

Building a Chat Server

Tweeting to the World

Weather Forecasts with JSON

Testing Your Knowledge

Exercise 1

Getting On the Web

Making Your Website Dynamic

Using Templates

Sending Data Back with Forms

Exercise 2

Keeping Things Secure

Summary

Solutions to Exercises

Exercise 1

Chapter 8: Minecraft

Exploring Minecraft

Controlling Your Minecraft World

Creating Minecraft Worlds in Python

Taking Things Further

Making the Game Snake

Moving the Snake

Growing the Snake

Adding the Apples

Taking Things Further

Summary

Chapter 9: Multimedia

Using PyAudio to Get Sound into Your Computer

Recording the Sound

Speaking to Your Pi

Asking the Program Questions

Putting It All Together

Taking Things Further

Making Movies

Using USB Webcams

Adding Computer Vision Features with OpenCV

Taking Things Further

Using the Raspberry Pi Camera Module

Creating Live Streams

Taking Things Further

Summary

Chapter 10: Scripting

Getting Started with the Linux Command Line

Using the Subprocess Module

Command-Line Flags

Regular Expressions

Testing Your Knowledge

Scripting with Networking

Bringing It All Together

Working with Files in Python

Summary

Chapter 11: Interfacing with Hardware

Setting Up Your Hardware Options

Female to Male Jumper Wires

Pi Cobbler

Solderless Breadboard

Stripboards and Prototyping Boards

PCB Manufacturing

Getting the Best Tools

Wire Cutters/Strippers

Multimeters

Soldering Irons

Hardware Needed for this Chapter

The First Circuit

Power Limits

Getting Input

Expanding the GPIO Options with I2C, SPI, and Serial

The SPI Communications Protocol

The I2C Communications Protocol

The Serial Communications Protocol

Taking the Example Further

Arduino

PiFace

Gertboard

Wireless Inventor's Kit

Trying Some Popular Projects

Robots

Home Automation

Burglar Alarms

Digital Art

Summary

Chapter 12: Testing and Debugging

Investigating Bugs by Printing Out the Values

Finding Bugs by Testing

Checking Bits of Code with Unit Tests

Getting More Assertive

Using Test Suites for Regression Testing

Testing the Whole Package

Making Sure Your Software's Usable

How Much Should You Test?

Summary

Guide

Table of Contents

Begin Reading

Pages

1

2

3

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

24

25

26

27

28

29

30

31

32

33

34

35

37

38

39

40

41

42

43

44

45

46

47

49

50

51

52

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

77

78

79

80

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

107

108

109

110

111

112

113

114

115

116

117

120

121

122

123

124

127

128

129

130

131

136

137

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

173

174

175

177

178

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

213

214

215

216

217

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

236

237

238

239

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

Introduction

COMPUTERS AREN'T JUST beige square things we use for work, they're everything that has a programmable processing unit at its heart. Games consoles, smartphones, GPS units, tablets and a mind-boggling range of other devices all work in the same way. They're all computers, and they've taken over the world. They're the things we use for work, for communications, and for relaxation. In fact, it's hard to think of an area that hasn't been taken over by computers.

Marketing people like to tell you that devices with embedded computers are smart (smartphones, smart TVs, smart watches, and so on), but the truth is they're not. The processing units are just bits of silicon that follow a set of instructions. The “smart” in a smartphone doesn't come from the computer chips, but from the people who program them.

Computers are the most powerful tools mankind has ever created, yet they're under-utilised because few people know how to unleash their full potential. In a world where everything is a computer, the most important people are the programmers who can realise their full power. Programming, then, is an essential skill that's only going to become more and more important in the future.

What Is Programming?

Computers, as we've said, aren't smart. They just follow a simple list of instructions one-by-one until they reach the end. That list of instructions is a program. Programming, then, is the process of taking a task, splitting it up into steps, and writing it down in a language the computer can understand.

The Raspberry Pi can understand many languages, but in this book, you'll learn about Python 3. It's a powerful language, and easy to learn.

This book is for people who want to learn about computer programming and who have a Raspberry Pi. You don't need any special skills or prior experience to work your way through this book, and it doesn't matter if you're not a classic geek who reads comics and watches Sci-Fi, and it doesn't matter if you are. As long as you fit those two basic criteria, this is the book is for you.

By the end of this book, you'll have a good grasp of Python 3, and you'll be familiar with many of the most useful modules (add-ons). Using these, you'll be able to control almost every aspect of your Pi. You'll make it interact with the world around through the General Purpose Inputs and Outputs (GPIOs), and communicate over the Internet. You'll give it vision so it can snap photos and know what it's looking at. You'll make games and manipulate three-dimensional worlds. In short, this is a book about how to utilise your Raspberry Pi to its fullest potential.

Why the Raspberry Pi?

There are a few things that make the Raspberry Pi a great device on which to learn programming. Firstly it's cheap. At around a tenth of the price of a low-end PC, it's cheap enough to have in addition to your main computer. This is useful because programmers tend to tinker with their development machine, and tinkering can break things. Generally this doesn't damage the machine itself, but it can require you to reinstall the system, which can mean a bit of lost data, and it can put the machine out of action for a few hours. If you have a Pi that's used just for development, this isn't a problem; however, if your only computer is shared with a few other people, they may be a bit put out by this.

Secondly, the Pi is raw. It doesn't come hidden away in a box, or in a complete system. This means that you get to decide what sort of system you want to make. You can enclose it in a case should you wish, or you can run it naked. You have access to GPIOs that many machines don't have. Most computers come pre-packaged for a particular purpose (a tablet for surfing the web or playing games, a games console for watching movies or playing games, a laptop for working or playing games, and so on). A Raspberry Pi can turn its hand to any of these things with just a little technical know-how.

Thirdly, the Raspberry Pi runs Linux. This is an operating system a bit like Windows or Mac OS X. It provides a windowing system and a text-based interface for controlling the Pi. If you haven't used Linux before, you'll notice a few differences between it and the system you're used to. For budding programmers, though, the most important difference is that Linux is far more flexible than the alternatives. Just as the physical design of the Raspberry Pi encourages experimentation, so does the operating system.

How Does this Book Work?

Chapters 1–3 are all about getting started with Python on your Raspberry Pi. At the end of them, you'll have a pretty good idea of what Python programming is about. The rest of the book is split into chapters that deal with different uses, such as games or multimedia. These chapters deal with different areas of Python, so generally, you don't need to have read one chapter to understand the next (there are a couple of times where we refer back to something, but we make it clear what's going on when we do).

This means that you can go through this second part of the book in whatever order you want. For example, if you have a particular interest in multimedia, you can skip ahead to that, and then come back and read the others later.

Learning to program is all about actually getting your hands dirty and programming. This means that you can't learn it by just sitting down and reading a book; you actually have to do some yourself. Throughout this book we challenge you to put what you've learned to the test. Sometimes it's through specific exercises designed to train your skills, other times it's through taking the programs we've introduced and adding your own features to them. An important part of programming is the creativity to decide what you want the program to do, so you don't have to follow our suggestions. In fact, we encourage you to treat our suggestions and code as a starting point to creating your own digital works of art.

Chapter 1

Getting Up and Running

WELCOME TOLearning Python with Raspberry Pi. In this book, you'll learn how to unlock the full power of the tiny computer, from 3D graphics to games programming to controlling electronics to tweeting. You'll see what's going on under the hood and learn how to create programs that take advantage of every feature of this minuscule computer.

Setting Up Your Raspberry Pi

To follow this book, you'll need a few bits of equipment:

Raspberry PiUSB keyboardUSB mouseSD cardMonitorPower supply

There are also a few optional bits of kit that may help:

Powered USB hub (highly recommended)Camera moduleUSB webcamUSB WiFi dongle

It is possible to do everything in this book with a model A Raspberry Pi. The real advantage of a model B as far as programming is concerned is the network port. This port will make it easier to connect to the Internet, which you'll need to do to install some software.

Any USB keyboard and mouse should work fine. Most SD cards should work, although there are a few that will cause problems. If you're unsure, buy one from a Raspberry Pi online shop (there are links to a few on http://raspberrypi.org).

The Raspberry Pi has a HDMI (high-definition multimedia interface) video output, but most monitors have VGA or DVI input. If at all possible, use a monitor that has DVI or HDMI input. A HDMI-to-DVI converter should cost only a few pounds/dollars and shouldn't detract from the image quality. HDMI-to-VGA converters are available, but they're more expensive and can cause problems, so use them only if you have no other option.

Most micro USB power supplies from reputable manufacturers should work; however, some cheap ones from no-name companies have caused problems, so if possible, don't skimp too much on this. You could use a USB cable from a normal computer to power your Pi.

Powered USB hubs are recommended for the power-related problems described later in this chapter. Not all USB hubs are powered, so make sure that whatever one you get plugs into the mains electricity to get extra power.

We talk more about camera options in Chapter 9 on multimedia. The only thing to say here is that if you do choose to get a USB webcam, make sure it's compatible with the Raspberry Pi. There's a partial list of working web cams at http://elinux.org/RPi_USB_Webcams.

You'll need to connect your Pi to the Internet to install the software you need in this book. You can do this either by plugging your Pi into your router with a network cable or by using a USB wireless dongle, which will add WiFi connectivity.

Solving Problems

The most common problems with the Raspberry Pi are power-related issues. Not all micro USB power sources can provide enough power, and it becomes more of a problem as you connect peripherals to your Pi, or when you overclock it (see Chapter 5 for more details). Power-related problems will usually manifest themselves as the computer crashing, so if you find that your Pi becomes unstable, this is the best place to start. A good way to get around such issues is to connect your Pi to one power source and connect all the peripherals (keyboard, mouse, and so on) via a powered USB hub.

The second most common cause of problems with Pis is the SD card. These issues can be caused by power supply problems, or they can be problems with the cards themselves. It's important to take preventative measures here to ensure that your data is safe, and that means backups! You can use a service such as Google Drive (although this runs slowly on the Pi), or you can simply keep extra copies of any work on a USB memory stick. SD card issues will usually manifest themselves by the Pi displaying error messages when you try to start it. Most of the time you can solve the problem by reinstalling Raspbian, but if this doesn't work, you'll need to get a new SD card.

If neither of these help, then you'll need to dig a little deeper. The most useful places to look are the kernel buffer and the system log file. The kernel buffer is usually best if you're having problems with hardware, such as a USB device not working. If you open LXTerminal and type:

dmesg

It will output all the messages from the Linux Kernel. The last ones are the most recent and should show any problems.

The system log file (often called syslog) can be displayed with:

cat /var/log/syslog

Again, the most recent messages will be at the end. The information in both of these can be somewhat cryptic. If you still can't work out the problem after reading these, the best place to go is the Raspberry Pi forums at www.raspberrypi.org/phpBB3/. There's a community of helpful people who should be able to point you in the right direction.

A Quick Tour of Raspbian

This is a book about programming, not about generally using Raspbian, so we won't dwell on it too much, but you'll find it useful to know a bit about what's going on.

There are a few operating systems available for the Raspberry Pi, but the instructions in this book are all based on Raspbian, which is the default operating system, and the best choice for a new user. If you have some experience with Linux, you could use Arch or Fedora if you like, but you'll have to change the apt-get commands to ones suitable for your package manager.

The easiest way to install Raspbian on your Pi is using NOOBS, which is available from www.raspberrypi.org/downloads. You'll also find a quick start guide at that website that will tell you everything you need to know to get up and running.

There are two different ways of interacting with Raspbian—from the terminal and using the graphical system (LXDE).

Using LXDE (Lightweight X11 Desktop Environment)

The Lightweight X11 Desktop Environment is the standard windowing system for Raspbian. Its basic setup is the same as most versions of Windows pre-Windows 8. There's a button in the bottom-left side of the screen that opens an applications menu, and currently running applications are displayed in the bar along the bottom (see Figure 1-1).

Figure 1-1:The LXDE desktop with the menu open.

If you get a black screen with white text asking you to log in when you boot up your Pi, it means that you haven't set it up to start LXDE automatically. Don't worry; just log in with the username pi and the password raspberry, and then type the following:

startx

You can set it up to boot into LXDE automatically using raspi-config (see the next section).

Using the Terminal

LXDE is great for many tasks, but sometimes you'll need to use the command line. This is an incredibly powerful interface that's accessed through the terminal. In LXDE, that means opening the LXTerminal application.

When you open LXTerminal, you should see the following line:

pi@raspberrypi~$

This signifies that you are using the username pi on a computer called raspberrypi, and you are in a directory called ~.

In Linux, all directories start from / or root. This is the base of the directory tree and every directory is located in some subdirectory of this. You can move between directories using the cd (change directory) command. Start by moving to this root directory with:

cd /

You should now seen that the command prompt has changed to

pi@raspberrypi/$

You can list the contents of this directory with the command ls. One of the subdirectories is called home. This is where every user on the system has his home directory. Move into it and view its contents with:

cd homels

There should only be one directory called pi. The command prompt should now have changed to show that you're in the directory /home. Move into the only subdirectory with:

cd pi

Now the command prompt will have reverted to:

pi@raspberrypi~$

This is because the character ~ is a shorthand for the current user's home directory. When you type ~ in the terminal, the computer converts it to /home/pi.

There is much more to learn about the command line. So much so that it would take another book this size to cover it with any semblance of completeness. However, you don't need to know everything to start using it, and whenever we tell you to use LXTerminal, we tell you exactly what to type.

Tip

If you are interested in learning more about the Raspberry Pi, or Linux in general, the command line is an excellent place to start, and there's loads of information about it both online and in print. The Linux command-line book, which you can browse for free online, is an excellent place to start. See http://linuxcommand.org/tlcl.php.

We'll leave you with two pieces of advice. Firstly, don't be afraid of the terminal. It can be a bit daunting at first, but the only way to learn how to use it is to use it. Secondly, almost all commands have built-in help that you can access using the flag ––help. For example, if you want to learn more about how to use the command ls, you can enter:

ls --help

This will output:

Usage: ls [OPTION]... [FILE]...List information about the FILEs (the current directory bydefault). Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.

It then goes on to list all the various flags you can use with the command.

Changing Configurations with Raspi-Config

Raspbian comes with a tool to help you set up the hardware on your Raspberry Pi; it's called raspi-config. To start it, open LXTerminal and type:

sudo raspi-config

Here, you'll find options to start LXDE automatically when you boot up, overclock your Pi, and other things. Overclocking your Pi will make a few things in this book run a little better, most notably, installing new software.

Installing Software

You can install new software on your Raspberry Pi using the apt-get command in the terminal. Before installing anything, it's a good idea to update all your software to the latest version. You can do this with:

sudo apt-get updatesudo apt-get upgrade

Then you can use apt-get to install whatever you want. For example, if you want to use iceweasel (a re-branded version of Firefox), you need to open LXTerminal and type:

sudo apt-get install iceweasel

If you prefer to do this using a graphical program, you can get the program synaptic with:

sudo apt-get install synaptic

When you want to install something, you can start it with:

sudo synaptic

From there you'll be able to search for whatever you want.

Note

Whenever you install software, you need to use the word sudo before the command. It tells the computer that you want to make a system-wide change and gives the program sufficient permissions to do this.

Python 3

In this book, you'll learn how to use the Python 3 programming language. In Raspbian, there are a couple of ways to use this language.

The Python Interpreter

There are two ways of using Python, from the shell and saved programs. The shell executes each instruction as you type it, which means it's a really good way of trying out things and doing experiments. Saved programs are bits of Python code that are saved in a text file and run all at once. It's easy to tell which environment you're in because in the shell, all the lines will start with three chevrons:

>>>

Most of the time in this book, we'll deal with saved programs, but there are some occasions (particularly early on) when we tell you to use the shell. To make it clear which bits of code are for which, we've started every bit of code for the shell with three chevrons.

Running Python Programs

There are two different ways you can write programs for Python. You can create text files that contain the code, and then run these files with Python, or you can use an Integrated Development Environment (IDE) such as IDLE 3. Either way will result in the code being run in the same way and it's just a matter of personal preference.

If you want to write the programs as text files, you need to use a text editor such as Leafpad. A word processor such as LibreOffice's Writer is unsuitable because the various formatting it uses will confuse Python. As an example, open Leafpad and create a new file that just has the line:

print("Hello World!")

Once you've created your file, just save it with the extension .py; for example testfile.py. You can then run it by opening LXTerminal and navigating to where the file is saved. Then you run python <filename>. You can use the cd command to move to different directories. For example, if you save the file in a folder called programming in your home directory, you could run it by typing the following into LXTerminal:

cd programmingpython3 testfile.py

If everything has worked correctly, you should see the following line appear on the screen:

Hello World!

The second way is a little simpler. Using an IDE, the text editor and Python interpreter are in the same program. For example, open IDLE 3 (make sure to use the one with the 3), and go to File⇒New Window. In the new window, enter this code:

print("Hello IDLE")

Then go to Run⇒Run Module. It will prompt you to save the module, so select a filename. Once you've done this, it will switch back to the Python interpreter and display the following:

Hello IDLE

It doesn't really matter which one you use, so just go with the way you feel most comfortable with.

Summary

After reading this chapter, you should understand the following a bit better:

You'll need a few extra bits of hardware to get the most out of your Raspberry Pi.Insufficient power is the most common cause of problems.If you're having problems, dmesg and syslog are the best places to find out what's going on.Raspbian uses the LXDE desktop environment.The terminal provides the most powerful way of interacting with the underlying operating system.The raspi-config tool lets you configure your Raspberry Pi.Use apt-get to install new software.You can run Python either through the interpreter or by running saved programs.