CH 2
CH 2
Programming in Python
Chapter 2: Basic Concepts in Python
Programming
Xiang Lian
The University of Texas – Pan American
Edinburg, TX 78539
[email protected]
Objectives
• In this chapter, you will
– Understand a typical Python program-development
environment
– Write simple input and output computer programs
in Python
– Become familiar with fundamental data types
– Use arithmetic operators and their precedence in
Python
– Write simple decision-making statements
2
Last Chapter: Python IDE
3
Python 3.4 GUI
Visual Programming
# Fig. 10.4: fig10_04.py
# Label demonstration.
def main():
LabelDemo().mainloop() # starts event loop
if __name__ == "__main__":
main()
4
Introduction
• Introduction to Python programming
• Introduction to programming techniques
– Structured programming
– Object-oriented programming
5
Hello Program
# Fig. 2.1: fig02_01.py
# Printing a line of text in Python.
6
First Program in Python: Printing a
Line of Text
• Python "//" or "/* … */" is used in C/C++/Java
– The # symbol
• Used to denote a single line comment
• "printf" or "cout" is used in C/C++
– The print function • "System.out.println(...)" in Java
• 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
7
Print a Line with Multiple
Statements
# Fig. 2.2: fig02_02.py
# Printing a line with multiple statements.
comma
print ("Welcome",
"to Python Programming Class!")
# Results:
# Welcome to Python Programming Class!
8
Special Characters in the String
• 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
9
Examples of Escape Characters
Escape Description
Sequence
\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.
10
Another Program: Adding Integers
"cin" is used in C++
• Functions Note: raw_input() is used
in the Textbook for version
– The input function 2.2.X, but not for 3.4.X
• Used to retrieve data from the user
– The int function Different from int in C/C++/Java
• Used to convert strings to integers
11
Outline
Sum is 117
# Result:
Enter first integer:
2
Enter second integer:
4
24
Memory Concepts
• Variable names correspond to Python objects
– E.g., integer1, integer2
– integer1 = input( "Enter first integer:\n" )
• 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
Fig. 2.9 Memory location showing value of a variable and the name bound to the value.
Fig. 2.10 Memory location showing the name and value of a variable.
integer1 45
integer2 72
Fig. 2.11 Memory locations after values for two variables have been input.
integer1 45
integer2 72
sum 117
• Functions
– The input function
• Used to retrieve data from the user
– The int function
• Used to convert strings to integers
– The id(…) function
• Used to return the interpreter’s representation of the
variable’s location
– The type(…) function
• Used to return the type of the variable
17
# Fig. 2.13: fig02_13.py Outline
# Displaying an object's location, type and value.
Division / x / y or x ÷y x/y
// x // y
Modulus % r mod s r%s
Fig. 2.14 Arithmetic operators.
20
Example of Arithmetic
# test arithmetic
x=2
y=3
print("x^y=\b", x**y)
print("x/y=\b", x/y)
print("x//y=\b", x//y)
21
Examples of (Floor) Division
Python 3.4 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 3.0 // 4.0 # floating-point floor division
0.0
>>> 3 / 4 # true division (new behavior)
0.75
>>> 3.0 / 4.0 # true division (same as before)
0.75
22
Precedence of Arithmetic Operators
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.
** Exponentiatio Evaluated second. If there are several,
n they are evaluated right to left.
* / // % Multiplication Evaluated third. If there are several,
Division they are evaluated left to right. [Note:
Modulus The // operator is new in version 2.2]
+ - Addition Evaluated last. If there are several, they
Subtraction are evaluated left to right.
Fig. 2.16 Precedence of arithmetic operators.
23
An Example of Arithmetic
Step 1.
Expression
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
24
Fig. 2.17 Order in which a second-degree polynomial is evaluated.
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
25
# Fig. 2.18: fig02_18.py Strings in single quotes need Outline
# Creating strings and using quote characters innot have double quotes escaped
strings.
print ("This is a string with \"double quotes.\"") Strings with double quotes
Fig02_18
print ('This is another string with "double quotes."')
print ('This is a string with \'single quotes.\'')
need not escape single quotes
print ("This is another string with 'single quotes.'")
print ("""This string has "double quotes" and 'single quotes'.
You can even do multiple lines.""")
print ('''This string also has "double" and 'single' quotes.''')
integerValue = 4237
print ("Integer ", integerValue) Fig02_19.py
print ("Decimal integer %d" % integerValue)
print ("Hexadecimal integer %x\n" % integerValue)
29
Decision Making: Equality and
Relational Operators (cont'd)
Standard algebraic Python equality Example Meaning of
equality operator or or relational of Python Python condition
relational operator operator condition
Relational
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. 30
Common Syntax Errors
• Spaces between pairs of symbols below
– = =, ! =, < =, > =
• Reversing the order
– =!, ><, =>, =<
• == vs. =
31
32
# Fig. 2.22: fig02_22.py Outline
# Compare integers using if structures, relational operators
# and equality operators.
print ( "Enter two integers, and I will tell you " ) Fig02_22.py
print ( "the relationships they satisfy." )
if number1 == number2:
print ("%d is equal to %d" % ( number1, number2 ))
if number1 != number2:
print ("%d is not equal to %d" % ( number1, number2 ))
34
35