Top Banner
Python & Perl Lecture 03 Department of Computer Science Utah State University
57
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Python lecture 03

Python & Perl

Lecture 03

Department of Computer ScienceUtah State University

Page 2: Python lecture 03

Recap

● Editing Python Code● Running Python Code● Sample Programs● Python Code Execution● Functional Abstraction● Tuples

Page 3: Python lecture 03

Goals for next few weeks

● Create simple graphics with PyGame

● Create simple games with PyGame

Page 4: Python lecture 03

Outline

● Python Built-In Objects● Numbers● Numeric Operations● Modules● User Input● Strings

Page 5: Python lecture 03

Python Built-In Objects

● Numbers● Strings● Lists, Tuples● Dictionaries● Files

Page 6: Python lecture 03

Numbers

Page 7: Python lecture 03

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

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

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

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

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

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

Numeric Operations

Page 14: Python lecture 03

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

Integer Division● >>> 10/7

● 1

● >>> 10.0/7

● 1.4285714285714286

● >>> 10 // 7

● 1

● >>> 10.0 // 7

● 1.0

Page 16: Python lecture 03

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

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

User Input

Page 19: Python lecture 03

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

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

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

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

Modules

Page 24: Python lecture 03

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

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

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

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

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

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

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

Strings

Page 32: Python lecture 03

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

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

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

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

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

● >>> str(5)

'5'

● >>> repr(5)

'5'

● >>> str('Hello, \'Python\'!')

"Hello, 'Python'!"

● >>> repr('Hello, \'Python\'!')

'"Hello, \'Python\'!"'

str() and repr()

Page 38: Python lecture 03

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

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

String Formatting● C

printf() sprintf()

● C++ <iomanip>

● Python string formatting is similar to C

Page 41: Python lecture 03

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

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

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

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

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

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

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

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

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

join() Solution

>>> chars = ['k', 'n', 'i', 'g', 'h', 't']

>>> myStr = ''.join(chars)

>>> myStr

'knight'

Page 51: Python lecture 03

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

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

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

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

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

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

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.