302x Filetype PDF File size 0.83 MB Source: angsila.cs.buu.ac.th
2
Introduction to Python
Programming
Objectives
• TounderstandatypicalPythonprogram-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.
• Tounderstandtheprecedenceofarithmeticoperators.
• To write simple decision-making statements.
High thoughts must have high language.
Aristophanes
Ourlife is frittered away by detail…Simplify, simplify.
Henry Thoreau
Myobject all sublime
I shall achieve in time.
W.S. Gilbert
74 Introduction to Python Programming Chapter2
Outline
2.1 Introduction
2.2 Simple Program: Printing a Line of Text
2.3 Another Simple Program: Adding Two Integers
2.4 MemoryConcepts
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.AfterpresentingbasicconceptsinChapters2–3,weexaminethestructuredprogram-
ming approach in Chapters 4–6. At the same time we explore introductory Python topics,
wealsobeginourdiscussionofobject-orientedprogrammingbecauseofthecentralimpor-
tanceobject-orientedprogrammingtakesthroughoutthistext.Forthisreason,weconclude
this chapter with Section 2.9, Thinking About Objects.
1
2.2 Simple Program: Printing a Line of Text
Pythonusesnotationsthatmayappearstrangetonon-programmers.Tofamiliarizereaders
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. Theresources for this book, including step-by-step instructions on installing Python on Windows
and Unix/Linux platforms are posted at www.deitel.com.
Chapter2 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
improveprogramreadability.Commentsalsohelpotherprogrammersreadandunderstand
your program. A comment that begins with # is called a single-line comment, because the
commentterminates at the end of the current line. The comment text A first program
inPythondescribesthepurposeoftheprogram(line2).
GoodProgrammingPractice2.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
whenyourevisit a document for modifications or updates. 2.1
ThePythonprintcommandinstructsthecomputertodisplaythestringofcharacters
contained betweenthequotationmarks(line4).AstringisaPythondatatypethatcontains
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 commandlineisatext“terminal”inwhichtheusercantypecommandsthatcausethe
computersystemtorespond.[Note:ToinvokePython,thesystempathvariablemustbeset
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.]
WhenthePython 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.
ThesecondwaytoexecutePythonstatements 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 Chapter2
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
WhenPythonisinvokedonafile, 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)causestheinterpretertoenterinteractivemodeafterrunningthefile.Thisisuse-
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
thePythonprompt(>>>).APythonstatementisinterpretedwhenadevelopertypesastate-
mentat 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 Pythonin interactive mode. (Copyright © 2001 Python Software
Foundation.)
Theprintstatementonthethird 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
Windowssystems)andpressingtheEnterkey.Figure 2.3 lists the keyboard combinations
for the end-of-file character for various computer systems.
Computersystem Keyboardcombination
UNIX/Linuxsystems 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-
graminFig. 2.1. Line 4 prints the string "Welcome" to the screen. Normally, a string fol-
lowingaprintstatementbeginsonanewline,belowthepreviousstring.Thecomma(,)
at the end of line 4, however, tells Python not to begin a new line but instead to add a space
no reviews yet
Please Login to review.