Post on 19-May-2015
Python & Perl
Lecture 03
Department of Computer ScienceUtah State University
Recap
● Editing Python Code● Running Python Code● Sample Programs● Python Code Execution● Functional Abstraction● Tuples
Goals for next few weeks
● Create simple graphics with PyGame
● Create simple games with PyGame
Outline
● Python Built-In Objects● Numbers● Numeric Operations● Modules● User Input● Strings
Python Built-In Objects
● Numbers● Strings● Lists, Tuples● Dictionaries● Files
Numbers
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
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
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>
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
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
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
Numeric Operations
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
Integer Division● >>> 10/7
● 1
● >>> 10.0/7
● 1.4285714285714286
● >>> 10 // 7
● 1
● >>> 10.0 // 7
● 1.0
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
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
User Input
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
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'
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 + '
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
Modules
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
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
Modules● There are three ways to import functionalities from modules:
import <module>
from <module> import <name>
from <module> import <name 1>, …, <name n>
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)
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
FROM <MODULE> IMPORT <NAME 1>, …, <NAME 2>● Imports specific functions, variables, classes defined in
<module> >>> from math import sqrt, pi
>>> sqrt(pi)
1.7724538509055159
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)
Strings
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!”'
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!''
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
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'
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
● >>> str(5)
'5'
● >>> repr(5)
'5'
● >>> str('Hello, \'Python\'!')
"Hello, 'Python'!"
● >>> repr('Hello, \'Python\'!')
'"Hello, \'Python\'!"'
str() and repr()
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\\'
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
String Formatting● C
printf() sprintf()
● C++ <iomanip>
● Python string formatting is similar to C
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.
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
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.'
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'
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
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'
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
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'
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
join() Solution
>>> chars = ['k', 'n', 'i', 'g', 'h', 't']
>>> myStr = ''.join(chars)
>>> myStr
'knight'
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
'''
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."
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
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
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')
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'
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.