You are on page 1of 52

1

Machine Languages, Assembly Languages


and High-Level Languages
Programming Languages
Hundreds exist today
Fall into three categories
Machine languages
Assembly languages
High-level languages

2002 Prentice Hall. All rights reserved.


2
Machine Languages, Assembly Languages
and High-Level Languages
Machine Languages
Only language understood directly by computer
Defined by computers hardware design
Machine-dependent
Languages specific to particular computers
Incomprehensible to human readers
Streams and numbers
Ultimately reduced to 0s and 1s
Instruct most elementary of operations
Slow, tedious and error-prone
Led to Assembly languages

2002 Prentice Hall. All rights reserved.


3
Machine Languages, Assembly Languages
and High-Level Languages
High-Level Languages
Single statements accomplish substantial tasks
Translated to machine language
Compilers convert to machine language
Conversion takes considerable time
Interpreters run programs without compiling
Used in development environment
Instructions comprehensible to humans
Look like everyday English
Contain common mathematical notation

2002 Prentice Hall. All rights reserved.


4

Structured Programming
Structured Languages
Pascal
Designed for teaching structured programming
Lacked features for commercial use
C
Had features Pascal didnt
Quickly adopted by programmers
Ada
Developed by U.S. Department of Defense (late 1970s)
Based on Pascal
DOD wanted one language for all its needs
Supported multitasking
Many activities occur in parallel

2002 Prentice Hall. All rights reserved.


5

Structured Programming (II)

Structured Languages
Pascal
Designed for teaching structured programming
Lacked features for commercial use
C
Had features Pascal didnt
Quickly adopted by programmers
Ada
Developed by U.S. Department of Defense (late 1970s)
Based on Pascal
DOD wanted one language for all its needs
Supported multitasking
Many activities occur in parallel

2002 Prentice Hall. All rights reserved.


6

Object-Oriented Programming

What is Object Technology?


Packaging scheme for creating software units
Units are objects
Any noun can be represented as an object
Date object, time object, car object
Have properties
Size, color, weight
Perform actions
Moving, sleeping, drawing
Defined in classes
Specify general format
Provide specific attributes and behaviors

2002 Prentice Hall. All rights reserved.


7

Object-Oriented Programming (II)

Object-Oriented programming
Based on nouns
Reflects way world is perceived
Advantages over structured programming
More natural process
Results in better productivity
Classes provide reusability
Microsoft Foundation Classes (MFC)
Easier to maintain
Programs more understandable
Focus on behaviors and interactions
Less attention to details

2002 Prentice Hall. All rights reserved.


8

Hardware Trends

Improving technologies
Internet community thrives on improvements of
Hardware
Software
Communications
Cost of products and services
Consistently dropping over the decades
Computer capacity and speed
Doubles every two years (on average)
Microprocessor chip
Laid groundwork in late 1970s and 1980s for productivity
improvements of the 1990s

2002 Prentice Hall. All rights reserved.


9

1.13 Open-Source Software Revolution

Open-source software
Unlike closed-source software, source code is freely
available
Available for modification, redistribution and as a basis for
other software
Usually available for download over the Internet
Free in the context of freedom
Most open-source software is copyrighted
Open-source licenses may impose restrictions
Community of developers
Problems detected and solved quickly
Continuous evolution of product

2002 Prentice Hall. All rights reserved.


10

1.13 Open-Source Software Revolution (II)

Python is part of the open-source community


License available at
www.python.org/2.4/license.html
Python developers newsgroup: comp.lang.python
Commercial support for open-source projects
IBM, Red Hat and Sun all support open-source projects
Some take open-source applications and sell them
commercially
Provide additional support, software, training, etc.
Open Source Initiatives Web site at
www.opensource.org

2002 Prentice Hall. All rights reserved.


11

1.14 History of Python

Created in 1989 by Guido van Rossum


Created as a scripting language for administrative tasks
Based on All Basic Code (ABC) and Modula-3
Added extensibility
Named after comic troupe Monty Python
Released publicly in 1991
Growing community of Python developers
Evolved into well-supported programming language

2002 Prentice Hall. All rights reserved.


12

1.15 Python Modules

Modules
Reusable pieces of software
Can be written by any Python developer
Extend Pythons capabilities
Python Web site at www.python.org
PrimarydistributioncenterforPythonsourcecode,modules
anddocumentation

2002 Prentice Hall. All rights reserved.


13
1.16 General Notes about Python and This
Book
Python
Designedtobeportableandextensible
OriginallyimplementedonUNIX
Programs often can be ported from one operating system to
anotherwithoutanychange
Syntaxanddesignpromotegoodprogrammingpracticesand
surprisinglyrapiddevelopmenttimes
Simpleenoughtobeusedbybeginningprogrammers
Powerfulenoughtoattractprofessionals

2002 Prentice Hall. All rights reserved.


14
Chapter 2 Introduction to Python
Programming
Outline
2.1 Introduction
2.2 First Program in Python: Printing a Line of Text
2.3 Modifying our First Python Program
2.3.1 Displaying a Single Line of Text with
Multiple Statements
2.3.2 Displaying Multiple Lines of Text with
a Single Statement
2.4 Another Python Program: Adding Integers
2.5 Memory Concepts
2.6 Arithmetic
2.7 String Formatting
2.8 Decision Making: Equality and Relational Operators
2.9 Indentation
2.10 Thinking About Objects: Introduction to Object Technology

2002 Prentice Hall. All rights reserved.


15

2.1 Introduction

Introduction to Python programming


Introduction to programming techniques
Structured programming
Object-oriented programming

2002 Prentice Hall. All rights reserved.


16
2.2 First Program in Python: Printing a Line of
Text
Python
The # symbol
Used to denote a single line comment
The print function
Used to send a stream of text to be output to the user
Executing
Saving as a file
Type code into a .py file and save it
To run it type python fileName.py
Executing code
Type python in the command line
Runs the python interpreter

2002 Prentice Hall. All rights reserved.


17
1 # Fig. 2.1: fig02_01.py Outline
2 # Printing a line of text in Python. This is a comment
3
4 print "Welcome to Python!" Prints out the line of text Fig02_01.py

Welcome to Python! Program Output

2002 Prentice Hall.


All rights reserved.
18
2.2 First Program in Python: Printing a Line of
Text

Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print "Welcome to Python!"
Welcome to Python!
>>> ^Z

Fig. 2.2 Interactive mode. (Python interpreter software Copyright 2001 Python
Software Foundation.)

2002 Prentice Hall. All rights reserved.


19

2.3 Modifying our First Python Program

Text outputs
How to display the text on one line through multiple
statements, 2.3.1
How to display the text on several lines with only one code
statement, 2.3.2

2002 Prentice Hall. All rights reserved.


20
2.3.1 Displaying a Single Line of Text with
Multiple Statements
Printing Lines of Text
Python displays each print function on a new line
The comma can be used to tell the compiler to make a space
rather than a white line

2002 Prentice Hall. All rights reserved.


21
2.3.1 Displaying a Single Line of Text with
Multiple Statements

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

Fig. 2.3 End-of-file key combinations for various popular computer systems.

2002 Prentice Hall. All rights reserved.


22
1 # Fig. 2.4: fig02_04.py Outline
2 # Printing a line with multiple statements.
3
4 print "Welcome",
5 print "to Python!" The comma tells the compiler to insert Fig02_04.py
a space rather than go to the next line
Welcome to Python! Program Output

2002 Prentice Hall.


All rights reserved.
23
2.3.2 Displaying Multiple Lines of Text with a
Single Statement
Escape characters
Used to perform a different task that normally intended
\n insert a new line
\" insert double quotes
\' insert a single quote
\\ inserts a backslash
More are listed in Fig. 2.6

2002 Prentice Hall. All rights reserved.


24
1 # Fig. 2.5: fig02_05.py Outline
2 # Printing multiple lines with a single statement.
3
4 print "Welcome\nto\n\nPython!"
Fig02_05.py
The \n is used to make the
Welcome text appear on the next line Program Output
To

Python!

2002 Prentice Hall.


All rights reserved.
25
2.3.2 Displaying Multiple Lines of Text with a
Single Statement
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.
\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 Escape sequences.

2002 Prentice Hall. All rights reserved.


26

2.4 Another Program: Adding Integers

Functions
The raw_input function
Used to retrieve data from the user
The int function
Used to convert strings to integers

2002 Prentice Hall. All rights reserved.


27
1 # Fig. 2.7: fig02_07.py Outline
2 # Simple addition program.
3
4 # prompt user for input
5 integer1 = raw_input( "Enter first integer:\n" ) # read string Fig02_07.py
6 integer1 = int( integer1 ) # convert string to integer
Prompts the user to
7 enter and integer value
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
Converts the string value
12 into an integer value
13 print "Sum is", sum # print sum

Adds up and then prints out


Enter first integer: the sum of the two numbers Program Output
45
Enter second integer:
72

Sum is 117

2002 Prentice Hall.


All rights reserved.
28

2.4 Another Program: Adding Integers

Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32
Type "help", "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 (incorrectly) without converting to


integers (the result should be 6).

2002 Prentice Hall. All rights reserved.


29

2.5 Memory Concepts

Objects
Every object has a type, size, value, and location
Stored in computers memory
Type and location cannot be changed
When a variable is made the name is binded to the value
Values are not modified as a computer performs the
calculation

2002 Prentice Hall. All rights reserved.


30

2.5 Memory Concepts

integer1 "45"

Fig. 2.9 Memory location showing value of a variable and the name bound to the value.

"45"

integer1 45

Fig. 2.10 Memory location showing the name and value of a variable.

2002 Prentice Hall. All rights reserved.


31

2.5 Memory Concepts

integer1 45

integer2 72

Fig. 2.11 Memory locations after values for two variables have been input.

integer1 45

integer2 72

sum 117

Fig. 2.12 Memory locations after a calculation.

2002 Prentice Hall. All rights reserved.


32
1 # Fig. 2.13: fig02_13.py Outline
2 # Displaying an objects location, type and value.
3
4 # prompt the user for input
5 integer1 = raw_input( "Enter first integer:\n" ) # read a string Fig02_13.py
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 Prints the id, type and
10 integer2 = raw_input( "Enter second integer:\n" ) # read a string value before and after
11 print "integer2: ", id( integer2 ), type( integer2 ), integer2
12 integer2 = int( integer2 ) # convert the string to an integer
the variable is converted
13 print "integer2: ", id( integer2 ), type( integer2 ), integer2 into an integer
14
15 sum = integer1 + integer2 # assignment of sum
16 print "sum: ", id( sum ), type( sum ), sum
Notice in the output that
Enter first integer:
after the conversion the
Program
value is the Output
same but the
5
type and id have changed
integer1: 7956744 <type 'str'> 5
integer1: 7637688 <type 'int'> 5
Enter second integer:
27
integer2: 7776368 <type 'str'> 27
integer2: 7637352 <type 'int'> 27
sum: 7637436 <type 'int'> 32

2002 Prentice Hall.


All rights reserved.
33

2.6 Arithmetic

Symbols
* = multiply
/ = divide
% = modulus
** = exponential
// = floor division
Only available in Python 2.2
Must use from __future__ import division
Order
Operators are done in order of parenthesis, exponents,
multiple and divide (left to right), and lastly add and subtract
(left to right)

2002 Prentice Hall. All rights reserved.


34

2.6 Arithmetic

Python Arithmetic Algebraic Python


operation operator expression expression
Addition + f+7 f + 7

Subtraction pc p - c
Multiplication * bm b * m
x ** y
Exponentiation ** xy
Division / x / y or <Anchor4> or x y x / y
// (new in Python 2.2) x // y

Modulus % r mod s r % s

Fig. 2.14 Arithmetic operators.

2002 Prentice Hall. All rights reserved.


35

2.6 Arithmetic

Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32
Type "help", "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.

2002 Prentice Hall. All rights reserved.


36

2.6 Arithmetic

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 Evaluated third. If there are several, they are


Division evaluated left to right. [Note: The // operator is
Modulus new in version 2.2]
+ - Addition Evaluated last. If there are several, they are evaluated
Subtraction left to right.

Fig. 2.16 Precedence of arithmetic operators.

2002 Prentice Hall. All rights reserved.


37

2.6 Arithmetic
Step 1.
y = 2 * 5 ** 2 + 3 * 5 + 7
5 ** 2 = 25 Exponentiation
Step 2.
y = 2 * 25 + 3 * 5 + 7
2 * 25 = 50 Leftmost multiplication
Step 3.
y = 50 + 3 * 5 + 7
3 * 5 = 15 Multiplication before addition
Step 4.
y = 50 + 15 + 7
50 + 15 = 65 Leftmost addition

Step 5.
y = 65 + 7 is 72 Last edition

Step 6.
y = 72 Python assigns 72 to y

Fig. 2.17 Order in which a second-degree polynomial is evaluated.

2002 Prentice Hall. All rights reserved.


38

2.7 String Formatting

Strings
Unlike other languages strings are a built in data type
Allows for easy string manipulation
Double quote strings
Single quotes need not be escaped
Single quote strings
Double quotes need not be escaped
Triple quoted strings
Do not need any escape sequence
Used for large blocks of text

2002 Prentice Hall. All rights reserved.


39
1 # Fig. 2.18: fig02_18.py Strings in single quotes need Outline
2 # Creating strings and using quote not have
characters double quotes escaped
in strings.
3
4 print "This is a string with \"double quotes.\"" Strings with double quotes
Fig02_18
5 print 'This is another string with "double quotes."'
6 print 'This is a string with \'single quotes.\''
need not escape 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."


Program
Strings in triple quotes do Output
This is another string with "double quotes."
not have to escape anything
This is a string with 'single quotes.'
and can span many lines
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.

2002 Prentice Hall.


All rights reserved.
40
1 # Fig. 2.19: fig02_19.py Outline
2 # String formatting.
3
4 integerValue = 4237
5 print "Integer ", integerValue Fig02_19.py
6 print "Decimal integer %d" % integerValue
7 print "Hexadecimal integer %x\n" % integerValue
8
9 floatValue = 123456.789 The %e is used to format the string
10 print "Float", floatValue to scientific notation number
11 print "Default float %f" % floatValue Formats the string to contain exactly
12 print "Default exponential %e\n" % floatValue a specified amount of letters
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 )

Formats the string to only


allow so many characters

2002 Prentice Hall.


All rights reserved.
41
Integer 4237
Outline
Decimal integer 4237
Hexadecimal integer 108d
Fig02_19.py
Program Output
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)

2002 Prentice Hall.


All rights reserved.
42

2.7 String Formatting

Conversion Specifier Symbol Meaning


c Single character (i.e., a string of length one) or the integer
representation of an ASCII character.

s String or a value to be converted to a string.


d Signed decimal integer.

u Unsigned decimal integer.


o Unsigned octal integer.
x Unsigned hexadecimal integer (with hexadecimal digits a
through f in lowercase letters).
X Unsigned hexadecimal integer (with hexadecimal digits A
through F in uppercase letters).
f 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.

2002 Prentice Hall. All rights reserved.


43
2.8 Decision Making: Equality and
Relational Operators
The if structure
Can be formed with equality and relational operators
<, >, ==,

2002 Prentice Hall. All rights reserved.


44
2.8 Decision Making: Equality and
Relational Operators
Standard algebraic Python equality Example Meaning of
equality operator or or relational of Python Python condition
relational operator operator condition
Relational 2.1
operators
> > x > y x is greater than y
< < 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.

2002 Prentice Hall. All rights reserved.


45
1 # Fig. 2.22: fig02_22.py Outline
2 # Compare integers using if structures, relational operators
3 # and equality operators.
4
5 print "Enter two integers, and I will tell you" Fig02_22.py
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 ) Gets two values from the user
11
12 # read second string and convert to integer and converts them to strings
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 Checks each of the rational
22 if number1 < number2:
23 print "%d is less than %d" % ( number1, number2 ) operators or the numbers
24 using if statements
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 )

2002 Prentice Hall.


All rights reserved.
46
Enter two integers, and I will tell you
Outline
the relationships they satisfy.
Please enter first integer: 37
Please enter second integer: 42
Fig02_22.py
Program Output
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

Enter two integers, and I will tell you


the relationships they satisfy.
Please enter first integer: 54
Please enter second integer: 17
54 is not equal to 17
54 is greater than 17
54 is greater than or equal to 17
2002 Prentice Hall.
All rights reserved.
47
2.8 Decision Making: Equality and
Relational Operators

Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print 1 +
File "<string>", line 1
print 1 +
^
SyntaxError: invalid syntax
>>> print 1 + \
... 2
3
>>>

2002 Prentice Hall. All rights reserved.


48
2.8 Decision Making: Equality and
Relational Operators
Oper Associativity Type
ators
() left to right parentheses

** right to left exponential


* / // % left to right multiplicative
+ - left to right additive
< <= > >= left to right relational
== != <> left to right equality

Fig. 2.24 Precedence and associativity of operators discussed so far.

2002 Prentice Hall. All rights reserved.


49

2.9 Indentation

Indenting
Used to delimit code
Python uses no end of statement character
Therefore a new line of code is determined by return space
Indenting is the same way
Python does not use {} to enclose a multi-line statement
The indentation must be exactly the same same
There is no exact rule for the number of spaces but they are
generally in groups of three

2002 Prentice Hall. All rights reserved.


50
1 # Fig. 2.25: fig02_25.py Outline
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" Fig02_25.py
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 ) Since this if statement is indented it is
15 considered part of the other if statement
16 if number1 == number2:
17 print "%d is equal to %d" % ( number1, number2 )
18
19 # improper indentation causes this if statement to execute only
20 # when the above if statement executes
21 if number1 != number2:
22 print "%d is not equal to %d" % ( number1, number2 )
23
24 if number1 < number2:
25 print "%d is less than %d" % ( number1, number2 )
26
27 if number1 > number2:
28 print "%d is greater than %d" % ( number1, number2 )
29
30 if number1 <= number2:
31 print "%d is less than or equal to %d" % ( number1, number2 )
32
33 if number1 >= number2:
34 print "%d is greater than or equal to %d" % ( number1, number2 )
2002 Prentice Hall.
All rights reserved.
51
Enter two integers, and I will tell you Outline
the relationships they satisfy.
Please enter first integer: 1 Fig02_25.py
Please enter second integer: 2 Program Output
1 is less than 2
1 is less than or equal to 2

2002 Prentice Hall.


All rights reserved.
52
2.10 Thinking about Objects: Introduction to
Object Technology
Objects
Everything in the real world is made of objects
Each object has attributes
Shape, size, color, weight
Each object has behaviors
Roll, bounce, inflate, deflate
Object Oriented Programming (OOP)
Modes real world objects with programming counterparts
Information hiding
Know how to communicate with one another
Dont know the specifics of other objects
Encapsulate, to prevent code repetition

2002 Prentice Hall. All rights reserved.

You might also like