How Does a Computer Run a Python Program?

In order to understand what happens when you’re programming, it helps to have have a mental model of how a computer executes a program.

The computer is assembled from pieces of hardware, including a processor that can execute instructions and do arithmetic, a place to store data such as a hard drive, and various other pieces, such as a screen, a keyboard, an Ethernet controller for connecting to a network, and so on.

To deal with all these pieces, every computer runs some kind of operating system, such as Microsoft Windows, Linux, or macOS. An operating system, or OS, is a program; what makes it special is that it’s the only program on the computer that’s allowed direct access to the hardware. When any other application (such as your browser, a spreadsheet program, or a game) wants to draw on the screen, find out what key was just pressed on the keyboard, or fetch data from storage, it sends a request to the OS (see the top image).

images/basic/os.png

This may seem like a roundabout way of doing things, but it means that only the people writing the OS have to worry about the differences between one graphics card and another and whether the computer is connected to a network through Ethernet or wireless. The rest of us—everyone analyzing scientific data or creating 3D virtual chat rooms—only have to learn our way around the OS, and our programs will then run on thousands of different kinds of hardware.

Today, it’s common to add another layer between the programmer and the computer’s hardware. When you write a program in Python, Java, or Visual Basic, it doesn’t run directly on top of the OS. Instead, another program, called an interpreter or virtual machine, takes your program and runs it for you, translating your commands into a language the OS understands. It’s a lot easier, more secure, and more portable across operating systems than writing programs directly on top of the OS:

images/basic/os2.png

There are two ways to use the Python interpreter. One is to tell it to execute a Python program that is saved in a file with a .py extension. Another is to interact with it in a program called a shell, where you type statements one at a time. The interpreter will execute each statement when you type it, do what the statement says to do, and show any output as text, all in one window. We will explore Python in this chapter using a Python shell.

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

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