Chapter 12: Introduction to Python

The science club at a school in Jaipur decided to keep a rainfall record. Every morning, two students measured the water collected in a plain rain gauge on the terrace and wrote the reading in a notebook. By the end of July there were thirty-one readings, and now the club wanted three things from them: the total rainfall, the average per day, and the wettest day of the month.

Meera started adding the numbers on paper. She reached the bottom of the column, wrote down a total, then checked it once more and got a slightly different total. So she began again.

Their teacher watched for a while and asked one question: what if you had to do this for every month of the year, and then for the last five years?

Nobody wanted to answer that.

Then she opened a plain window on the computer, typed a few short lines in a language called Python, and pressed Enter. The total, the average and the wettest day appeared straight away — and they would appear just as quickly for five years of readings.

Fig. 12.0-1 shows the same job being done in these two ways.

Diagram

Fig. 12.0-1 – a two-panel drawing. Left panel: a student at a desk adding a long column of rainfall readings in a notebook, with a pencil and an eraser beside her; label this panel “By hand”. Right panel: the same list of readings on a computer screen, with a few short lines of instructions above and the total, average and wettest day shown below; label this panel “By program”. A wide arrow points from the left panel to the right panel.

NoteCuriosity Corner

Q1. What exactly is Python, and where did it come from? Q2. Why is Python called a high-level language? Q3. What does it mean to say that Python is an object-oriented language? Q4. Where is Python used in artificial intelligence and robotics? Q5. What happens inside the computer when you type an instruction at the Python prompt and press Enter?

This chapter will answer each of these five questions.

12.1 Meeting Python

A computer is very fast, very patient, and completely literal. It will add a thousand numbers without getting bored and without making a slip. But it will not do anything at all until someone tells it exactly what to do.

That is the whole problem this chapter starts with. Before you can use a computer for rainfall records, or for a robot, or for anything to do with artificial intelligence, you need a way of telling it what to do. Python is one such way, and it is the one you will use through this book.

12.1.1 Why a Computer Needs a Language

Think about giving directions to someone who has just arrived in your town. You say “turn left at the petrol pump, go straight for two minutes, the school is on your right”. You give steps, in order, in words the other person knows. Give the steps in the wrong order and they end up somewhere else.

A computer needs the same thing, only stricter. It follows steps in order, exactly as given, and it does not fill in anything you left out.

Deep inside, a computer works only with patterns of two signals, usually written as 0 and 1. The instructions it can actually carry out are written in these patterns. This is called machine language. It is perfect for the machine and painful for a person — a single simple job can take dozens of lines of 0s and 1s, and one wrong digit anywhere breaks the whole thing.

So people built a middle layer. Instead of writing 0s and 1s, you write instructions in words and symbols that a human can read, and a piece of software turns them into machine language for you. That set of words and rules is called a programming language.

NoteDefinition

(A programming language is a set of words and rules used to write instructions that a computer can be made to carry out.)

What you write is called a program — a list of instructions, in order, for one particular job. The rainfall program in the opening story was a program: read the readings, add them, divide by the number of days, find the largest.

NoteDefinition

(A program is a set of instructions, written in a programming language, that tells a computer how to do a particular job.)

A program written in Python cannot be carried out by the processor as it stands, because the processor only works in machine language. Python programs are handled by an interpreter — software that reads your program one line at a time, converts that line, and gets the computer to carry it out before moving to the next line. Fig. 12.1-1 shows this path.

Diagram

Fig. 12.1-1 – a left-to-right flow in three labelled boxes. Box 1: “Program written in Python” showing two short instruction lines in a text window. Box 2: “Python interpreter” drawn as a gear or converter. Box 3: “Instructions the processor carries out” showing a processor chip with 0s and 1s around it. Arrows point from Box 1 to Box 2 to Box 3. A small return arrow from Box 3 back to a screen labelled “result shown to you”.

Because the interpreter works line by line, a Python program stops at the first line it cannot deal with and reports the problem there. That is helpful while you are learning, since you are told roughly where the mistake is. It is also the reason a Python program usually runs a little slower than a program written in a language that is converted all at once, before it is ever run.

Q. Why can’t we just tell the computer what we want in ordinary English?

A. Ordinary English is often incomplete or open to more than one meaning — “add up the readings” does not say what to do with a day that was missed. A programming language has a small vocabulary and fixed rules, so every instruction has exactly one meaning.

12.1.2 The Story of Python

Python was created by Guido van Rossum, a Dutch programmer. He began working on it towards the end of 1989 at a research institute in the Netherlands, and released the first version publicly in 1991. His aim was a language that was quick to write, easy to read, and still powerful enough for real work.

Two later versions matter. Python 2 arrived in 2000. Python 3, released in 2008, tidied up several parts of the language and is the version used today. Everything in this book is Python 3. Fig. 12.1-2 shows these dates together.

Diagram

Fig. 12.1-2 – a horizontal timeline with four marked points, left to right: “1989 – work begins”, “1991 – first public release”, “2000 – Python 2”, “2008 – Python 3”. Draw the line as a simple arrow pointing right, with a small caption below reading “Python 3 is the version in use today”.

Python is free. Anyone can download it, use it, and look at how it is built, without paying for it. This is one reason it spread so widely into schools, colleges and companies.

NoteDefinition

(Python is a free, high-level, general purpose, object-oriented programming language, first released in 1991, known for being easy to read and write.)

Those three descriptions — high-level, general purpose, object-oriented — are the heart of what Python is, and each one is explained in the next section.

Q1. What exactly is Python, and where did it come from?

A. Python is a programming language — a set of words and rules for writing instructions a computer can carry out. It was created by Guido van Rossum in the Netherlands, begun in 1989 and first released to the public in 1991. It is free for anyone to use, and the version in use today is Python 3, released in 2008.

Python is not named after the snake. Guido van Rossum was a fan of the British comedy series Monty Python’s Flying Circus, and picked the name because it was short and slightly odd. The snake picture stuck to the language later, entirely by accident.

12.2 What Kind of Language Python Is

There are hundreds of programming languages, and they are not all alike. Some are built for one narrow job. Some sit very close to the machine. Some are built to be pleasant for people to read.

Python is usually described in three words: object-oriented, high-level and general purpose. Each of these says something useful about what Python is like to work with, and each is explained below.

12.2.1 An Object-Oriented Language

Think about the ID cards in your school. There is one design: a photograph in the corner, then the name, the class, and the roll number. Every card follows that design, but each card carries different details.

Software has the same problem. A school’s computer system may hold three thousand students. Writing separate instructions for each one would be impossible. What you want is one design, used three thousand times.

That is the idea behind object-oriented programming (OOP) — a way of writing programs in which data and the actions that work on that data are kept together in one unit.

The design is called a class, and each thing built from that design is called an object. A class describes what details an object will hold and what actions it can perform. An object is one actual item made from that design, with its own details filled in. See Fig. 12.2-1.

Diagram

Fig. 12.2-1 – on the left, a rectangle labelled “Class: Robot” divided into two parts. Upper part headed “Details it holds” listing “name, battery level, speed”. Lower part headed “Actions it can do” listing “move forward, stop, report battery”. On the right, three smaller rectangles labelled “Object 1”, “Object 2”, “Object 3”, each showing the same three details with different values filled in. Three arrows point from the class rectangle to the three objects, with the label “made from the same design”.

NoteDefinition

(A class is a design that says what details an object will hold and what actions it can perform. An object is one item built from that design, with its own values filled in.)

Object-oriented programming is built on a few further ideas. You will not write them yourself this year, but you should know what the words mean when you meet them.

  1. Encapsulation — keeping an object’s data and its actions bundled inside the object, so that other parts of the program change that data only through the actions provided.
  2. Inheritance — building a new class from an existing one, so that it keeps the old details and actions and adds its own. A “Delivery Robot” class can be built from a general “Robot” class.
  3. Polymorphism — allowing the same action name to work on different kinds of objects, each doing what suits it. A “stop” action means one thing for a wheeled robot and another for a robotic arm.
  4. Abstraction — showing only what is needed to use a thing, and keeping the inner detail out of the way. You start a scooter without knowing how its engine is built.

Python is called an object-oriented language because it supports all of this. But it does not force it on you. You can write a complete, useful Python program without ever creating a class, and that is exactly what you will do in this book. The object-oriented side of Python is there for when programs grow large.

Q3. What does it mean to say that Python is an object-oriented language?

A. It means Python lets you write programs around objects — units that hold some data along with the actions that work on that data. You write a class once as the design, then build as many objects from it as you need. Python supports this fully, but does not insist on it; small programs can be written without classes at all.

12.2.2 A High-Level Language

The 0s and 1s from Section 12.1.1 are the machine’s own level. A language that stays close to that level, working directly with the processor’s own instructions and memory addresses, is called a low-level language. It gives very tight control over the hardware, and it is slow and difficult to write.

A high-level language does the opposite. It lets you write in terms of the problem you are solving rather than the machine you are solving it on. Python is a high-level language, for these reasons.

  1. Its instructions are made of ordinary English words such as print, if and while, so a line of Python can often be read aloud and roughly followed.
  2. It handles memory for you. When your program needs space to hold a value, Python arranges it, and when that value is no longer needed, Python clears the space. You never work with memory addresses.
  3. It hides machine detail. The same Python program will normally run on a Windows computer, a Mac or a Linux machine without being rewritten.
  4. It comes with a large amount of ready-made code for common jobs, so you rarely start from nothing.
  5. It reports errors in readable messages that name the line and the kind of problem, instead of simply stopping.

Table 12.1 sets the two levels side by side.

Table 12.1 – Low-level language vs high-level language | Feature | Low-level language | High-level language | |—|—|—| | How it reads | Machine codes and memory addresses | Words close to plain English | | Ease of writing | Difficult, long, easy to get wrong | Short and readable | | Memory handling | Done by the programmer | Done by the language | | Works on other computers | Usually needs rewriting | Usually runs unchanged | | Control over hardware | Very direct | Limited | | Typical use | Device drivers, small controllers | Websites, data work, AI, general software |

The honest cost of working at a high level is speed and control. A high-level program has extra work going on beneath it, so for the same job it usually runs slower than a carefully written low-level one, and you cannot reach the hardware as directly. For almost everything you will do, this trade is well worth making.

Q. If high-level languages are easier, why does anyone still use low-level ones?

A. Because some jobs need direct control of the hardware or the last bit of speed — the software inside a tiny microcontroller, for example, where there is very little memory to spare.

Q2. Why is Python called a high-level language?

A. Because it is written in terms of the problem rather than the machine. Its instructions use ordinary English words, it manages memory on your behalf, it hides the details of the processor, and the same program will usually run on different computers without being changed.

12.2.3 A General Purpose Language

Some languages are built for one job and are excellent at that job alone. SQL, for example, is designed for storing and fetching data in databases. You would not build a game with it.

Python is not like that. It is a general purpose language — a language that is not tied to any one field, and can be used to build many different kinds of software. The same language handles a school’s rainfall calculation, a website, a robot’s control program and an image-recognition system.

Two things make this possible. The core language is small and unfussy, so it fits many kinds of problem. And an enormous amount of ready-made code has been written for it over the years, covering field after field, so whatever you are working on, much of the groundwork already exists.

This is the main reason Python is a good first language to learn. What you learn here will still be useful whether you go on to work with data, with websites, or with robots.

Q. Does being general purpose mean Python is the best choice for every job?

A. No. It means Python can be used for most jobs. For work where speed matters greatly, or where a program must fit into a very small memory, another language is often the better choice.

12.3 Advantages of Python

Plenty of languages are high-level and general purpose. So why has Python, in particular, ended up in so many schools, laboratories and companies?

The reasons below are the ones that matter most to someone starting out. Some of them follow from what you have just read; the rest are about the world that has grown up around the language.

  1. It is easy to read and write. The rules for how instructions must be written — the syntax of a language — are unusually simple in Python. Instructions are short, they use everyday English words, and the layout of the lines on the page shows how the program is organised. You can often get the sense of a Python program before you have been taught the instructions in it.

  2. It is free and open source. Open source means the code the language itself is built from is published for anyone to read, use and improve. Python costs nothing to download, nothing to use in a school, and nothing to use in a business. Nobody needs a licence, and no work you do in it can be locked away behind a fee later on.

  3. It runs on almost any computer. Python is available for Windows, macOS and Linux, and a program written on one of them will normally run on the others without a single change. This is called being cross-platform. Fig. 12.3-1 shows the idea.

Diagram

Fig. 12.3-1 – at the top, a single sheet of paper labelled “One Python program”. Three arrows fan out downwards to three computers labelled “Windows”, “macOS” and “Linux”. Below each computer, show the same result on the screen. Caption strip along the bottom: “same program, same result, different machines”.

  1. A very large amount of ready-made code exists for it. Python has been used by a huge number of people for over thirty years, and a great deal of what they wrote has been shared for others to use. Whether you need to read a spreadsheet, draw a graph or control a motor, someone has almost certainly already written and tested the difficult part.

  2. It is used for real work, not only for teaching. Large technology companies use Python inside their own products and pay people to improve the language. That means it is well maintained, well documented, and worth learning as a skill and not just as a school subject.

  3. You can try things out one line at a time. Python lets you type a single instruction, press Enter, and see the result straight away, without writing a whole program first. When something does not work, you can test the doubtful part on its own. This one habit will save you more time than anything else in this book, and Section 12.6 shows you how to use it.

Q. If Python is free, who pays the people who build it?

A. Much of the work is done by volunteers, and some of it by people employed at companies that depend on Python and contribute their work back. Open source means the code is shared, not that everyone working on it is unpaid.

Where Python is not the best choice

No language is best at everything, and it is worth being honest about where Python is weak.

It is comparatively slow. Because the interpreter deals with your program line by line while it runs, a Python program will usually take longer than the same job written in a language such as C. For a rainfall calculation this makes no difference at all. For software that must react within a fraction of a second, it can.

It also uses more memory than a low-level language, which matters on very small devices, and it is rarely the first choice for building phone apps. When you meet a project where speed or memory is tight, expect a different language to be used for that part of the work.

12.4 Uses of Python

A language is only as useful as the work people do with it. Python turns up in a surprising number of places — behind websites you visit, inside research laboratories, in the software that recommends what to watch next, and in small robots on a school workbench.

Fig. 12.4-1 gathers the main fields together. The two sub-sections below take them in two groups: ordinary software first, then the data and artificial intelligence work that this book is heading towards.

Diagram

Fig. 12.4-1 – a wheel diagram. A central circle labelled “Python”. Eight spokes lead out to eight labelled boxes arranged around it: “Websites”, “Games”, “Databases”, “Scientific work”, “Office automation”, “Data analysis”, “Artificial intelligence”, “Robotics and small devices”. Keep all boxes the same size and use a simple line for each spoke.

12.4.1 Python in Everyday Software

Much of the software you use every day has a part written in Python. Here are the common uses.

  1. Websites. When you open a website, something on a distant computer has to work out what to send back — check your login, look up your details, build the page. Python is widely used for this behind-the-scenes half of a website. Ready-made toolkits such as Django and Flask handle the routine parts.

  2. Databases. A database is an organised store of information — a school’s student records, a shop’s stock list. Python can connect to database software such as MySQL and SQLite, put information in, and pull it back out.

  3. Automating repeating jobs. This is where Python quietly saves the most time. Renaming four hundred photographs, pulling one column out of fifty spreadsheets, checking whether a file arrived this morning — jobs that are simple but tedious, and exactly the kind of thing a computer should be doing.

  4. Scientific work. Researchers use Python for calculations, simulations and modelling in subjects such as physics, biology and chemistry, with toolkits such as SciPy and SymPy for the mathematics.

  5. Games. Simple two-dimensional games are often built in Python using Pygame, which handles the drawing, the sound and the keyboard.

Q. If a website’s page is what I see, what is Python doing that I cannot see?

A. It runs on the web server — the computer that sends you the page. It checks who you are, fetches the right information from a database, and builds the page before it is sent to your screen.

12.4.2 Python in AI, Data and Robotics

Artificial intelligence (AI) is the branch of computer science concerned with building systems that carry out tasks we normally think of as needing human intelligence — recognising a face in a photograph, working out what a sentence is asking for, picking out a pattern in a pile of records.

Every one of those tasks starts in the same place: a large amount of data that has to be read in, cleaned up, measured and reshaped before anything clever can be done with it. That is unglamorous work, and Python is very good at it. This is the main reason Python became the usual language for AI.

The work falls into a few areas.

  1. Handling and exploring data. Toolkits such as NumPy and pandas are used to load thousands of records, sort them, find averages and totals, and spot readings that look wrong. Matplotlib draws the graphs that let you see the shape of the data.

  2. Machine learning. This is the part of AI where a system is built by showing it many examples rather than by writing out every rule. scikit-learn and TensorFlow are commonly used for it.

  3. Computer vision. Getting useful information out of pictures and video — counting vehicles at a junction, checking whether a part on a factory line is the right shape. OpenCV is the usual toolkit.

  4. Natural language processing. Working with human language in text form, as a chat assistant or a translation tool does. NLTK and spaCy are used here.

  5. Robotics and small devices. A robot needs to read its sensors, decide what to do with those readings, and drive its motors. Python is used for this in two ways: on the ordinary computer that plans and monitors, and — through cut-down versions such as MicroPython and CircuitPython — directly on the small controller boards inside the robot itself.

AI systems are built from data, and data about people is never neutral. A system trained mainly on photographs of one group of people will work poorly for everyone else, and a system that scores job applicants will repeat whatever unfairness sits in the records it was given. Before building anything that makes a judgement about people, ask who is missing from the data, and be ready to show how the system reached its answer.

Q4. Where is Python used in artificial intelligence and robotics?

A. In AI it is used at every stage — loading and cleaning data, drawing graphs to explore it, building machine learning models, working with images, and working with human language. In robotics it is used both on the computer that plans and monitors the robot, and on the small controller boards inside the robot, through cut-down versions such as MicroPython and CircuitPython.

12.4.3 Python Libraries

You have now met about a dozen names — NumPy, Flask, Pygame, OpenCV. None of them is part of the Python language itself. They are libraries.

Here is the problem a library solves. Suppose your program needs a square root. Working one out from scratch is a real piece of mathematics, and you would have to write it, test it, and fix it before you got anywhere near the job you actually cared about. Someone has already done that work, carefully, and shared it.

NoteDefinition

(A library is a collection of ready-written, tested code that your program can use, so that you do not have to write that part yourself.)

Python already carries a large collection of libraries when you install it. One of them, called math, holds the common mathematical operations. To use a library, you bring it into your program with the word import, and then use its contents by name. The instruction print() shows a value on the screen.

finding a square root using the math library Problem: display the square root of 144 without writing the method for it yourself.

import math

print(math.sqrt(144))

Output:

12.0

The line import math makes the library available. The name math.sqrt means “the square-root operation belonging to math”. The answer is shown as 12.0 rather than 12 because square roots are not usually whole numbers, so Python gives the result in decimal form.

A single file of ready-written code like this is called a module, and a group of related modules bundled together is called a package. In everyday use, people say “library” for all of these.

Fig. 12.4-2 shows the idea. Your program is short, because most of the difficult work is borrowed.

Diagram

Fig. 12.4-2 – on the left, a small box labelled “Your program” containing three short lines. On the right, a bookshelf with four labelled books: “math”, “pandas”, “Matplotlib”, “OpenCV”. Arrows run from three of the books to the small box, each labelled “import”. Caption strip below: “borrow the difficult part, write only what is yours”.

Libraries save enormous amounts of time, but they are not free of cost. Every library you import is code you did not write and have not checked, and if it has a fault or is no longer being maintained, your program carries that fault too. For schoolwork, stick to the well-known libraries named in this chapter.

Change 144 in the program above to 2 and run it again. Note down how many digits Python shows after the decimal point, and try to say why the answer cannot be written exactly.

12.5 Getting Python Running on a Computer

Reading about a language will only take you so far. From the next chapter onwards you will be writing programs, and for that you need two things on the computer in front of you: the Python interpreter, which carries out your instructions, and somewhere to type those instructions.

Both arrive together in a single download, which is what this section is about.

12.5.1 Installing Python

Python does not usually come with a Windows computer, so it has to be downloaded and installed once. After that it stays on the machine. The steps below are for Windows, which is what most school laboratories use.

  1. Open a web browser and go to the official Python website, python.org, then open its downloads page for Windows.
  2. Near the top of that page, under the heading for Python releases for Windows, click the latest Python 3 release. Always take a Python 3 version — Python 2 is long out of use.
  3. Scroll down that release’s page to the list of files and click the Windows installer for 64-bit computers, which is the right one for almost any machine bought in the last several years. The download is a single file.
  4. Open your Downloads folder and double-click that file. An installer window opens, as in Fig. 12.5-1.
  5. Before clicking anything else, tick the box near the bottom that says “Add python.exe to PATH”.
  6. Click “Install Now” and wait for the installer to finish. It arranges everything itself, and you do not need to choose a folder.

Diagram

Fig. 12.5-1 – screenshot of the Python installer’s first window on Windows, showing the two choices “Install Now” and “Customize installation”, with the tick box “Add python.exe to PATH” at the bottom of the window circled or arrowed for attention.

That last tick box is worth a word. PATH is a list the operating system keeps of the folders it should look in when you ask for a program by name. Adding Python to it means you can start Python from any folder simply by typing python. Leave the box unticked and Python still installs perfectly well, but the computer will not find it by name later.

forgetting to tick “Add python.exe to PATH” What goes wrong: Python installs, but typing python in a terminal gives a message saying the command was not recognised, and students assume the installation failed. The fix: run the installer again and choose the repair or modify option, where the same setting can be turned on. Nothing needs to be uninstalled first.

On other systems it is simpler. Most Linux computers already have Python 3 installed. On a Mac, the same website offers a macOS installer that works in the same way.

Q. The school computer already has Python. Should I install it again?

A. No. Check first, and ask the teacher in charge of the laboratory before installing anything on a school machine. Two versions on one computer can leave you unsure which one is running your program.

12.5.2 IDLE and the Python Shell

The installation brings a small program along with the language. It is called Integrated Development and Learning Environment (IDLE), and it is where you will type your Python.

An environment like this is more than a place to type. It colours the parts of your program differently so mistakes stand out, it lines up the indentation for you, and it lets you run what you have written without leaving the window.

To open it on Windows, do either of these.

  1. Click the Start menu, find the Python folder for the version you installed, open it, and choose IDLE.
  2. Or click the search box, type IDLE, and open the result.

What appears is the Python shell — a window in which you type one instruction at a time and Python carries it out immediately. Fig. 12.5-2 shows it as it looks when it opens.

Diagram

Fig. 12.5-2 – screenshot of the IDLE shell window just after it opens, showing the menu bar with File, Edit, Shell, Debug, Options, Window and Help, then the two opening lines giving the Python version and the “Type help, copyright, credits or license() for more information” message, and below them the >>> prompt on an otherwise empty line.

The first line names the version of Python that is running. The line below it points you to some built-in help. Then comes the part that matters: three angle brackets, >>>, with the cursor blinking after them.

Those three brackets are the prompt. A prompt is the sign that a program is waiting for you to type something. Here it means Python has started, has nothing to do, and is ready for an instruction.

NoteDefinition

(The Python shell is a window in which you type one Python instruction at a time and see its result immediately. The >>> mark it shows is called the prompt, and means Python is waiting for an instruction.)

Do not be put off by how plain the window looks. Every program in this book, and a good deal of the software described in Section 12.4, was written and tested in a window very much like this one.

12.6 The Interactive Window

Imagine you are working through a long calculation in your notebook and you are unsure of one small step. You do not rewrite the whole page. You pick up a calculator, check that one step, and carry on.

Programming needs the same thing. Most of the time you are not writing a finished program — you are checking one small doubt. Does this instruction give the answer I expect? What does this library return? Writing, saving and running a whole file each time would be slow.

That is what the interactive window is for. It is another name for the Python shell you met in Section 12.5.2, and it is the window that opens when you start IDLE. You type one line, press Enter, and the result appears underneath.

Type a small multiplication at the prompt and press Enter. Python shows the answer straight away and then puts up a fresh prompt.

>>> 7 * 8
56
>>>

Notice that you did not have to ask for the answer to be displayed. In the interactive window, when a line produces a value, Python shows it. The new >>> underneath means Python is finished and is waiting again.

The read-evaluate-print loop

The window is doing the same four things over and over.

what the interactive window does with each line you type Input: one line of Python typed at the prompt Output: the value that line produces, shown on the screen Steps:

1. Show the >>> prompt and wait.
2. Read the line the user types when Enter is pressed.
3. Evaluate it — work out what it produces.
4. Print the result on the next line.
5. Go back to step 1.

Why it works: each line is dealt with completely before the next is asked for, so what you see on screen is always the result of the line directly above it.

This cycle of reading, evaluating and printing, repeated without end, is called the read-evaluate-print loop (REPL). The name is simply the first letter of each step. Fig. 12.6-1 shows it as a circle.

Diagram

Fig. 12.6-1 – a circular flow of four labelled boxes joined by curved arrows going clockwise: “Read the line you typed”, “Evaluate it”, “Print the result”, “Wait at the >>> prompt”, with the last arrow returning to the first box. Place the letters R, E, P, L beside the matching boxes.

Q5. What happens inside the computer when you type an instruction at the Python prompt and press Enter?

A. Python reads the line you typed, evaluates it — that is, works out what it produces — prints the result on the next line, and then shows the prompt again and waits for the next line. This repeating cycle is called the read-evaluate-print loop, or REPL.

Two windows, two jobs

The interactive window has one weakness: it forgets. Close IDLE and everything you typed is gone. It is a workbench, not a notebook.

So IDLE has a second window. The editor window is a plain text window in which you type a whole program, save it as a file ending in .py, and run all of it at once. You open it from the File menu by choosing New File, and run what you have written from the Run menu. The result appears back in the interactive window.

Table 12.2 sets the two side by side.

Table 12.2 – Interactive window vs editor window | Feature | Interactive window | Editor window | |—|—|—| | How much you type | One line at a time | A whole program | | When it runs | The moment you press Enter | When you choose Run | | Is it saved | No, it is lost when IDLE closes | Yes, saved as a .py file | | Showing a value | Shown automatically | Only where print() is used | | Best used for | Trying one thing out, checking a doubt | Writing anything you want to keep or run again |

That fourth row catches people out often enough to be worth its own warning.

expecting a saved program to display a value on its own What goes wrong: a line such as 7 * 8 is typed into the editor window and the program is run. Nothing appears. The student assumes the program is broken. The fix: the value was worked out — it was simply never displayed. In a saved program, anything you want to see must be inside print(), so the line becomes print(7 * 8). The interactive window is the exception, not the rule.

From here on, use the interactive window to test small pieces and the editor window for anything you want to keep. The next chapter starts writing programs in that second window.

Open the editor window, type the two lines of the square-root program from Section 12.4.3, save the file as root.py, and run it. Then remove the word print and the brackets around math.sqrt(144), run it again, and note what changes.

12.7 Summary

  1. A computer carries out instructions exactly as given, in the order given, and fills in nothing that has been left out.
  2. The instructions a processor can actually carry out are written in machine language, as patterns of 0 and 1. Writing directly in it is slow and error-prone.
  3. A programming language is a set of words and rules for writing instructions a computer can be made to carry out. A program is a list of such instructions written for one particular job.
  4. Python programs are handled by an interpreter, which reads the program one line at a time, converts each line and gets it carried out before moving on. This makes errors easier to locate and makes Python a little slower than languages converted all at once.
  5. Python was created by Guido van Rossum, begun in 1989 and first released in 1991. Python 3, released in 2008, is the version in use today. Python is free for anyone to use.
  6. Python is described as object-oriented, high-level and general purpose.
  7. Object-oriented programming keeps data and the actions that work on that data together in one unit. A class is the design; an object is one item built from that design. Its further ideas are encapsulation, inheritance, polymorphism and abstraction.
  8. Python supports object-oriented programming fully but does not force it. Small programs can be written without any classes.
  9. A high-level language is written in terms of the problem rather than the machine. Python uses English-like words, manages memory for you, hides machine detail, and usually runs unchanged on Windows, macOS and Linux.
  10. A low-level language stays close to the processor. It gives direct control of the hardware but is difficult to write and rarely portable.
  11. A general purpose language is not tied to one field. Python is used for websites, databases, automation, scientific work, games, data analysis, artificial intelligence and robotics.
  12. The main advantages of Python are its simple syntax, its being free and open source, its cross-platform nature, the large amount of ready-made code available for it, its wide use in real work, and the ability to test one line at a time.
  13. Python is comparatively slow and uses more memory than a low-level language, so it is not the best choice where speed or memory is tight.
  14. Python became the usual language for artificial intelligence because so much AI work is the handling of large amounts of data, which Python does well.
  15. A library is a collection of ready-written, tested code brought into a program with import, so that difficult parts need not be written again. A single such file is a module; a bundle of related modules is a package.
  16. Any system built from data about people can carry the unfairness present in that data, so it matters who is represented in the data and whether the system’s answers can be explained.
  17. Installing Python on Windows means downloading the latest Python 3 installer from the official site and running it, with the option to add Python to PATH turned on. Most Linux computers already have Python 3.
  18. IDLE is the environment installed along with Python. It opens the Python shell, where the >>> prompt shows that Python is waiting for an instruction.
  19. The interactive window carries out one line the moment Enter is pressed, showing any value it produces. This cycle is called the read-evaluate-print loop, or REPL.
  20. The editor window is for whole programs, saved as .py files and run all at once. In a saved program, a value is shown only where print() is used.

12.8 Key Terms

  1. Abstraction – showing only what is needed to use something and keeping the inner detail out of the way.
  2. Artificial intelligence (AI) – the branch of computer science concerned with building systems that carry out tasks we normally think of as needing human intelligence.
  3. Class – a design that says what details an object will hold and what actions it can perform.
  4. Cross-platform – able to run on different operating systems, such as Windows, macOS and Linux, without being rewritten.
  5. Editor window – the IDLE window in which a whole program is typed, saved as a .py file, and run all at once.
  6. Encapsulation – keeping an object’s data and its actions bundled inside the object, so other parts of a program change that data only through the actions provided.
  7. General purpose language – a programming language that is not tied to one field and can be used to build many different kinds of software.
  8. High-level language – a programming language written in terms of the problem being solved rather than the machine it runs on.
  9. Inheritance – building a new class from an existing one, keeping its details and actions and adding more.
  10. Integrated Development and Learning Environment (IDLE) – the environment installed along with Python, used to type, run and test Python code.
  11. Interactive window – the Python shell as used in IDLE, where one line is typed and carried out at a time.
  12. Interpreter – software that reads a program one line at a time, converts each line and gets the computer to carry it out.
  13. Library – a collection of ready-written, tested code that a program can use instead of writing that part itself.
  14. Low-level language – a programming language that stays close to the processor, working with its own instructions and memory addresses.
  15. Machine language – the instructions a processor can carry out directly, written as patterns of 0 and 1.
  16. Object – one item built from a class, with its own values filled in.
  17. Object-oriented programming (OOP) – a way of writing programs in which data and the actions that work on that data are kept together in one unit.
  18. Open source – published so that anyone may read, use and improve the code it is built from.
  19. Polymorphism – allowing the same action name to work on different kinds of objects, each doing what suits it.
  20. Program – a set of instructions, written in a programming language, telling a computer how to do a particular job.
  21. Programming language – a set of words and rules used to write instructions that a computer can be made to carry out.
  22. Prompt – the sign shown by a program to say it is waiting for you to type something; in Python it is >>>.
  23. Python – a free, high-level, general purpose, object-oriented programming language, first released in 1991.
  24. Python shell – a window in which one Python instruction is typed at a time and its result is shown immediately.
  25. Read-evaluate-print loop (REPL) – the repeating cycle in which the shell reads a line, works out what it produces, prints the result, and waits again.
  26. Syntax – the rules that say how instructions in a language must be written.

12.9 Objective Questions

  1. (Python was first released to the public in the year)

    1. 1989
    2. 1991
    3. 2000
    4. 2008
  2. (Which of these is true of a high-level language?)

    1. The programmer works directly with memory addresses.
    2. Instructions are written as patterns of 0 and 1.
    3. Instructions use words close to plain English.
    4. The program will run on only one make of computer.
  3. (Which of these is not an advantage of Python?)

    1. It is free and open source.
    2. It runs faster than a low-level language.
    3. It runs on Windows, macOS and Linux.
    4. Its syntax is short and readable.
  4. (Fill in the blank: the >>> mark shown by the Python shell is called the ________.)

  5. (Fill in the blank: a collection of ready-written, tested code that your program can use instead of writing that part itself is called a ________.)

  6. (State whether true or false: a Python program written on a Windows computer normally has to be rewritten before it will run on Linux.)

  7. (Match each library in Column A with the work it is used for in Column B.)

    Column A Column B
    a. Django i. Getting useful information out of pictures and video
    b. pandas ii. Building simple two-dimensional games
    c. OpenCV iii. The behind-the-scenes half of a website
    d. Pygame iv. Loading, sorting and exploring large sets of records
  8. (You type 12 * 12 at the prompt in the interactive window and press Enter. Write exactly what appears on the next line.)

12.10 Concept Questions

  1. (Define a programming language and a program, and state in one sentence how the two differ.)

  2. (A processor cannot carry out a Python program as it stands. Explain why, and describe what the interpreter does about it.)

  3. (Give three reasons why Python is described as a high-level language, and state one thing you give up by working at that level.)

  4. (Explain what a class is and what an object is, using an example of your own that has not been used in this chapter.)

  5. (Write the two lines you would put in a saved Python program to display the square root of 225, and state exactly what would be displayed when the program is run.)

  6. (A student types the single line 9 * 9 into the editor window, saves the file and runs it. Nothing appears on the screen. Explain why this happens, and state what the line should be changed to.)

  7. (Python is called a general purpose language. Explain what this means, and give one situation in which another language would still be the better choice.)

12.11 Case-Based Questions

  1. (A stationery shop near a school keeps a handwritten record of how many notebooks it sells each day. The owner wants to know the weekly total, the daily average, and the busiest day, and she wants this every week without redoing the sums by hand. Her daughter, who has just learned some Python, offers to help. One week’s record is shown in Table 12.3.)

Table 12.3 – notebooks sold on each day of one week | Day | Notebooks sold | |—|—| | Monday | 42 | | Tuesday | 38 | | Wednesday | 51 | | Thursday | 47 | | Friday | 60 |

  1. Read the table and state which day was the busiest.
  2. Give two features of Python that make it well suited to a job of this kind, and explain each in one sentence.
  3. The daughter first wants to check that one instruction gives the answer she expects, and then wants to write the finished program so it can be used again next week. Say which IDLE window she should use for each of these two steps, and why.
  1. (A school plans a system that looks at last year’s test records and marks out the students who may need extra help in mathematics. The teachers want the system built in Python. The records available cover only the students who sat every test that year.)

    1. Name two areas of artificial intelligence work described in this chapter for which Python is commonly used, and say what each involves.
    2. Explain one fairness problem that could arise from building the system on these particular records, and state what the school should do about it.
    3. Being general purpose, Python could later be used to add a web page for teachers to view the results. Explain what “general purpose” means and why it helps here.