Introduction to Python Programming

Similar documents
Introduction to C++ Programming Pearson Education, Inc. All rights reserved.

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Programming for Engineers Introduction to C

C: How to Program. Week /Mar/05

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator

Chapter 2 - Introduction to C Programming

IT 374 C# and Applications/ IT695 C# Data Structures

2.5 Another Application: Adding Integers

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Chapter 1 Introduction to Computers and C++ Programming

by Pearson Education, Inc. All Rights Reserved. 2

Chapter 2 Author Notes

Full file at C How to Program, 6/e Multiple Choice Test Bank

Chapter 2, Part III Arithmetic Operators and Decision Making

Introduction to Java Applications; Input/Output and Operators

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Full file at

JavaScript: Introduction to Scripting

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Introduction to Programming

Introduction to C++ Programming. Adhi Harmoko S, M.Komp

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Fundamentals of Programming. Lecture 3: Introduction to C Programming

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Fundamentals of Programming Session 4

UNIT- 3 Introduction to C++

2.8. Decision Making: Equality and Relational Operators

Full file at

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Fundamental of Programming (C)

Bits, Words, and Integers

Program Elements -- Introduction

Variables and Literals

Chapter 1 & 2 Introduction to C Language

Introduction to C# Applications

Introduction to C# Applications Pearson Education, Inc. All rights reserved.

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Reserved Words and Identifiers

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Objectives. In this chapter, you will:

Maciej Sobieraj. Lecture 1

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

CMPT 125: Lecture 3 Data and Expressions

Chapter 2, Part I Introduction to C Programming

Chapter 2 Basic Elements of C++

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Visual C# Instructor s Manual Table of Contents

JavaScript: Introductionto Scripting

Chapter 17. Fundamental Concepts Expressed in JavaScript

ANSI C Programming Simple Programs

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

9. Elementary Algebraic and Transcendental Scalar Functions

Work relative to other classes

Introduction to Java Applications

4. Inputting data or messages to a function is called passing data to the function.

Chapter 3: Operators, Expressions and Type Conversion

Unit 3. Operators. School of Science and Technology INTRODUCTION

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

4 Programming Fundamentals. Introduction to Programming 1 1

CS112 Lecture: Working with Numbers

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

Chapter 2: Introduction to C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Data Types and Variables in C language

2.2 Syntax Definition

The C++ Language. Arizona State University 1

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

CPS122 Lecture: From Python to Java

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Chapter 2 Working with Data Types and Operators

CS102: Variables and Expressions

Overview of C. Basic Data Types Constants Variables Identifiers Keywords Basic I/O

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

Chapter Two PROGRAMMING WITH NUMBERS AND STRINGS

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

1. What type of error produces incorrect results but does not prevent the program from running? a. syntax b. logic c. grammatical d.

DECLARATIONS. Character Set, Keywords, Identifiers, Constants, Variables. Designed by Parul Khurana, LIECA.

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

Number Systems CHAPTER Positional Number Systems

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

Variables, Constants, and Data Types

Arithmetic Expressions in C

PYTHON. Values and Variables

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Lecture 3 Tao Wang 1

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

A variable is a name for a location in memory A variable must be declared

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Lecture 2 Tao Wang 1

Programming Lecture 3

Transcription:

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 features 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 programming 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 importance 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 Text 1 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 illustrates 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 program) 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 languages, like C++ and Java, statements must end with a semicolon. In Python, most statements end when the lines end. Output (displays information) and input (receives information) in Python are accomplished with streams of characters (continuous rows of characters). Thus, when the preceding 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 instructions 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 statements 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 useful 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 statement 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 UNIX/Linux systems DOS/Windows Macintosh VAX (VMS) Keyboard combination Ctrl-D (on a line by itself) Ctrl-Z (sometimes followed by pressing Enter) Ctrl-D 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 program in Fig. 2.1. Line 4 prints the string "Welcome" to the screen. Normally, a string following 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 carriage 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 characters, 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 current line; do not advance to the next line. Fig. 2.6 Some common escape sequences (part 1 of 2).

78 Introduction to Python Programming Chapter 2 Escape Sequence Description \b Backspace. Move the screen cursor back one space. \a Alert. Sound the system bell. \\ Backslash. Print a backslash character. \" Double quote. Print a double quote character. \' Single quote. Print a single quote character. Fig. 2.6 Some common escape sequences (part 2 of 2). 2.3 Another Simple Program: Adding Two Integers Our next program invokes Python functions raw_input and int to obtain two integers entered by a user at a keyboard. The program then computes the sum of these values and outputs the result using print. Figure 2.7 contains the program and its output. 1 # Fig. 2.7: fig02_07.py 2 # Simple addition program 3 4 # prompt user for input 5 integer1 = raw_input( "Enter first integer:\n" ) # read string 6 integer1 = int( integer1 ) # convert string to integer 7 8 integer2 = raw_input( "Enter second integer:\n" ) # read string 9 integer2 = int( integer2 ) # convert string to integer 10 11 sum = integer1 + integer2 # compute and assign sum 12 13 print "Sum is", sum # print sum Enter first integer: 5 Enter second integer: 27 Sum is 32 Fig. 2.7 Addition program. The comments in lines 1 2 state the name of the file and the purpose of the program. Line 5 calls Python s built-in function raw_input to request user input. A built-in function is a piece of code provided by Python that performs a task. The task is performed by calling the function writing the function name, followed by parentheses (()). After performing its task, a function may return a value that represents the result of the task. Python function raw_input takes the argument, "Enter first integer:\n" that requests user input. An argument is a value that a function accepts and uses to perform its task. In this case, function raw_input accepts the prompt argument (that requests user input) and prints that prompt to the screen. The user enters a number and presses the

Chapter 2 Introduction to Python Programming 79 Enter key. After the user presses the Enter key, the number is sent to function raw_input in the form of a string. The result of raw_input (a string containing the characters typed by the user) is given to variable (or, identifier) integer1 using the assignment statement, =. In Python, variables are simply names that identify objects (containers that store given values). A variable name (e.g., integer1) consists of letters, digits and underscores (_) that does not begin with a digit. Python is case sensitive uppercase and lowercase letters are different, so a1 and A1 are different variables. An object can have multiple variable names. The statement (line 5) is read as integer1 references the value returned by raw_input( "Enter first integer:\n" ). Good Programming Practice 2.2 Choosing meaningful variable names helps a program to be self-documenting, i.e., it is easier to understand the program simply by reading it rather than having to read manuals or use excessive comments. 2.2 Good Programming Practice 2.3 Avoid identifiers that begin with underscores and double underscores because the Python interpreter or other Python code may reserve those characters for internal use. This prevents names you choose from being confused with names the interpreter chooses. This avoids confusion between user-defined identifiers and interpreter-defined identifiers. 2.3 In addition to a name and value, each object has a type. An object s type describes the object s format (e.g., integer, string, etc.) which identifies the kind of information stored in the object. Integers are whole numbers that encompass negative numbers (-14), zero (0) and positive numbers (6). In languages like C++ and Java, the programmer must declare (state) the object type before using the object in the program. However, Python uses dynamic typing, which determines an object s type during program execution. For example, if object a is initialized to 2, then the object is of type integer (because the number 2 is an integer). Similarly, if object b is initialized to "Python", then the object is of type string. Function raw_input returns values of type string, so the object referenced by integer1 (line 5) is of type string. To perform integer addition on the value referenced by integer1, the program must convert the string value to an integer value. Python function int (line 6) converts a noninteger value to an integer value and returns the new value. If we do not obtain an integer value for variable integer1, we will not achieve the desired results the program would concatenate (merge) two strings instead of adding two integers (Fig. 2.8).

80 Introduction to Python Programming Chapter 2 Python 2.2b1 (#25, Oct 19 2001, 11:44:52) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> value1 = raw_input( "Enter an integer: " ) Enter an integer: 2 >>> value2 = raw_input( "Enter an integer: " ) Enter an integer: 4 >>> print value1 + value2 24 Fig. 2.8 Adding values from raw_input without converting to integers. (Copyright 2001 Python Software Foundation.) The assignment statement (line 11 of Fig. 2.7) calculates the sum of the variables integer1 and integer2 and assigns the result to variable sum using the assignment symbol =. The statement is read as, sum gets the value of integer1 + integer2. Most calculations are performed through assignment statements. The + symbol is an operator a special symbol that performs a specific operation. In this case, the + operator performs addition. The + operator is called a binary operator, because it receives two operands (values) on which it performs its operation. In this example, the operands are integer1 and integer2. Good Programming Practice 2.4 Place spaces on either side of a binary operator or symbol. This makes the operator or symbol stand out and create a more easily readable program. 2.4 Line 14 displays the string "Sum is" followed by the numerical value of variable sum. Items we want to output are separated by commas (,). Note that the print statement outputs multiple values of different types. Python knows how to convert each piece of data to a string before outputting it. Calculations also can be performed in output statements. We could have combined the statements in lines 11 and 13 into the statement print "Sum is", integer1 + integer2 thus eliminating the need for variable sum. A powerful feature of Python is that users can create their own data types. (We explore this capability in Chapter 7, Classes and Data Abstraction.) Users can then teach Python how to output values of these new data types using the print statement. (This is accomplished through method overriding a topic we explore in Chapter 8, Customizing Classes.) 2.4 Memory Concepts Variable names such as integer1, integer2 and sum actually correspond to Python objects. Every object has a type, a size, a value and a location in the computer s memory.

Chapter 2 Introduction to Python Programming 81 A program cannot change an object s type or location. Some object types permit programmers to change the object s value. We discuss these types beginning in Chapter 5, Tuples, Lists and Dictionaries. When the addition program in Fig. 2.7, executes the statement integer1 = raw_input( "Enter first integer:\n" ) Python first creates an object to hold the user-entered string and places the object into a memory location. The = assignment symbol then binds the name integer1 to the newly created object. Suppose the user enters 45 at the raw_input prompt. Python places "45" into a memory location to which the name integer1 is bound, as shown in Fig. 2.9. integer1 "45" Fig. 2.9 Memory location showing value of a variable and the name bound to the value. When the statement integer1 = int( integer1 ) is executed, function int creates a new object to store the integer value 45. This integer object is contained in a new memory location, and Python binds the name integer1 to this new memory location (Fig. 2.10). Variable integer1 no longer refers to the memory location that contains the string value "45". We demonstrate this at the end of this section. "45" integer1 45 Fig. 2.10 Memory location showing the name and value of a variable. Returning to our addition program, when the statements integer2 = raw_input( "Enter second integer:\n" ) integer2 = int( integer2 ) are executed, suppose the user enters the value "72". This value is converted to the integer value 72 by the second line, placed into a memory location to which integer2 is bound, and memory appears as in Fig. 2.11. Note that these locations are not necessarily adjacent locations in memory.

82 Introduction to Python Programming Chapter 2 integer1 45 integer2 72 Fig. 2.11 Memory locations after values for two variables have been input. Once the program has obtained values for integer1 and integer2, it adds these values and assigns the sum to variable sum. The statement sum = integer1 + integer2 that performs the addition causes memory to appear as in Fig. 2.12. Note that the values of integer1 and integer2 appear exactly as they did before they were used in the calculation of sum. These values were used, but not destroyed, as the computer performed the calculation. Thus, when a value is read out of a memory location, the process is nondestructive. integer1 45 integer2 72 sum 117 Fig. 2.12 Memory locations after a calculation. In Fig. 2.13, the program demonstrates that each Python object has a location, a type and a value and that these properties are accessed through an object s name. This program is identical to the program in Fig. 2.7, except that we have added statements that display the memory location, type and value for each object at various points in the program. 1 # Fig. 2.13: fig02_13.py 2 # Displaying location, type and value 3 4 # prompt the user for input 5 integer1 = raw_input( "Enter first integer:\n" ) # read a string 6 print "integer1: ", id( integer1 ), type( integer1 ), integer1 7 integer1 = int( integer1 ) # convert the string to an integer 8 print "integer1: ", id( integer1 ), type( integer1 ), integer1 9 10 integer2 = raw_input( "Enter second integer:\n" ) # read a string Fig. 2.13 Displaying an object s location and type (part 1 of 2).

Chapter 2 Introduction to Python Programming 83 11 print "integer2: ", id( integer2 ), type( integer2 ), integer2 12 integer2 = int( integer2 ) # convert the string to an integer 13 print "integer2: ", id( integer2 ), type( integer2 ), integer2 14 15 sum = integer1 + integer2 # assignment of sum 16 print "sum: ", id( sum ), type( sum ), sum Enter first integer: 5 integer1: 7962320 <type 'string'> 5 integer1: 7955860 <type 'int'> 5 Enter second integer: 27 integer2: 7962400 <type 'string'> 27 integer2: 7955440 <type 'int'> 27 sum: 7955608 <type 'int'> 32 Fig. 2.13 Displaying an object s location and type (part 2 of 2). Line 6 prints integer1 s location, type and value after the call to raw_input. Python function id returns the interpreter s representation of the variable s location. Function type returns the type of the variable. We print these values again (line 8), after converting the string value in integer1 to an integer value. Notice that both the type and the location of variable integer1 change as a result of the statement integer1 = int( integer1 ) The change underscores the fact that a program cannot change a variable s type. Instead, the statement causes Python to create a new integer value in a new location and assigns the name integer1 to this location. The location to which integer1 previously referred is no longer accessible. The remainder of the program prints the location type and value for variables integer2 and sum in a similar manner. Functions id and type are examples of Python s introspective capabilities Python s ability to provide information about itself. An advanced program might use these functions to perform the program s task. In our example, however, we use these functions only to reenforce basic facts about Python variables. 2.5 Arithmetic Many programs perform arithmetic calculations. The arithmetic operators are summarized in Fig. 2.14. Note the use of various special symbols not used in algebra. The asterisk (*) indicates multiplication, and the percent sign (%) is the modulus operator that we discuss shortly. The arithmetic operators in Fig. 2.14 are all binary operators, (i.e., operators that take two operands). For example, the expression integer1 + integer2 contains the binary operator + and the two operands integer1 and integer2.

84 Introduction to Python Programming Chapter 2 Python operation Arithmetic operator Algebraic expression Python expression Addition + f + 7 f + 7 Subtraction - p c p - c Multiplication * bm b * m Exponentiation ** x^y or x y x ** y Division / // (new in Python 2.2) x / y or or x y x / y x // y Modulus % r mod s r % s x - y Fig. 2.14 Arithmetic operators. Python is a growing language, and as such, some language features change over time. Starting with Python 2.2, the behavior of the / division operator will begin to change from floor division to true division. Floor division (sometimes called integer division), divides the numerator by the denominator and returns the highest integer value that is no more than the result. For example, dividing 7 by 4 with floor division yields 1, and dividing 17 by 5 with floor division yields 3. Note that any fractional part in floor division is simply discarded (i.e., truncated) no rounding occurs. True division yields the precise floatingpoint result of dividing the numerator by the denominator. For example, dividing 7 by 4 with true division yields 1.75. In prior versions, Python contained only one operator for division the / operator. The behavior (i.e., floor or true division) of the operator is determined by the type of the operands. If the operands are both integers, the operator performs floor division. If one or both of the operands are floating-point numbers, the operator perform true division. The language designers and many programmers disliked the ambiguity of the / operator and decided to create two operators for version 2.2 one for each type of division. The / operator performs true division, and the // operator performs floor division. However, this decision could introduce errors into programs that use older versions of Python. Therefore, the designers came up with a compromise: Starting with Python 2.2 all future 2.x versions will include two operators, but if a program author wants to use the new behavior, the programmer must state their intention explicitly with the statement from future import division After Python sees this statement, the / operator performs true division and the // operator performs floor division. Figure 2.15 contains an example.

Chapter 2 Introduction to Python Programming 85 Python 2.2b1 (#25, Oct 19 2001, 11:44:52) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> 3 / 4 # floor division (default behavior) 0 >>> 3.0 / 4.0 # true division (floating-point operands) 0.75 >>> 3 // 4 # floor division (only behavior) 0 >>> 3.0 // 4.0 # floating-point floor division 0.0 >>> from future import division >>> 3 / 4 # true division (new behavior) 0.75 >>> 3.0 / 4.0 # true division (same as before) 0.75 Fig. 2.15 Difference in behavior of the / operator. (Copyright 2001 Python Software Foundation.) We first evaluate the expression 3 / 4. This expression evaluates to the value 0, because the default behavior of the / operator with integer operands is floor division. The expression 3.0 / 4.0 evaluates to 0.75. In this case, we use floating-point operands, so the / operator performs true division. The expressions 3 // 4 and 3.0 // 4.0 evaluate to 0 and 0.0, respectively, because the // operator always performs floor division, regardless of the types of the operands. Then, we change the behavior of the / operator with the special import statement. In effect, this statement turns on the true division behavior for operator /. Now the expression 3 / 4 evaluates to 0.75. In this text, we use only the default 2.2 behavior for the / operator, namely floor division for integers and true division for floating-point numbers. In Python version 3.0 (due to be released no sooner than 2003), the / operator can perform only true division. After the release of version 3.0, programmers need to update applications to compensate for the new behavior. For more information on the change, see http://python.sourceforge.net/peps/pep-0238.html Python provides the modulus operator (%), which yields the remainder after integer division. The modulus operator usually is used only with integer operands. The expression x % y yields the remainder after x is divided by y. Thus, 7 % 4 yields 3 and 17 % 5 yields 2. In later chapters, we discuss many interesting applications of the modulus operator, such as determining whether one number is a multiple of another. (A special case of this is determining whether a number is odd or even.) Arithmetic expressions in Python must be entered into the computer in straight-line form. Thus, expressions such as a divided by b must be written as a / b, so that all constants, variables and operators appear in a straight line. The algebraic notation

86 Introduction to Python Programming Chapter 2 a -- b is generally not acceptable to compilers or interpreters, although some special-purpose software packages do exist that support more natural notation for complex mathematical expressions. Parentheses are used in Python expressions in much the same manner as in algebraic expressions. For example, to multiply a times the quantity b + c, we write a * (b + c) Python applies the operators in arithmetic expressions in a precise sequence determined by the following rules of operator precedence, which are generally the same as those followed in algebra: 1. Expressions contained within pairs of parentheses are evaluated first. Thus, parentheses may force the order of evaluation to occur in any sequence desired by the programmer. Parentheses are said to be at the highest level of precedence. In cases of nested, or embedded, parentheses, the operators in the innermost pair of parentheses are applied first. 2. Exponentiation operations are applied next. If an expression contains several exponentiation operations, operators are applied from right to left. 3. Multiplication, division and modulus operations are applied next. If an expression contains several multiplication, division and modulus operations, operators are applied from left to right. Multiplication, division and modulus are said to be on the same level of precedence. 4. Addition and subtraction operations are applied last. If an expression contains several addition and subtraction operations, operators are applied from left to right. Addition and subtraction also have the same level of precedence. Not all expressions with several pairs of parentheses contain nested parentheses. For example, the expression a * (b + c) + c * (d + e) does not contain nested parentheses. Rather, the parentheses are said to be on the same level. The rules of operator precedence enable Python to apply operators in the correct order. When we say that certain operators are applied from left to right, we are referring to the associativity of the operators. For example, in the expression a + b + c the addition operators (+) associate from left to right. We will see that some operators associate from right to left. Figure 2.16 summarizes these rules of operator precedence. This table will be expanded as additional Python operators are introduced. A complete precedence chart is included in the appendices.

Chapter 2 Introduction to Python Programming 87 Operator(s) Operation(s) Order of Evaluation (Precedence) ( ) Parentheses Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses on the same level (i.e., not nested), they are evaluated left to right. ** Exponentiation Evaluated second. If there are several, they are evaluated right to left. * / // % Multiplication Division Modulus + - Addition Subtraction Evaluated third. If there are several, they are evaluated left to right. [Note: The // operator is new in version 2.2] Evaluated last. If there are several, they are evaluated left to right. Fig. 2.16 Precedence of arithmetic operators. Now let us consider several expressions in light of the rules of operator precedence. Each example lists an algebraic expression and its Python equivalent. The following is an example of an arithmetic mean (average) of five terms: Algebra: m = a + b + c + d + e -------------------------------------- 5 Python: m = ( a + b + c + d + e ) / 5 The parentheses are required because division has higher precedence than addition. The entire quantity ( a + b + c + d + e ) is to be divided by 5. If the parentheses are erroneously omitted, we obtain a + b + c + d + e / 5, which evaluates incorrectly as e a + b + c + d + -- 5 The following is an example of the equation of a straight line: Algebra: y = mx + b Python: y = m * x + b No parentheses are required. The multiplication is applied first, because multiplication has a higher precedence than addition. The following example contains modulus (%), multiplication, division, addition and subtraction operations:

88 Introduction to Python Programming Chapter 2 Algebra: z = pr%q + w/x y Python: z = p * r % q + w / x - y 1 2 4 3 5 The circled numbers under the statement indicate the order in which Python applies the operators. The multiplication, modulus and division are evaluated first, in left-to-right order (i.e., they associate from left to right) because they have higher precedence than addition and subtraction. The addition and subtraction are applied next. These are also applied left to right. Once the expression has been evaluated, Python assigns the result to variable z. To develop a better understanding of the rules of operator precedence, consider how a second-degree polynomial is evaluated: y = a * x ** 2 + b * x + c 2 1 4 3 5 The circled numbers under the statement indicate the order in which Python applies the operators. Suppose variables a, b, c and x are initialized as follows: a = 2, b = 3, c = 7 and x = 5. Figure 2.17 illustrates the order in which the operators are applied in the preceding second-degree polynomial.

Chapter 2 Introduction to Python Programming 89 Step 1. y = 2 * 5 ** 2 + 3 * 5 + 7 5 ** 2 is 25 (Exponentiation) Step 2. y = 2 * 25 + 3 * 5 + 7 2 * 25 is 50 (Leftmost multiplication) Step 3. y = 50 + 3 * 5 + 7 3 * 5 is 15 (Multiplication before addition) Step 4. y = 50 + 15 + 7 50 + 15 is 65 (Leftmost addition) Step 5. y = 65 + 7 65 + 7 is 72 (Last addition) Step 6. y = 72 (Python assigns 72 to y) Fig. 2.17 Order in which a second-degree polynomial is evaluated. The preceding assignment statement can be parenthesized with unnecessary parentheses for clarity as y = ( a * ( x ** 2 ) ) + ( b * x ) + c Good Programming Practice 2.5 As in algebra, it is acceptable to place unnecessary parentheses in an expression to make the expression clearer. These parentheses are called redundant parentheses. Redundant parentheses are commonly used to group subexpressions in a large expression to make that expression clearer. Breaking a large statement into a sequence of shorter, simpler statements also promotes clarity. 2.5 2.6 String Formatting Now that we have investigated Python numeric values, let us turn our attention to Python strings. Unlike some other popular programming languages, Python provides strings as a

90 Introduction to Python Programming Chapter 2 basic data type, thereby enabling Python programs to perform powerful text-based operations simply. We have already learned how to create a string by placing text inside double quotes ("). Python strings can be created in a variety of other ways, as Fig. 2.18 demonstrates. 1 # Fig. 2.18: fig02_18.py 2 # Creating strings and using quote characters in strings 3 4 print "This is a string with \"double quotes.\"" 5 print 'This is another string with "double quotes."' 6 print 'This is a string with \'single quotes.\'' 7 print "This is another string with 'single quotes.'" 8 print """This string has "double quotes" and 'single quotes'. 9 You can even do multiple lines.""" 10 print '''This string also has "double" and 'single' quotes.''' This is a string with "double quotes." This is another string with "double quotes." This is a string with 'single quotes.' This is another string with 'single quotes.' This string has "double quotes" and 'single quotes'. You can even do multiple lines. This string also has "double" and 'single' quotes. Fig. 2.18 Creating Python strings. Line 4 creates a string with the familiar double-quote character ("). If we want such a string to print double quotes to the screen, we must use the escape sequence for the doublequote character, rather than the double-quote character itself. Recall from Fig. 2.6 that the escape sequence for the double-quote character is \". Strings can be created using the single-quote character ('), too (line 5). If we want to use the double-quote character inside a string created with single quotes, we do not need to use the escape character. Similarly, if we want to use a single-quote character inside a string created with double quotes, we do not need to use the escape sequence (line 7). However, if we want to use the single-quote character inside a string created with single quotes, we must use the escape sequence (line 6). Python also supports triple-quoted strings (lines 8 10). Triple-quoted strings are useful for programs that output strings with special characters such as quote characters. Single- or double-quote characters inside a triple-quoted string do not need to use the escape sequence. Triple-quoted strings also are used for large blocks of text because triplequoted strings can span multiple lines. In this book, we use triple-quoted strings when we write programs that output large blocks of text for the Web. Python strings support simple, but powerful, output formatting, not available to basic data types in some other languages. We can create strings that format output in several ways: 1. Rounding floating-point values to an indicated number of decimal places. 2. Representing floating-point numbers in exponential format.

Chapter 2 Introduction to Python Programming 91 3. Aligning a column of numbers with decimal points appearing one above the other. 4. Using right-justification and left-justification of outputs. 5. Inserting literal characters at precise locations in a line of output. 6. Displaying all types of data with fixed-size field widths and precision. The program in Fig. 2.19 demonstrates basic string-formatting capabilities. 1 # Fig. 2.19: fig02_19.py 2 # String formatting. 3 4 integervalue = 4237 5 print "Integer ", integervalue 6 print "Decimal integer %d" % integervalue 7 print "Hexadecimal integer %x\n" % integervalue 8 9 floatvalue = 123456.789 10 print "Float", floatvalue 11 print "Default float %f" % floatvalue 12 print "Default exponential %e\n" % floatvalue 13 14 print "Right justify integer (%8d)" % integervalue 15 print "Left justify integer (%-8d)\n" % integervalue 16 17 stringvalue = "String formatting" 18 print "Force eight digits in integer %.8d" % integervalue 19 print "Five digits after decimal in float %.5f" % floatvalue 20 print "Fifteen and five characters allowed in string:" 21 print "(%.15s) (%.5s)" % ( stringvalue, stringvalue ) Integer 4237 Decimal integer 4237 Hexadecimal integer 108d Float 123456.789 Default float 123456.789000 Default exponential 1.234568e+005 Right justify integer ( 4237) Left justify integer (4237 ) Force eight digits in integer 00004237 Five digits after decimal in float 123456.78900 Fifteen and five characters allowed in string: (String formatti) (Strin) Fig. 2.19 Demonstrating the string-formatting operator %. Lines 4 7 demonstrate how to represent integers in a string. Line 5 simply prints the value of variable integervalue, without string formatting. The % formatting operator inserts the value of a variable in a string (line 6). The value to the left of the operator is a string that contains one or more conversion specifiers place holders for values in the

92 Introduction to Python Programming Chapter 2 string. Each conversion specifier begins with a percent sign (%) and ends with a conversionspecifier symbol. Conversion-specifier symbol d indicates that we want to place an integer within the current string at the specified point. Figure 2.20 lists several conversion-specifier symbols for use in string formatting. [Note: See Appendix C, Number Systems, for a discussion of numeric terminology in Fig. 2.20.] Conversion Specifier Symbol Meaning c s d u o x X f Single character (i.e., a string of length one) or the integer representation of an ASCII character. String or a value to be converted to a string. Signed decimal integer. Unsigned decimal integer. Unsigned octal integer. Unsigned hexadecimal integer (using format abcdef). Unsigned hexadecimal integer (using format ABCDEF). Floating-point number. e, E Floating-point number (using scientific notation). g, G Floating-point number (using least-significant digits). Fig. 2.20 String-formatting characters. The value to the right of the % formatting operator specifies what replaces the placeholders in the strings. In line 6, we specify the value integervalue to replace the %d placeholder in the string. Line 7 inserts the hexadecimal value assigned to variable integervalue into the string. Lines 9 12 demonstrate how to insert floating-point values in a string. The f conversion specifier acts as a place holder for a floating-point value (line 11). To the right of the % formatting operator, we use variable floatvalue as the value to be displayed. The e conversion specifier acts as a place holder for a floating-point value in scientific notation. Lines 14 15 demonstrate string formatting with field widths. A field width is the exact size of a field in which a value is printed. If the field width is larger than the value being printed, the data are normally right-justified within the field. To use field widths, place an integer representing the field width between the percent sign and the conversion-specifier symbol. Line 14 right-justifies the value of variable integervalue in a field width of size eight. To left-justify a value, specify a negative integer as the field width (line 15). Lines 17 21 demonstrate string formatting with precision. Precision has different meaning for different data types. When used with integer conversion specifiers, precision indicates the minimum number of digits to be printed. If the printed value contains fewer digits than the specified precision, zeros are prefixed to the printed value until the total number of digits is equivalent to the precision. To use precision, place a decimal point (.) followed by an integer representing the precision between the percent sign and the conver-

Chapter 2 Introduction to Python Programming 93 sion specifier. Line 18 prints the value of variable integervalue with a precision of eight. When precision is used with a floating-point conversion specifier, the precision is the number of digits to appear after the decimal point. Line 19 prints the value of variable floatvalue with a precision of five. When used with a string-conversion specifier, the precision is the maximum number of characters to be written from the string. Line 21 prints the value of variable stringvalue twice once with a precision of fifteen and once with a precision of five. Notice that the conversion specifications are contained within parentheses. When the string to the left of the % formatting operator contains more than one conversion specifier, the value to the right of the operator must be a comma-separated sequence of conversion specifications. This sequence is contained within parentheses and must have the same number of conversion specifications as the string has conversion specifiers. Python constructs the string from left to right by matching a placeholder with the next value specified between parentheses and replacing the formatting character with that value. Python strings support even more powerful string-formatting capabilities through string methods. We discuss string methods in detail in Chapter 13, String Manipulation and Regular Expressions. 2.7 Decision Making: Equality and Relational Operators This section introduces a simple version of Python s if structure that allows a program to make a decision based on the truth or falsity of some condition. If the condition is true, (i.e., the condition is met), the statement in the body of the if structure is executed. If the condition is not met, the body statement is not executed. We will see an example shortly. Conditions in if structures can be formed using the equality operators and relational operators summarized in Fig. 2.21. The relational operators all have the same level of precedence and associate from left to right. All equality operators have the same level of precedence, which is lower than the precedence of the relational operators. The equality operators also associate from left to right. Common Programming Error 2.1 A syntax error occurs if any of the operators ==,!=, >= and <= appear with spaces between its pair of symbols. 2.1 Common Programming Error 2.2 Reversing the order of the pair of operators in any of the operators!=, <>, >= and <= (by writing them as =!, ><, => and =<, respectively) is a syntax error. 2.2 Standard algebraic equality operator or relational operator Python equality or relational operator Example of Python condition Meaning of Python condition Relational operators > > x > y x is greater than y Fig. 2.21 Equality and relational operators (part 1 of 2).

94 Introduction to Python Programming Chapter 2 Standard algebraic equality operator or relational operator Python equality or relational operator Example of Python condition Meaning of Python condition < < x < y x is less than y >= x >= y x is greater than or equal to y <= x <= y x is less than or equal to y Equality operators = == x == y x is equal to y!=, <> x!= y, x is not equal to y x <> y Fig. 2.21 Equality and relational operators (part 2 of 2). Common Programming Error 2.3 Confusing the equality operator == with the assignment symbol = is a common error. The equality operator should be read is equal to and the assignment symbol should be read gets, gets the value of or is assigned the value of. Some people prefer to read the equality operator as double equals. In Python, the assignment symbol causes a syntax error when used in a conditional statement. 2.3 The following example uses six if statements to compare two user-entered numbers. If the condition in any of these if statements is satisfied, the output statement associated with that if is executed. The program and three sample executions are shown in Fig. 2.22. 1 # Fig. 2.22: fig02_22.py 2 # Using if statements, relational operators and 3 # equality operators 4 5 print "Enter two integers, and I will tell you" 6 print "the relationships they satisfy." 7 8 # read first string and convert to integer 9 number1 = raw_input( "Please enter first integer: " ) 10 number1 = int( number1 ) 11 12 # read second string and convert to integer 13 number2 = raw_input( "Please enter second integer: " ) 14 number2 = int( number2 ) 15 16 if number1 == number2: 17 print "%d is equal to %d" % ( number1, number2 ) 18 19 if number1!= number2: 20 print "%d is not equal to %d" % ( number1, number2 ) 21 Fig. 2.22 Equality and relational operators used to determine mathematical relationships (part 1 of 2).

Chapter 2 Introduction to Python Programming 95 22 if number1 < number2: 23 print "%d is less than %d" % ( number1, number2 ) 24 25 if number1 > number2: 26 print "%d is greater than %d" % ( number1, number2 ) 27 28 if number1 <= number2: 29 print "%d is less than or equal to %d" % ( number1, number2 ) 30 31 if number1 >= number2: 32 print "%d is greater than or equal to %d" % ( number1, number2 ) Enter two integers, and I will tell you the relationships they satisfy. Please enter first integer: 37 Please enter second integer: 42 37 is not equal to 42 37 is less than 42 37 is less than or equal to 42 Enter two integers, and I will tell you the relationships they satisfy. Please enter first integer: 7 Please enter second integer: 7 7 is equal to 7 7 is less than or equal to 7 7 is greater than or equal to 7 Fig. 2.22 Equality and relational operators used to determine mathematical relationships (part 2 of 2). The program uses Python functions raw_input and int to input two integers (lines 8 14). First a value is obtained for variable number1, then a value is obtained for variable number2. The if structure in lines 16 17 compares the values of variables number1 and number2 to test for equality. If the values are equal, the statement displays a line of text indicating that the numbers are equal (line 17). If the conditions are met in one or more of the if structures starting at lines 19, 22, 25, 28 and 31, the corresponding print statement displays a line of text. Each if structure consists of the word if, the condition to be tested and a colon (:). An if structure also contains a body. Notice that each if structure in Fig. 2.22 has a single statement in its body and that each body is indented. Some languages, like C++ and Java, use braces ( { } ) to denote the body of if structures; Python requires indentation. We discuss indentation in the next section. Common Programming Error 2.4 Forgetting the colon (:) in an if structure causes a syntax error. 2.4

96 Introduction to Python Programming Chapter 2 Common Programming Error 2.5 Forgetting to indent the body of an if structure causes a syntax error. 2.5 Good Programming Practice 2.6 Set a convention for the size of indent you prefer, then apply that convention uniformly. The tab key may create indents, but tab stops may vary. We recommend using three spaces to form a level of indent. However, the Python style guide recommends using four spaces. 2.6 In Python, syntax evaluation is dependent on white space, thus, the inconsistent use of white space can cause syntax errors. For instance, splitting a statement over multiple lines can result in a syntax error. If a statement is long, the statement can be spread over multiple lines using the \ line-continuation character (Fig. 2.23). Some interpreters use "..." to denote a continuing line. 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 1 + File "<stdin>", line 1 print 1 + ^ SyntaxError: invalid syntax >>> print 1 + \... 2 3 >>> Fig. 2.23 Demonstrating the \ line-continuation character. (Copyright 2001 Python Software Foundation.) Good Programming Practice 2.7 A lengthy statement may be spread over several lines with the \ continuation character. If a single statement must be split across lines, choose breaking points that make sense, such as after a comma in a print statement or after an operator in a lengthy expression. 2.7 Figure 2.24 shows the precedence of the operators introduced in this chapter. The operators are shown from top to bottom in decreasing order of precedence. Notice that all these operators, except exponentiation, associate from left to right. Operators Associativity Type () left to right parentheses ** right to left exponential * / // % left to right multiplicative + - left to right additive Fig. 2.24 Precedence and associativity of the operators discussed so far.

Chapter 2 Introduction to Python Programming 97 Operators Associativity Type < <= > >= left to right relational ==!= <> left to right equality Fig. 2.24 Precedence and associativity of the operators discussed so far. Good Programming Practice 2.8 Refer to the operator precedence chart when writing expressions containing many operators. Confirm that the operators in the expression are performed in the order you expect. If you are uncertain about the order of evaluation in a complex expression, break the expression into smaller statements or use parentheses to force the order, exactly as you would do in an algebraic expression. Be sure to observe that some operators, such as exponentiation (**), associate from right to left rather than from left to right. 2.8 2.8 Indentation Python uses indentation to delimit (distinguish) blocks of code, called suites. This is in contrast to many other programming languages, which normally use braces to delimit blocks of code. The Python programmer chooses the number of spaces to indent a suite, and the number of spaces must remain consistent within a suite. Python recognizes new suites when there is a change in the number of indented spaces. If a single suite contains lines of code which are not uniformly indented, the Python interpreter reads those lines as belonging to other suites, normally resulting in syntax errors. Figure 2.25 contains a modified version of the code in Fig. 2.22 to illustrate improper indentation. 1 # Fig. 2.25: fig02_25.py 2 # Using if statements, relational operators and equality 3 # operators to show improper indentation 4 5 print "Enter two integers, and I will tell you" 6 print "the relationships they satisfy." 7 8 # read first string and convert to integer 9 number1 = raw_input( "Please enter first integer: " ) 10 number1 = int( number1 ) 11 12 # read second string and convert to integer 13 number2 = raw_input( "Please enter second integer: " ) 14 number2 = int( number2 ) 15 16 if number1 == number2: 17 print "%d is equal to %d" % ( number1, number2 ) 18 19 # improper indentation causes this if statement to execute only Fig. 2.25 if statements used to show improper indentation (part 1 of 2).