Guido van Rossum invented the Python programming language in the early 1990s. Python is a high-level, general-purpose programming language for solving problems on modern computer systems. The language and many supporting tools are free, and Python programs can run on any operating system. You can download Python, its documentation, and related materials from www.python.org. Instructions for downloading and installing Python are in Appendix A. In this section, we show you how to create and run simple Python programs.
Running Code in the Interactive Shell
Python is an interpreted language, and you can run simple Python expressions and state- ments in an interactive programming environment called the shell. The easiest way to open a Python shell is to launch the IDLE (Integrated DeveLopment Environment). This is an integrated program development environment that comes with the Python installation.
When you do this, a window named python Shell opens. Figure 1-6 shows a shell window on macOS. A shell window running on a Windows system or a Linux system should look similar, if not identical, to this one. Note that the version of Python appearing in this
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
23 Getting Started with Python Programming
A shell window contains an opening message followed by the special symbol >>>, called a shell prompt. The cursor at the shell prompt waits for you to enter a Python command.
Note that you can get immediate help by entering help at the shell prompt or selecting Help from the window’s drop-down menu.
When you enter an expression or statement, Python evaluates it and displays its result, if there is one, followed by a new prompt. The next few lines show the evaluation of several expressions and statements.
>>> 3 + 4 # Simple arithmetic 7
>>> 3 # The value of 3 is
3
>>> "Python is really cool!" # Use a string for text 'Python is really cool!'
>>> name = "Ken Lambert" # Give a variable a value
>>> name # The value of name is
'Ken Lambert'
>>> "Hi there, " + name # Create some new text 'Hi there, Ken Lambert'
>>> print('Hi there') # Output some text Hi there
>>> print("Hi there,", name) # Output two values Hi there, Ken Lambert
Note the use of colors in the Python code. The IDLE programming environment uses color- coding to help the reader pick out different elements in the code. In this example, the items within quotation marks are in green, the names of standard functions are in purple, program comments are in red, and the responses of IDLE to user commands are in blue. The remaining code is in black. Table 1-1 lists the color-coding scheme used in all program code in this book.
Figure 1-6 Python shell window
screenshot is 3.6.1. This book assumes that you will use Python 3 rather than Python 2.
There are substantial differences between the two versions, and many examples used in this book will not work with Python 2.
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
24
The Python shell is useful for experimenting with short expressions or statements to learn new features of the language, as well as for consulting documentation on the language. To quit the Python shell, you can either select the window’s close box or press the Control1D key combination.
The means of developing more complex and interesting programs are examined in the rest of this section.
Input, Processing, and Output
Most useful programs accept inputs from some source, process these inputs, and then finally output results to some destination. In terminal-based interactive programs, the input source is the keyboard, and the output destination is the terminal display. The Python shell itself is such a program; its inputs are Python expressions or statements. Its processing evaluates these items. Its outputs are the results displayed in the shell.
The programmer can also force the output of a value by using the print function. The sim- plest form for using this function looks like the following:
print(<expression>)
This example shows you the basic syntax (or grammatical rule) for using the print func- tion. The angle brackets (the < and > symbols) enclose a type of phrase. In actual Python code, you would replace this syntactic form, including the angle brackets, with an example of that type of phrase. In this case, <expression> is shorthand for any Python expression, such as 3 + 4.
Color type of element examples
Black Inputs in the IDLE shell Numbers
Operator symbols
Variable, function, and method references Punctuation marks
67, +, name, y = factorial(x)
Blue Outputs in the IDLE shell
Function, class, and method names in definitions
'Ken Lambert', def factorial(n)
Green Strings "Ken Lambert"
Orange Keywords def, if, while
Purple Built-in function names abs, round, int
Red Program comments
Error messages in the IDLE shell # Output the results
ZeroDivisionError: division by zero
table 1-1 Color-coding of Python program elements in IDLE
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
25 Getting Started with Python Programming
When running the print function, Python first evaluates the expression and then displays its value. In the example shown earlier, print was used to display some text. The following is another example:
>>> print ("Hi there") Hi there
In this example, the text "Hi there" is the text that we want Python to display. In program- ming terminology, this piece of text is referred to as a string. In Python code, a string is always enclosed in quotation marks. However, the print function displays a string without the quotation marks.
You can also write a print function that includes two or more expressions separated by commas. In such a case, the print function evaluates the expressions and displays their results, separated by single spaces, on one line. The syntax for a print statement with two or more expressions looks like the following:
print(<expression>,..., <expression>)
Note the ellipsis (...) in this syntax example. The ellipsis indicates that you could include multiple expressions after the first one. Whether it outputs one or multiple expressions, the
print function always ends its output with a newline. In other words, it displays the values of the expressions, and then it moves the cursor to the next line on the console window.
To begin the next output on the same line as the previous one, you can place the expression
end = "", which says “end the line with an empty string instead of a newline,” at the end of the list of expressions, as follows:
print(<expression>, end = "")
As you create programs in Python, you’ll often want your programs to ask the user for input. You can do this by using the input function. This function causes the program to stop and wait for the user to enter a value from the keyboard. When the user presses the return or enter key, the function accepts the input value and makes it available to the pro- gram. A program that receives an input value in this manner typically saves it for further processing.
The following example receives an input string from the user and saves it for further pro- cessing. The user’s input is in black.
>>> name = input("Enter your name: ") Enter your name: Ken Lambert
>>> name 'Ken Lambert'
>>> print(name) Ken Lambert
>>>
The input function does the following:
1. Displays a prompt for the input. In this example, the prompt is "Enter your name: ". 2. Receives a string of keystrokes, called characters, entered at the keyboard and
returns the string to the shell.
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
26
How does the input function know what to use as the prompt? The text in parenthe- ses, "Enter your name: ", is an argument for the input function that tells it what to use for the prompt. An argument is a piece of information that a function needs to do its work.
The string returned by the function in our example is saved by assigning it to the variable
name. The form of an assignment statement with the input function is the following:
<variable identifier> = input(<a string prompt>)
A variable identifier, or variable for short, is just a name for a value. When a variable receives its value in an input statement, the variable then refers to this value. If the user enters the name "Ken Lambert" in our last example, the value of the variable name can be viewed as follows:
>>> name 'Ken Lambert'
The input function always builds a string from the user’s keystrokes and returns it to the program. After inputting strings that represent numbers, the programmer must con- vert them from strings to the appropriate numeric types. In Python, there are two type conversion functions for this purpose, called int (for integers) and float (for floating- point numbers). The next session inputs two integers and displays their sum:
>>> first = int(input("Enter the first number: ")) Enter the first number: 23
>>> second = int(input("Enter the second number: ")) Enter the second number: 44
>>> print("The sum is", first + second) The sum is 67
Note that the int function is called with each result returned by the input function. The two numbers are added, and then their sum is output. Table 1-2 summarizes the functions introduced in this subsection.
Function What It Does
float(<a string of digits>) Converts a string of digits to a floating-point value.
int(<a string of digits>) Converts a string of digits to an integer value.
input(<a string prompt>) Displays the string prompt and waits for keyboard input.
Returns the string of characters entered by the user.
print(<expression>, ...,<expression>)
Evaluates the expressions and displays them, separated by one space, in the console window.
<string 1> + <string 2> Glues the two strings together and returns the result.
table 1-2 Basic Python functions for input and output
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
27 Getting Started with Python Programming
Editing, Saving, and Running a Script
While it is easy to try out short Python expressions and statements interactively at a shell prompt, it is more convenient to compose, edit, and save longer, more complex programs in files. We can then run these program files or scripts either within IDLE or from the operat- ing system’s command prompt without opening IDLE. Script files are also the means by which Python programs are distributed to others. Most important, as you know from writ- ing term papers, files allow you to save, safely and permanently, many hours of work.
To compose and execute programs in this manner, you perform the following steps:
1. Select the option New Window from the File menu of the shell window.
2. In the new window, enter Python expressions or statements on separate lines, in the order in which you want Python to execute them.
3. At any point, you may save the file by selecting File/Save. If you do this, you should use a . py extension. For example, your first program file might be named myprogram.py.
4. To run this file of code as a Python script, select Run Module from the Run menu or press the F5 key.
The command in Step 4 reads the code from the saved file and executes it. If Python exe- cutes any print functions in the code, you will see the outputs as usual in the shell window.
If the code requests any inputs, the interpreter will pause to allow you to enter them. Oth- erwise, program execution continues invisibly behind the scenes. When the interpreter has finished executing the last instruction, it quits and returns you to the shell prompt.
Figure 1-7 shows an IDLE window containing a complete script that prompts the user for the width and height of a rectangle, computes its area, and outputs the result:
Figure 1-7 Python script in an IDLE window
When the script is run from the IDLE window, it produces the interaction with the user in the shell window shown in Figure 1-8.
This can be a slightly less interactive way of executing programs than entering them directly at Python’s interpreter prompt. However, running the script from the IDLE window will allow you to construct some complex programs, test them, and save them in program libraries that you can reuse or share with others.
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
28
Behind the Scenes: How Python Works
Whether you are running Python code as a script or interactively in a shell, the Python interpreter does a great deal of work to carry out the instructions in your program. This work can be broken into a series of steps, as shown in Figure 1-9.
Figure 1-8 Interaction with a script in a shell window
Figure 1-9 Steps in interpreting a Python program Python code
User inputs Other error messages
Syntax error messages
Program outputs Byte code
Syntax Checker and Translator
Python Virtual Machine (PVM)
1. The interpreter reads a Python expression or statement, also called the source code, and verifies that it is well formed. In this step, the interpreter behaves like a strict English teacher who rejects any sentence that does not adhere to the gram- mar rules, or syntax, of the language. As soon as the interpreter encounters such an error, it halts translation with an error message.
2. If a Python expression is well formed, the interpreter then translates it to an equiva- lent form in a low-level language called byte code. When the interpreter runs a script, it completely translates it to byte code.
3. This byte code is next sent to another software component, called the python virtual machine (pVM), where it is executed. If another error occurs during this step, execution also halts with an error message.
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
29