Download - Python lecture 03
![Page 1: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/1.jpg)
Python & Perl
Lecture 03
Department of Computer ScienceUtah State University
![Page 2: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/2.jpg)
Recap
● Editing Python Code● Running Python Code● Sample Programs● Python Code Execution● Functional Abstraction● Tuples
![Page 3: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/3.jpg)
Goals for next few weeks
● Create simple graphics with PyGame
● Create simple games with PyGame
![Page 4: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/4.jpg)
Outline
● Python Built-In Objects● Numbers● Numeric Operations● Modules● User Input● Strings
![Page 5: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/5.jpg)
Python Built-In Objects
● Numbers● Strings● Lists, Tuples● Dictionaries● Files
![Page 6: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/6.jpg)
Numbers
![Page 7: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/7.jpg)
Plain Integers● Plain integers are are in the range [-sys.maxint-1, sys.maxint]
● In Python 2.7.2 on 64-bit Windows 7: >>> sys.maxint
2147483647
>>> -sys.maxint – 1
-2147483648
● In Python 2.6.6 on 64-bit Ubuntu 10.10: >>> sys.maxint
9223372036854775807
>>> -sys.maxint -1
-9223372036854775808
![Page 8: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/8.jpg)
Hexadecimal Integers● Hexadecimal is a positional number system with a base
of 16● Hexadecimal system uses 16 distinct symbols: 0-9, A, B, C, D, E, F
● 0-9 represent themselves● A, B, C, D, E, F represent 10, 11, 12, 13, 14,
15, respectively● 2AF3 = (2 x 163) + (10 x 162) + (15 x 161) + (3 x 160) = 10,995
![Page 9: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/9.jpg)
Hexadecimal Integers● Primary use of hexadecimal notation is a human-friendly
representation of byte-coded values in electronics >>> hex(10995)
'0x2af3'
>>> 0x2af3
10995
● Hexadecimal notation is used to represent memory address >>> def f(x): return x + 1
>>> f
<function f at 0x7f1287bb45f0>
![Page 10: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/10.jpg)
Octal Integers● Octal is a position number system with a base 8 and
uses the digits 0 through 7● 112 = 1 x 82 + 1 x 81 + 2 x 80 = 74
● In Python:
>>> oct(74)
'0112'
>>> 0112
74
![Page 11: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/11.jpg)
Floating Point Numbers● Floats are implemented as the C double● Python documentation: “All bets on their precision are off unless
you happen to know the machine you are working with”● They have an embedded decimal point (1.0 or 3.14159) or an
optional signed exponent preceded by 'e' or 'E' >>> 1.0e2
100.0
>>> 1.0e-2
0.01
![Page 12: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/12.jpg)
Complex Numbers● Python can represent ● Complex numbers have the real and imaginary parts, both of which
are represented as double● Appending 'j' or 'J' to a number makes it a complex number with the
zero real part >>> 1j
1j
>>> 5+4j
(5+4j)
−1
![Page 13: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/13.jpg)
Numeric Operations
![Page 14: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/14.jpg)
Numeric Operators● x + y ### sum of x and y
● x – y ### difference of x and y
● x * y ### product of x and y
● x / y ### quotient of x and y
● x // y ### floored quotient of x and y
● x % y ### remainder (modulus) of x / y
● -x ### negated x
● x ** y ### x to the power of y
![Page 15: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/15.jpg)
Integer Division● >>> 10/7
● 1
● >>> 10.0/7
● 1.4285714285714286
● >>> 10 // 7
● 1
● >>> 10.0 // 7
● 1.0
![Page 16: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/16.jpg)
IMPORT FROM __FUTURE__● In Python 3.X, x/y changed to true division● For example, 3/2 evaluates to 1.5, not to 1● You can do this type of division in Python 2.6 and Python 2.7
>>> from __future__ import division
>>> 3/2
1.5
● __future__ (double underscores on both sides) is a module with future enhancements that can be tested in current versions
![Page 17: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/17.jpg)
Built-in Number Functions● abs(x) ### absolute value (magnitude) of x
● int(x) ### convert x to plain integer
● long(x) ### convert x to long integer
● float(x) ### convert x to float
● complex(r,i) ### make a complex number with r
### as real and i as imaginary● c.conjugate() ### conjugate of complex number c
● divmod(x,y) ### pair (x//y, x%y)
● pow(x,y) ### x to the power of y
![Page 18: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/18.jpg)
User Input
![Page 19: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/19.jpg)
User Input● There are two user input functions in Python:
input([prompt])
raw_input([prompt])
● Similarities
Both take an optional prompt Both read user input
● Differences
input() reads an input string as a Python expression and evaluates it
raw_input() returns the input as a string
![Page 20: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/20.jpg)
input() vs. raw_input()>>> x = input("type in value for x: ")
type in value for x: 1
>>> x
1
>>> x = raw_input("type in value for x: ")
type in value for x: 1
>>> x
'1'
![Page 21: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/21.jpg)
input() vs. raw_input()>>> x = input("type in value for x: ")
type in value for x: 1 +
Traceback (most recent call last):
File "<pyshell#37>", line 1, in <module>
x = input("type in value for x: ")
File "<string>", line 1
1 +
^
SyntaxError: unexpected EOF while parsing
>>> x = raw_input("type in value for x: ")
type in value for x: 1 +
>>> x
'1 + '
![Page 22: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/22.jpg)
User Input: Official Documentation
input() “is not safe from user errors! It expects a valid Python
expression; if the input is not syntactically valid, a SynaxError will be raised. Other exceptions may be raised if there is an error during evaluation... Consider using raw_input() function for general input from users.”
http://docs.python.org/library/functions.html#input
![Page 23: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/23.jpg)
Modules
![Page 24: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/24.jpg)
Modules
● A module is a .py file that contains Python definitions and statements
● A module can contain executable statements and function definitions
● A module can import other modules● Convention: put all the import statements at the
beginning of a module
![Page 25: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/25.jpg)
Modules
● For efficiency, each module is imported only once per interpreter session
● If you change some modules, restart the interpreter and import them again
● If you are debugging a specific module, you can use reload(modulename) in the interpreter
![Page 26: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/26.jpg)
Modules● There are three ways to import functionalities from modules:
import <module>
from <module> import <name>
from <module> import <name 1>, …, <name n>
![Page 27: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/27.jpg)
IMPORT <MODULE>● Imports all functions, classes, variables defined in
<module> >>> import math
>>> math.sqrt(2.0)
1.4142135623730951
>>> math.pi
3.141592653589793
>>> math.sin(math.pi/2)
![Page 28: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/28.jpg)
FROM <MODULE> IMPORT <NAME>● Imports a specific function, variable, class defined in
<module> >>> math.sqrt(2)
NameError: name 'math' is not defined
>>> from math import sqrt
>>> sqrt(2.0)
1.4142135623730951
>>> from math import pi
>>> pi
3.141592653589793
![Page 29: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/29.jpg)
FROM <MODULE> IMPORT <NAME 1>, …, <NAME 2>● Imports specific functions, variables, classes defined in
<module> >>> from math import sqrt, pi
>>> sqrt(pi)
1.7724538509055159
![Page 30: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/30.jpg)
Math Modules
● Python has two math modules math and cmath that you can import:
>>> import math
>>> import cmath
● math contains functions for integers and floats (seehttp://docs.python.org/library/math.html)
● cmath contains functions for complex numbers (seehttp://docs.python.org/library/cmath.html)
![Page 31: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/31.jpg)
Strings
![Page 32: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/32.jpg)
Strings
● String literals in Python can be written in double or single quotes:
>>> “Hello, Python!”
>>> 'Hello, Python!'
● One type of quote can be embedded in the other type of quote without escaping:
>>> “Hello, 'Python!'”
>>> 'Hello, “Python!”'
![Page 33: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/33.jpg)
Strings
● If you want to embed the (single or double quote) into the same type of quote, you have to escape
>>> “Hello, \”World!\””
>>> 'Hello, \'World!\''
● Both statements below will result in an error:
>>> “Hello, “World!””
>>> 'Hello, 'World!''
![Page 34: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/34.jpg)
String Concatenation● String literals are automatically concatenated when separated by
space:
>>> “hello ” “world”
“hello world”
>>> 'hello ' 'world'
'hello world'
● String variables are not concatenated:
>>> h = 'hello '
>>> w = 'world'
>>> h w
ERROR
![Page 35: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/35.jpg)
String Concatenation● If you want to concatenate string variables, use + (it will also work on
string literals):
>>> “hello ” + “world”
'hello world'
>>> h = 'hello '
>>> w = 'world'
>>> h + w
'hello world'
![Page 36: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/36.jpg)
str() and repr()● There are two built-in string conversion functions
● str([object])
returns a string containing a printable representation of the ob-ject
one can think of the returned string as the User's string view of the object
● repr([object])
returns a string containing a printable representation of the ob-ject
one can think of the returned string as Python's string view of the object
![Page 37: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/37.jpg)
● >>> str(5)
'5'
● >>> repr(5)
'5'
● >>> str('Hello, \'Python\'!')
"Hello, 'Python'!"
● >>> repr('Hello, \'Python\'!')
'"Hello, \'Python\'!"'
str() and repr()
![Page 38: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/38.jpg)
Raw Strings● If you need to preserve backslashes in your strings, escape them:
>>> path = "C:\\My Dir\\table.txt"
● You can make the string raw, which turns the escape mechanism off:
>>> path = r"C:\My Dir\table.txt"
● Raw strings cannot end in '\':
>>> path = r”C:\My Documents\My Python Programs\”
ERROR● The '\' can be concatenated:
>>> path = r”C:\My Documents\My Python Programs” + “\\”
'C:\\My Documents\\My Python Programs\\'
![Page 39: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/39.jpg)
Strings● Strings are immutable sequences, i.e., they do not support item
assignment: >>> str = 'rock violin'
>>> str[0]
'r'
>>> str[0] = 's'
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
str[0] = 's'
TypeError: 'str' object does not support item assignment
![Page 40: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/40.jpg)
String Formatting● C
printf() sprintf()
● C++ <iomanip>
● Python string formatting is similar to C
![Page 41: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/41.jpg)
Basic Syntax● format_str % values
format_str is a string to be formatted
% is a required operator
values specify formatting values
values must specify a value for every specifier that format_str contains.
![Page 42: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/42.jpg)
Formatting Specifiers● Full (and rather lengthy) list of specifiers is at
http://docs.python.org/library/stdtypes.html#string-formatting-operations
● Some common specifiers that you are likely to use in your programs are:
%d signed integer
%x unsigned hexadecimal
%f floating point decimal format
%s string (converted using str())
%% a percent sign
![Page 43: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/43.jpg)
Example 01>>> x, y = 20, 5 ## x is assigned 20, y is assigned 5
>>> "John is %d years old." % x
'John is 20 years old.'
>>> "John is %d years and %d months old." % (x, y)
'John is 20 years and 5 months old.'
![Page 44: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/44.jpg)
Specifier Width● Specifier width is optional● The width specifies the minimum number of characters
for the formatted value:>>> "%d" % 2
'2'
>>> "%2d" % 2 ### 2 characters wide
' 2'
>>> "%3d" % 2 ### 3 characters wide
' 2'
![Page 45: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/45.jpg)
String Module● To use the string module, execute import string
● In general, many methods can be called as functions of the string module (many of these are depricated) or as methods on string objects
● Calling methods on string objects is preferred
![Page 46: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/46.jpg)
Functions vs. Object Methods>>> import string
>>> string.upper("hello") ## depricated function, but still works
'HELLO'
>>> "hello".upper() ## preferred object method
'HELLO'
>>> x = " hello "
>>> string.strip(x) ## depricated function, but still works
'hello'
>>> x
' hello '
>>> x.strip() ## preferred object method
'hello'
![Page 47: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/47.jpg)
string.capwords()
● Some methods can only be called as the string module functions>>> s = "poetry, music, and math"
>>> string.capwords(s)
'Poetry, Music, And Math'
>>> s.capwords() ## error
![Page 48: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/48.jpg)
String Building
● String building is turning a sequence (e.g. a list or a tuple) of characters into a string
● For example, start with this:['k', 'n', 'i', 'g', 'h', 't']
● End with this:'knight'
![Page 49: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/49.jpg)
Obvious Solution
chars = ['k', 'n', 'i', 'g', 'h', 't']
myStr = '' ## string to be built
for ch in chars: ## loop thru chars
myStr += ch
## print chars and myStr.
print 'chars = ', chars
print 'myStr = ', myStr
![Page 50: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/50.jpg)
join() Solution
>>> chars = ['k', 'n', 'i', 'g', 'h', 't']
>>> myStr = ''.join(chars)
>>> myStr
'knight'
![Page 51: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/51.jpg)
Sample Stringrumi_verse = '''
Someone who makes a habit of eating clay
gets mad when you try to keep him from it.
Being a leader can also be a poisonous habit,
so that when someone questions your authority,
you think, "He's trying to take over."
You may respond courteously, but inside you rage.
Jalaladdin Rumi, "The Mouse and the Camel"
Translated by Coleman Barks
'''
![Page 52: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/52.jpg)
find()>>> rumi_verse.find('who') ## where 1st 'who' starts
9
>>> rumi_verse.find('"') ## where 1st double quote starts
188
>>> rumi_verse.find('"', 189) ## specifying optional start
214
>>> rumi_verse[189:214] ## slicing the quoted string
"He's trying to take over."
![Page 53: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/53.jpg)
find()● When a string is not found, -1 is returned
>>> rumi_verse.find('$$$') ## no dollar signs in Rumi
-1
● Both start and end of search range can be specified>>> rumi_verse.find('poisonous habit', 110, 150)
114
![Page 54: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/54.jpg)
split()● split() is used to split strings with specific characters● The argument to split() is the sequence of characters
(typically one character) by which the string is split into substrings
● The result is a list of strings● The argument to split() is not included in any of the
strings
![Page 55: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/55.jpg)
split()● Splitting rumi_verse into individual words by white
space>>> rumi_verse.split(' ')
● Splitting rumi_verse into individual lines>>> rumi_verse.split('\n')
● Splitting rumi_verse into two strings by 'and'
>>> rumi_verse.split('and')
![Page 56: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/56.jpg)
replace()● replace() replaces all occurrences of one string with
another string>>> 'someone who makes a habit of eating dirt'.replace('dirt', 'clay')
'someone who makes a habit of eating clay'
>>> '101010'.replace('0', 'zero')
'1zero1zero1zero'
![Page 57: Python lecture 03](https://reader035.vdocuments.net/reader035/viewer/2022062303/555a6736d8b42ae7218b4ba2/html5/thumbnails/57.jpg)
Reading & References
● www.python.org.● http://en.wikipedia.org/wiki/Hexadecimal● http://en.wikipedia.org/wiki/Octal● M. L. Hetland. Beginning Python From Novice to Profession-
al, 2nd Ed., APRESS.