Introduction to Python Programming
Total Page:16
File Type:pdf, Size:1020Kb
2 Introduction to Python Programming Objectives • To understand a typical Python program-development environment. • To write simple computer programs in Python. • To use simple input and output statements. • To become familiar with fundamental data types. • To use arithmetic operators. • To understand the precedence of arithmetic operators. • To write simple decision-making statements. High thoughts must have high language. Aristophanes Our life is frittered away by detail…Simplify, simplify. Henry Thoreau My object all sublime I shall achieve in time. W.S. Gilbert 74 Introduction to Python Programming Chapter 2 Outline 2.1 Introduction 2.2 Simple Program: Printing a Line of Text 2.3 Another Simple Program: Adding Two Integers 2.4 Memory Concepts 2.5 Arithmetic 2.6 String Formatting 2.7 Decision Making: Equality and Relational Operators 2.8 Indentation 2.9 Thinking About Objects: Introduction to Object Technology Summary • Terminology • Self-Review Exercises • Answers to Self-Review Exercises • Exercises 2.1 Introduction Learning the Python language using Python How to Program facilitates a structured and disciplined approach to computer-program design. In this first programming chapter, we introduce Python programming and present several examples that illustrate important fea- tures of the language. To understand each example, we analyze the code one statement at a time. After presenting basic concepts in Chapters 2–3, we examine the structured program- ming approach in Chapters 4–6. At the same time we explore introductory Python topics, we also begin our discussion of object-oriented programming because of the central impor- tance object-oriented programming takes throughout this text. For this reason, we conclude this chapter with Section 2.9, Thinking About Objects. 2.2 Simple Program: Printing a Line of Text1 Python uses notations that may appear strange to non-programmers. To familiarize readers with these notations, we consider a simple program that prints a line of text. Figure 2.1 il- lustrates the program and its screen output. 1 # Fig. 2.1: fig02_01.py 2 # A first program in Python 3 4 print "Welcome to Python!" Welcome to Python! Fig. 2.1 Text-printing program. 1. The resources for this book, including step-by-step instructions on installing Python on Windows and Unix/Linux platforms are posted at www.deitel.com. Chapter 2 Introduction to Python Programming 75 This first program illustrates several important features of the Python language. Let us consider each line of the program. Both lines 1 and 2 begin with the pound symbol (#), which indicates a comment. Programmers insert comments to document programs and to improve program readability. Comments also help other programmers read and understand your program. A comment that begins with # is called a single-line comment, because the comment terminates at the end of the current line. The comment text A first program in Python describes the purpose of the program (line 2). Good Programming Practice 2.1 Place comments throughout a program. Comments help other programmers understand the program, assist in debugging a program (i.e., discovering and removing errors in a pro- gram) and list useful information. Comments also help you understand your own coding when you revisit a document for modifications or updates. 2.1 The Python print command instructs the computer to display the string of characters contained between the quotation marks (line 4). A string is a Python data type that contains a sequence of characters. The entire line is called a statement. In other programming lan- guages, like C++ and Java, statements must end with a semicolon. In Python, most state- ments end when the lines end. Output (displays information) and input (receives information) in Python are accom- plished with streams of characters (continuous rows of characters). Thus, when the pre- ceding statement is executed, it sends the stream of characters Welcome to Python! to the standard output stream. Standard output stream is the information presented to the user by an application—which is typically displayed on the screen by may be printed on a printer, written to a file, etc. Python statements can be executed in two ways. The first is by typing statements into a file (as in Fig. 2.1) to create a program and saving the file with a .py extension. Python files typically end with .py, although other extensions (e.g., .pyw on Windows) can be used. The Python interpreter, which executes (runs) the program, is then invoked (called) on the file by typing python file.py at the DOS or Unix shell command line, in which file is the name of the Python file. The shell command line is a text “terminal” in which the user can type commands that cause the computer system to respond. [Note: To invoke Python, the system path variable must be set properly to include the python executable, a file containing a program that can be run. The resources for this book posted at our Web site—www.deitel.com—include in- structions on how to set the appropriate variable.] When the Python interpreter runs a program stored in the file, the interpreter starts at the first line of the file and executes statements until the end of the file. The output box in Fig. 2.1 contains the results of the Python interpreter running fig02_01.py. The second way to execute Python statements is interactively. Typing python at the shell command line runs the Python interpreter in interactive mode. With this mode, the programmer types statements directly to the interpreter, which executes these state- ments one at a time. 76 Introduction to Python Programming Chapter 2 Testing and Debugging Tip 2.1 In interactive mode, Python statements are entered and interpreted one at a time. This mode often is useful when debugging a program. 2.1 Testing and Debugging Tip 2.2 When Python is invoked on a file, the interpreter exits after the last statement in the file has been executed. However, invoking Python on a file using the -i flag (e.g., python -i file.py) causes the interpreter to enter interactive mode after running the file. This is use- ful when debugging a program (e.g., for checking variable values). 2.2 Figure 2.2 shows Python 2.2 running in interactive mode on Windows. The first two lines display information about the version of Python being used. The third line contains the Python prompt (>>>). A Python statement is interpreted when a developer types a state- ment at the Python prompt and presses the Enter key (sometimes called the Return key). Python 2.2b1 (#25, Oct 19 2001, 11:44:52) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> print "Welcome to Python!" Welcome to Python! >>> ^Z Fig. 2.2 Python in interactive mode. (Copyright © 2001 Python Software Foundation.) The print statement on the third line prints the text Welcome to Python! to the screen. After printing the text to the screen, the interpreter waits for the user to enter the next statement. We exit Python by typing the Ctrl-Z end-of-file character (on Microsoft Windows systems) and pressing the Enter key. Figure 2.3 lists the keyboard combinations for the end-of-file character for various computer systems. Computer system Keyboard combination UNIX/Linux systems Ctrl-D (on a line by itself) DOS/Windows Ctrl-Z (sometimes followed by pressing Enter) Macintosh Ctrl-D VAX (VMS) Ctrl-Z Fig. 2.3 End-of-file key combinations for various popular computer systems. The string "Welcome to Python!" can be printed several ways. For example, Fig. 2.4 uses two print statements (lines 4–5), yet produces identical output to the pro- gram in Fig. 2.1. Line 4 prints the string "Welcome" to the screen. Normally, a string fol- lowing a print statement begins on a new line, below the previous string. The comma (,) at the end of line 4, however, tells Python not to begin a new line but instead to add a space Chapter 2 Introduction to Python Programming 77 after the string, and the next string printed to the screen (line 5) appears on the same line as the string "Welcome" 1 # Fig. 2.4: fig02_04.py 2 # Printing a line with multiple statements 3 4 print "Welcome", 5 print "to Python!" Welcome to Python! Fig. 2.4 Printing on one line with separate statements using print. Python offers special characters that perform certain tasks, such as backspace and car- riage return. A special character is formed by combining the backslash (\) character, also called the escape character, with any letter. When a backslash exists in a string of charac- ters, the backslash and the character immediately following the backslash form an escape sequence. An example of an escape sequence is \n, or newline. Each occurrence of the \n escape sequence causes the screen cursor to move to the beginning of the next line. To print a blank line, simply place two newline characters back-to-back. Figure 2.5 illustrates the use of the \n escape sequence; notice that the escape sequence is not printed to the screen. Figure 2.6 lists other common escape sequences. 1 # Fig. 2.5: fig02_05.py 2 # Printing multiple lines with a single statement 3 4 print "Welcome\nto\n\nPython!\n" Welcome to Python! Fig. 2.5 Printing on multiple lines with a single statement using print. Escape Sequence Description \n Newline. Move the screen cursor to the beginning of the next line. \t Horizontal tab. Move the screen cursor to the next tab stop. \r Carriage return. Move the screen cursor to the beginning of the cur- rent line; do not advance to the next line.