Pythongoodppt 2024 07 04 09 15 51
Pythongoodppt 2024 07 04 09 15 51
with Python
1
Languages
Some influential ones:
FORTRAN
science / engineering
COBOL
business data
LISP
logic and AI
BASIC
a simple language
2
4 Major Versions of Python
“Python” or “CPython” is written in C/C++
- Version 2.7 came out in mid-2010
- Version 3.1.2 came out in early 2010
3
Development Environments
what IDE to use? http://stackoverflow.com/questions/81584
4
Programming basics
code or source code: The sequence of instructions in a program.
syntax: The set of legal structures and commands that can be
used in a particular programming language.
output: The messages printed to the user by a program.
5
Compiling and interpreting
Many languages require you to compile (translate) your program
into a form that the machine understands.
compile execute
source code byte code output
Hello.java Hello.class
interpret
source code output
Hello.py
6
Operators
Anything after a # symbol is treated as a comment
Multi line comment
‘’’multiline
comment’’’ # triple quotes
+ addition
- subtraction
/ division
** exponentiation
% modulus (remainder after division)
Python has incorporated operators like +=, but ++ (or --) do not
work in Python
Number1 +=number2 ie a+=7
7
Arithmetic Operators
Operator Description Example
= Assignment num = 7
+ Addition num = 2 + 2
- Subtraction num = 6 - 4
* Multiplication num = 5 * 4
/ Division num = 25 / 5
// Division returns whole no. Num = 7// 2= 3
% Modulo num = 8 % 3 =2
If there are multiple operations that are on the same level then precedence goes
from left to right.
** Exponent
+, - Addition, subtraction
9
Bit wise operator
10
Membership operator
11
Order Of Operation And Style
Even for languages where there are clear rules of precedence (e.g., Java, Python) it is
regarded as good style to explicitly bracket your operations.
x = (a * b) + (c / d)
It not only makes it easier to read complex formulas but also a good habit for
languages where precedence is not always clear (e.g., C++, C).
12
Expressions
Example operators.py
print (2*2)
print (2**3)
print (10%3)
print (1.0/2.0)
print (1/2)
Output:
4
8
1
0.5
0
Note the difference between floating point division and integer
division in the last two lines
13
Type conversion
int(), float(), str(), and
bool() convert to integer,
floating point, string,
and boolean (True or
False) types,
respectively
Example typeconv.py: Output:
print 1.0/2.0 0.5
print 1/2 0
print float(1)/float(2) 0.5
print int(3.1415926) 3
print str(3.1415926) 3.1415926
print bool(1) True
print bool(0) False
14
Operators acting on strings
>>> "Ni!"*3 Output: 'Ni!Ni!Ni!'
>>> "hello " + "world!“ Output: 'hello world!‘
and, or, not
Note: We do NOT use &&, ||, !, as in C!
15
Expressions
expression: A data value or set of operations to compute a value.
Examples: 1 + 4 * 3
42
Arithmetic operators we will use:
+ - * / addition, subtraction/negation, multiplication,
division
% modulus, a.k.a. remainder
** exponentiation
16
Format
print('The area of the triangle is %0.2f' %area)
This will the value of area upto 2 places of decimam
17
Booleans: True and False
>>> type (True)
<type 'bool'>
>>> type (true)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'true' is not defined
>>> 2+2==5
False
Note: True and False are of type bool. The capitalization is
required for the booleans!
A boolean expression can be evaluated as True or False. An
expression evaluates to False if it is...
the constant False, the object None, an empty sequence or
collection, or a numerical item of value 0
Everything else is considered True
18
Expressions
expression: A data value or set of operations to compute a value.
Examples: 1 + 4 * 3
42
Arithmetic operators we will use:
+ - * / addition, subtraction/negation, multiplication,
division
% modulus, a.k.a. remainder
** exponentiation
19
Data types
Python is a loosely typed language. Therefore, no need to define the data type of
variables
No need to declare variable before using them
20
Data types: Number
21
Array
One of the most fundamental data structures in any language is the
array.
A matrix is a two-dimensional data structure. In real-world tasks you
often have to store rectangular data table. The table below shows
the marks of three students in different subjects.
23
Array(Negative index)
a = [['Roy',80,75,85,90,95], ['John',75,80,75,85,100], ['Dave',80,80,80,90,95]]
print(a[-1]) Output: ['Dave', 80, 80, 80, 90, 95]
print(a[-1][-2]) Output: 90
print(a[-2][-3]) Output: 75
24
Array(index) value modification
a = [['Roy',80,75,85,90,95], ['John',75,80,75,85,100], ['Dave',80,80,80,90,95]]
b=a[0]
print(b) Output: b=['Roy',80,75,85,90,95]
b[1]=75
print(b) Output: b=['Roy',75,75,85,90,95]
a[2]=['Sam',82,79,88,97,99]
print(a) [['Roy',75,75,85,90,95], ['John',75,80,75,85,100], ['Sam',82,79,88,97,99]]
a[0][4]=95
print(a) [['Roy',75,75,85,95,95], ['John',75,80,75,85,100], ['Sam',82,79,88,97,99]]
25
Array(Negative index)
a = [['Roy',80,75,85,90,95], ['John',75,80,75,85,100], ['Dave',80,80,80,90,95]]
print(a[-1]) Output: ['Dave', 80, 80, 80, 90, 95]
print(a[-1][-2]) Output: 90
print(a[-2][-3]) Output: 75
26
Expressions
expression: A data value or set of operations to compute a value.
Examples: 1 + 4 * 3
42
Arithmetic operators we will use:
+ - * / addition, subtraction/negation, multiplication,
division
% modulus, a.k.a. remainder
** exponentiation
27
Integer division
When we divide integers with / , the quotient is also an integer.
3 52
4 ) 14 27 ) 1425
12 135
2 75
54
21
More examples:
35 / 5 is 7
84 / 10 is 8
156 / 100 is 1
28
Real numbers
Python can also manipulate real numbers.
Examples: 6.022 -15.9997 42.0 2.143e17
When integers and reals are mixed, the result is a real number.
Example: 1 / 2.0 is 0.5
The conversion occurs on a per-operator basis.
7 / 3 * 1.2 + 3 / 2
2 * 1.2 + 3 / 2
2.4 + 3 / 2
2.4 + 1
3.4
29
Math commands
Python has useful commands for performing calculations.
Command name Description Constant Description
abs(value) absolute value e 2.7182818...
ceil(value) rounds up pi 3.1415926...
cos(value) cosine, in radians
floor(value) rounds down
log(value) logarithm, base e
log10(value) logarithm, base 10
max(value1, value2) larger of two values
min(value1, value2) smaller of two values
round(value) nearest whole number
sin(value) sine, in radians
sqrt(value) square root
Examples: x = 5
gpa = 3.14
x 5 gpa 3.14
A variable that has been given a value can be used in expressions.
x + 4 is 9
32
Reference Semantics
Assignment manipulates references
x = y does not make a copy of y
x = y makes x reference the object y references
Very useful; but beware!
Example:
>>> a = [1, 2, 3]
>>> b = a
>>> a.append(4)
>>> print b
[1, 2, 3, 4]
33
Changing a Shared List
a = [1, 2, 3]
a
1
2
3
a
b=a
1 2 3
b
a
a.append(4) 1 2 3 4
34
Changing an Integer
a=1 a
1
a
b=a
1
b new int object created
a 2
by assignment (a=...)
b
35
print
print : Produces text output on the console.
Syntax:
print ("Message“)
print (Expression)
Prints the given text message or expression value on the console, and
moves the cursor down to the next line.
Examples:
print ("Hello, world!“)
age = 45
print ("You have", 65 - age, "years until retirement“)
Output:
Hello, world!
You have 20 years until retirement
36
input
The computer program getting string information from the user.
Strings cannot be used for calculations (information getting numeric input will
provided shortly).
Format:
<variable name> = input()
OR
<variable name> = input("<Prompting message>")
Example:
Program name: input1.py
37
input
input : Reads a number from user input.
You can assign (store) the result of input into a variable.
Example:
age = input("How old are you? ")
print "Your age is", age
print "You have", 65 - age, "years until retirement"
Output:
How old are you? 53
Your age is 53
You have 12 years until retirement
38
input
input : Reads a number from user input.
You can assign (store) the result of input into a variable.
Example:
age = input("How old are you? ")
print "Your age is", age
print "You have", 65 - age, "years until retirement"
Output:
How old are you? 53
Your age is 53
You have 12 years until retirement
39
Repetition (loops)
and Selection (if/else)
40
Control Flow
Things that are False
The boolean value False
The empty list [], empty dictionary {} and empty set set().
41
The for loop
for loop: Repeats a set of statements over a group of values.
Syntax:
for variableName in groupOfValues:
statements
We indent the statements to be repeated with tabs or spaces.
variableName gives a name to each value, so you can refer to it in the statements.
groupOfValues can be a range of integers, specified with the range function.
Example:
for x in range(1, 6):
print x, "squared is", x * x
Output:
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
42
The for loop
>>> for value in [3, 1, 4, 1, 5, 9, 2]:
... print "Checking", value
... if value > 8: Checking 3
... print "Exiting for loop" The square is 9
... break Checking 1
... elif value < 3:
Ignoring
... print "Ignoring"
... continue Checking 4
... print "The square is", value**2 The square is 16
...
Checking 1
Use “break” to stop
Ignoring
the for loop
Checking 5
The square is 25
Use “continue” to
Checking 9
stop
Exiting for loop
processing the
>>>
current item
43
The for loop
for loop: Repeats a set of statements over a group of values.
Syntax:
for variableName in groupOfValues:
statements
We indent the statements to be repeated with tabs or spaces.
variableName gives a name to each value, so you can refer to it in the statements.
groupOfValues can be a range of integers, specified with the range function.
Example:
for x in range(1, 6):
print x, "squared is", x * x
Output:
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
44
range
The range function specifies a range of integers:
range(start, stop) - the integers between start (inclusive)
and stop (exclusive)
It can also accept a third value specifying the change between values.
range(start, stop, step) - the integers between start (inclusive)
and stop (exclusive) by step
Example:
for x in range(5, 0, -1):
print x
print "Blastoff!"
Output:
5
4
3
2
1
Blastoff!
Exercise: How would we print the "99 Bottles of Beer" song?
45
Cumulative loops
Some loops incrementally compute a value that is initialized outside
the loop. This is sometimes called a cumulative sum.
sum = 0
for i in range(1, 11):
sum = sum + (i * i)
print "sum of first 10 squares is", sum
Output:
sum of first 10 squares is 385
46
if
if statement: Executes a group of statements only if a certain
condition is true. Otherwise, the statements are skipped.
Syntax:
if condition:
statements
Example:
gpa = 3.4
if gpa > 2.0:
print "Your application is accepted.“
Range Test
if (3 <= Time <= 5):
print “Office Hour"
47
if/else
if/else statement: Executes one block of statements if a certain
condition is True, and a second block of statements if it is False.
Syntax:
if condition:
statements
else:
statements
Example:
gpa = 1.4
if gpa > 2.0:
print "Welcome to Mars University!"
else:
print "Your application is denied."
Bingo!
---
---
---
In Python: In C: 3
---
---
6
if i%3 == 0: { ---
if (i%3 == 0) { ---
print i ---
printf("%d\n", i); 9
if i%5 == 0: ---
if (i%5 == 0) {
---
print "Bingo!"
printf("Bingo!\ ---
---
} ---
---
printf("---\n");
15
} Bingo!
---
---
---
18
---
---
49
while
while loop: Executes a group of statements as long as a condition is True.
good for indefinite loops (repeat an unknown number of times)
Syntax:
while condition:
statements
Example:
number = 1
while number < 200:
print number,
number = number * 2
Output:
1 2 4 8 16 32 64 128
50
Logic
Many logical expressions use relational operators:
Operator Meaning Example Result
== equals 1 + 1 == 2 True
!= does not equal 3.2 != 2.5 True
< less than 10 < 5 False
> greater than 10 > 5 True
<= less than or equal to 126 <= 100 False
>= greater than or equal to 5.0 >= 5.0 True
52
Text and File Processing
53
Strings
string: A sequence of text characters in a program.
Strings start and end with quotation mark " or apostrophe ' characters.
Examples:
"hello"
"This is a string"
"This, too, is a string. It can be very long!"
A string may not span across multiple lines or contain a " character.
"This is not
a legal String."
"This is not a "legal" String either."
54
Strings
"hello"+"world" "helloworld" #
concatenation
"hello"*3 "hellohellohello" # repetition
"hello"[0] "h" # indexing
"hello"[-1] "o" # (from end)
"hello"[1:4] "ell" # slicing
len("hello") 5 # size
"hello" < "jello" 1 # comparison
"e" in "hello" 1 # search
"escapes: \n etc, \033 etc, \if etc"
'single quotes' """triple quotes""" r"raw strings"
55
List
In Python programming, a list is created by placing all the items (elements)
inside a square bracket [ ], separated by commas.
A Lists in Python language can be compared to arrays in Java but they are
different in many other aspects.
Lists in python are zero indexed. This means, you can access individual elements in a list just as
you would do in an array. Here is an example :
>>> myList[0] Output: 'The'
>>> myList[4] Output: 'sun‘
>>> myList[-1] Output: 'sun‘
print ("lmyist[1:5]: ", mylist[1:5])
56
List
2. Add Elements to a List
One can use the method insert, append and extend to add elements to a List.
The insert method expects an index and the value to be inserted. Here is an example
of insert :
>>> myList.insert(0,"Yes")
>>> myList Output: ['Yes', 'The', 'earth', 'revolves', 'around', 'sun']
value ‘yes’ was inserted at the index 0 in the list and all the other elements were
shifted accordingly.
The append method can take one or more elements as input and appends them into the
list. Here is an example :
>>> myList.append(["a", "true"])
>>> myList Output:['Yes', 'The', 'earth', 'revolves', 'around', 'sun', ['a', 'true']]
two values were appended towards the end of the list
The extend method. Like append, it also expects one or more values as input. But, unlike
append, all the elements are added as individual elements. Here is an example :
>>> myList.extend(["statement", "for", "sure"])
>>> myList
['Yes', 'The', 'earth', 'revolves', 'around', 'sun', ['a', 'true'], 'statement', 'for', 'sure']
>>> len(myList) Output: 10
57
Slice Elements from a List
You can access a part of complete list by using index range.
If it is required to access a sub-list from index 1 to index 3 then it can be done in following way:
>>> myList[1:4] Output: ['The', 'earth', 'revolves']
>>> myList[:]
['Yes', 'The', 'earth', 'revolves', 'around', 'sun', ['a', 'true'], 'statement', 'for', 'sure']
58
4. Search the Lists and find Elements
myList :['Yes', 'The', 'earth', 'revolves', 'around', 'sun', ['a', 'true']]
Lists can easily be searched for values using the index method that expects a
value that is to be searched. The output is the index at which the value is
kept.
59
5. Delete Elements from the List
>>> myList
['Yes', 'The', 'earth', 'revolves', 'around', 'sun', ['a', 'true'], 'statement', 'for',
'sure']
>>> myList.remove("Yes")
>>> myList
['The', 'earth', 'revolves', 'around', 'sun', ['a', 'true'], 'statement', 'for', ‘Sure’]
>>> myList.remove("statement")
>>> myList
['The', 'earth', 'revolves', 'around', 'sun', ['a', 'true'], 'for', 'sure']
60
5. Delete Elements from the List
If it is required to access the last element and then to delete it, this can be
done through pop method.
>>> myList.pop() 'sure‘
>>> myList
['The', 'earth', 'revolves', 'around', 'sun', 'for']
61
6. Python List Operators
Python allows to use mathematical operators like +, * etc to be used with
lists.
62
List
A compound data type:
[0]
[2.3, 4.5]
[5, "Hello", "there", 9.8]
[]
Use len() to get the length of a list
>>> names = [“Ben", “Chen", “Yaqin"]
>>> len(names)
3
>>> names[0]
‘Ben' [0] is the first item.
>>> names[1]
[1] is the second item
‘Chen'
>>> names[2] ...
‘Yaqin'
>>> names[3]
Traceback (most recent call last):
Out of range values
File "<stdin>", line 1, in <module> raise an exception
65
zipping lists together
>>> names
['ben', 'chen', 'yaqin']
66
Multi Dimension Array
Example 10: Create a two-dimensional array using lists
multd = [[1,2], [3,4], [5,6], [7,8]]
print(multd[0]) Output: [1, 2]
print(multd[3]) Output: [7, 8]
print(multd[2][1]) 6
print(multd[3][0]) 7
all()Return True if all elements of the list are true (or if the list is
empty).
any()Return True if any element of the list is true. If the list is
empty, return False.
enumerate()Return an enumerate object. It contains the index and
value of all the items of list as a tuple.
67
Functions of list
Methods Functions
append() to add element to the end of the list a.append(5)
68
# Count the occurrences of the number 4
print([1, 2, 9, 4, 5, 4, 1].count(4))
# Count the occurrences of the letter "a“
list = ["d", "a", "t", "a", "c", "a", "m", "p"]
list.count("a")
69
Dictionaries
Python programs or scripts without lists and dictionaries are nearly
inconceivable.
Like lists dictionaries can easily be changed, can be shrunk and
grown ad libitum at run time. They shrink and grow without the
necessity of making copies.
Dictionaries can be contained in lists and vice versa
Lists are ordered sets of objects, whereas dictionaries are
unordered sets
main difference is that items in dictionaries are accessed via keys
and not via their position
A dictionary is an associative array (also known as hashes). Any key
of the dictionary is associated (or mapped) to a value. The values of a
dictionary can be any Python data type. So dictionaries are
unordered key-value-pairs.
70
Dictionaries
Dictionaries are lookup tables.
>>> empty = {}
>>> empty Output : {}
They map from a “key” to a “value”.
symbol_to_name = {"H": "hydrogen“, "He": "helium", "Li": "lithium“,
"C": "carbon“, "O": "oxygen", "N": "nitrogen“ }
To add one element in a dictionaries
>>> symbol_to_name [“P"] = “phosphorus“
Example:s
ymbol_to_name = {'H': 'hydrogen', 'He': 'helium', 'Li': 'lithium','C': 'carbon',
'O': 'oxygen', 'N': 'nitrogen'}
print(symbol_to_name)
symbol_to_name['P']="Phosphorus"
print(symbol_to_name)
print(symbol_to_name["H"]) output: hydrogen
print(symbol_to_name[0]) output: error
Duplicate keys are not allowed
Duplicate values are just fine
71
Operators on Dictionaries
Operator Explanation
len(d) returns the number of stored entries, i.e. the
number of (key,value) pairs.
del d[k] deletes the key k together with his value
k in d True, if a key k exists in the dictionary d
k not in d True, if a key k doesn't exist in the dictionary d
72
Update: Merging Dictionaries
>>> w1 = {"red":"rouge","blau":"bleu"}
>>> w.update(w1)
>>> print w
73
Keys can be any immutable value numbers, strings, tuples,
frozenset, not list, dictionary, set, ...
atomic_number_to_name = { A set is an unordered collection
1: "hydrogen",
with no duplicate elements.
6: "carbon",
7: "nitrogen",
8: "oxygen",
}
print(atomic_number_to_name)
nobel_prize_winners = {
(1979, "physics"): ["Glashow", "Salam", "Weinberg"],
(1962, "chemistry"): ["Hodgkin"],
(1984, "biology"): ["McClintock"],
}
print(nobel_prize_winners)
74
Dictionary
>>> symbol_to_name["C"] Get the value for a given
'carbon' key
>>> "O" in symbol_to_name, "U" in symbol_to_name
(True, False)
>>> "oxygen" in symbol_to_name Test if the key exists
75
Some useful dictionary methods
>>> symbol_to_name.keys() ['C', 'H', 'O', 'N', 'Li', 'He']
>>> symbol_to_name.values()
['carbon', 'hydrogen', 'oxygen', 'nitrogen', 'lithium', 'helium']
For loop
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
print(squares[i])
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(squares[0]) This gives an error
76
Dictionary
In Dictionary we store data in key value pair. No position value
like a list.
We can store any data types.
A={} # this is a empty dictionary
A={“amit”, “sumit”, “suman”} # Not a valid dictionary
A={“k1”: “amit”, “k2” : “India”, “k3” :“22} # Dictionary
77
Dictionary
A={“k1”: “amit”, “k2” : “India”, “k3” :“22}
For loop
for I in A.keys():
print(i) prints k1, k2, k3
for I in A.values():
print(i) prints amit, India, 22
78
Set
Python offers a datatype called set whose elements must be unique.
79
Set
# Program to perform different set operations like in mathematics
# set union
print("Union of E and N is",E | N)
# set intersection
print("Intersection of E and N is",E & N)
# set difference
print("Difference of E and N is",E - N)
80
Directories
Hash tables, "associative arrays"
d = {"duck": "eend", "water": "water"}
Lookup:
d["duck"] -> "eend"
d["back"] # raises KeyError exception
Delete, insert, overwrite:
del d["water"] # {"duck": "eend", "back": "rug"}
d["back"] = "rug" # {"duck": "eend", "back": "rug"}
d["duck"] = "duik" # {"duck": "duik", "back": "rug"}
81
Directories
Hash tables, "associative arrays"
d = {"duck": "eend", "water": "water"}
Lookup:
d["duck"] -> "eend"
d["back"] # raises KeyError exception
Delete, insert, overwrite:
del d["water"] # {"duck": "eend", "back": "rug"}
d["back"] = "rug" # {"duck": "eend", "back": "rug"}
d["duck"] = "duik" # {"duck": "duik", "back": "rug"}
82
More Dictionary Ops
Keys, values, items:
d.keys() -> ["duck", "back"]
d.values() -> ["duik", "rug"]
d.items() -> [("duck","duik"), ("back","rug")]
Presence check:
d.has_key("duck") -> 1; d.has_key("spam") -> 0
Values of any type; keys almost any
{"name":"Guido", "age":43, ("hello","world"):1,
42:"yes", "flag": ["red","white","blue"]}
83
print "list2[1:5]: ", list2[1:5]
Tuples
A tuple is a sequence of immutable Python objects.
Tuples are sequences, just like lists.
The differences between tuples and lists are, the tuples cannot be
changed
tuples use parentheses(small and culry), whereas lists use square
brackets.
Creating a tuple is as simple as putting different comma-separated
values.
Optionally you can put these comma-separated values between
parentheses also. For example −
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
print(tup1) Output:('physics', 'chemistry', 1997, 2000)
print(tup2) Output:(1, 2, 3, 4, 5)
print(tup3) Output:('a', 'b', 'c', 'd')
84
print "list2[1:5]: ", list2[1:5]
Tuples
tup2 = (1, 2, 3, 4, 5 );
print(tup2[1]) Output: 2
Like string indices, tuple indices start at 0, and they can be sliced,
concatenated, and so on.
>>> x, y = 1, 2
>>> x Output: 1
>>> y Output: 2
85
print "list2[1:5]: ", list2[1:5]
Output
tup1[0]: physics
tup2[1:5]: (2, 3, 4, 5)
86
print "list2[1:5]: ", list2[1:5]
Updating Tuples
Tuples are immutable which means you cannot update or change
the values of tuple elements.
You are able to take portions of existing tuples to create new tuples
as the following example demonstrates −
88
print "list2[1:5]: ", list2[1:5]
89
print "list2[1:5]: ", list2[1:5]
90
print "list2[1:5]: ", list2[1:5]
91
print "list2[1:5]: ", list2[1:5]
No Enclosing Delimiters
Any set of multiple objects, comma-separated, written without
identifying symbols, i.e., brackets for lists, parentheses for tuples,
etc., default to tuples, as indicated in these short examples −
Value of x , y : 1 2
92
print "list2[1:5]: ", list2[1:5]
Tuples
key = (lastname, firstname)
point = x, y, z # parentheses optional
x, y, z = point # unpack
lastname = key[0]
singleton = (1,) # trailing comma!!!
empty = () # parentheses!
tuples vs. lists; tuples immutable
>>> names
['ben', 'chen', 'yaqin']
93
Tuples assignment in For loop
data = [ ("C20H20O3", 308.371),
("C22H20O2", 316.393),
("C24H40N4O2", 416.6),
("C14H25N5O3", 311.38),
("C15H20O2", 232.3181)]
94
Tuples: sort of an immutable list
>>> yellow = (255, 255, 0) # r, g, b
>>> one = (1,)
>>> yellow[0]
>>> yellow[1:]
(255, 0)
>>> yellow[0] = 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
95
Directories
Hash tables, "associative arrays"
d = {"duck": "eend", "water": "water"}
Lookup:
d["duck"] -> "eend"
d["back"] # raises KeyError exception
Delete, insert, overwrite:
del d["water"] # {"duck": "eend", "back": "rug"}
d["back"] = "rug" # {"duck": "eend", "back": "rug"}
d["duck"] = "duik" # {"duck": "duik", "back": "rug"}
Dictionaries are lookup tables.
They map from a “key” to a “value”.
symbol_to_name = {
"H": "hydrogen",
"He": "helium",
"Li": "lithium",
"C": "carbon",
"O": "oxygen",
"N": "nitrogen"
}
Duplicate keys are not allowed
Duplicate values are just fine 96
Indexes
Characters in a string are numbered with indexes starting at 0:
Example:
name = "P. Diddy"
index 0 1 2 3 4 5 6 7
characte P . D i d d y
r
Output:
P. Diddy starts with P
97
String properties
len(string) - number of characters in a string
(including spaces)
str.lower(string) - lowercase version of a string
str.upper(string) - uppercase version of a string
Example:
name = "Martin Douglas Stepp"
length = len(name)
big_name = str.upper(name)
print big_name, "has", length, "characters"
Output:
MARTIN DOUGLAS STEPP has 20 characters
98
String operators: in, not in
if "Br" in “Brother”:
print "contains brother“
email_address = “clin”
if "@" not in email_address:
email_address += "@brandeis.edu“
email_address = “clin”
if "@" not in email_address:
email_address += "@brandeis.edu“
>>> “chen".upper()
‘CHEN'
101
Unexpected things about strings
>>> s = "andrew"
>>> s[0] = "A"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> s = "A" + s[1:]
>>> s
'Andrew‘
102
“\” is for special characters
\n -> newline
\t -> tab
\\ -> backslash
...
But Windows uses backslash for directories!
filename = "M:\nickel_project\reactive.smi" # DANGER!
filename = "M:\\nickel_project\\reactive.smi" # Better!
filename = "M:/nickel_project/reactive.smi" # Usually works
103
More String methods
email.startswith(“c") endswith(“u”)
True/False
>>> “chen".upper()
‘CHEN'
104
Lists are mutable - some useful methods
>>> ids = ["9pti", "2plv", "1crn"]
>>> ids.append("1alm")
>>> ids append an element
['9pti', '2plv', '1crn', '1alm']
>>>ids.extend(L)
Extend the list by appending remove an
all the items inelement
the given list;
equivalent to a[len(a):] = L.
>>> del ids[0]
>>> ids
sort by default order
['2plv', '1crn', '1alm']
>>> ids.sort()
>>> ids
['1alm', '1crn', '2plv'] reverse the elements in a list
>>> ids.reverse()
>>> ids
['2plv', '1crn', '1alm'] insert an element at some
>>> ids.insert(0, "9pti")
specified position.
>>> ids
['9pti', '2plv', '1crn', '1alm']
(Slower than .append()) 105
106
More String methods
email.startswith(“c") endswith(“u”)
True/False
>>> “chen".upper()
‘CHEN'
107
String properties
len(string) - number of characters in a string
(including spaces)
str.lower(string) - lowercase version of a string
str.upper(string) - uppercase version of a string
Example:
name = "Martin Douglas Stepp"
length = len(name)
big_name = str.upper(name)
print big_name, "has", length, "characters"
Output:
MARTIN DOUGLAS STEPP has 20 characters
108
raw_input
raw_input : Reads a string of text from user input.
Example:
name = raw_input("Howdy, pardner. What's yer name? ")
print name, "... what a silly name!"
Output:
Howdy, pardner. What's yer name? Paris Hilton
Paris Hilton ... what a silly name!
109
Text processing
text processing: Examining, editing, formatting text.
often uses loops that examine the characters of a string one by one
110
Strings and numbers
ord(text) - converts a string into a number.
Example: ord("a") is 97, ord("b") is 98, ...
Characters map to numbers using standardized mappings such as
ASCII and Unicode.
111
Functions, Procedures
def name(arg1, arg2, ...):
"""documentation""" # optional doc string
statements
112
Example Function
def gcd(a, b):
"greatest common divisor"
while a != 0:
a, b = b%a, a # parallel assignment
return b
>>> gcd.__doc__
'greatest common divisor'
>>> gcd(12, 20)
4
113
Classes
class name:
"documentation"
statements
-or-
class name(base1, base2, ...):
...
Most, statements are method definitions:
def name(self, arg1, arg2, ...):
...
May also be class variable assignments
114
Example class
class Stack:
"A well-known data structure…"
def __init__(self): # constructor
self.items = []
def push(self, x):
self.items.append(x) # the sky is the limit
def pop(self):
x = self.items[-1] # what happens if it’s empty?
del self.items[-1]
return x
def empty(self):
return len(self.items) == 0 # Boolean result
115
Using Classes
To create an instance, simply call the class object:
x = Stack() # no 'new' operator!
116
Sub classing
class FancyStack(Stack):
"stack with added ability to inspect inferior stack items"
117
Sub classing 2
class LimitedStack(FancyStack):
"fancy stack with limit on stack size"
118
Class / Instance Variables
class Connection:
verbose = 0 # class variable
def __init__(self, host):
self.host = host # instance variable
def debug(self, v):
self.verbose = v # make instance variable!
def connect(self):
if self.verbose: # class or instance variable?
print "connecting to", self.host
119
Instance Variable Rules
On use via instance (self.x), search order:
(1) instance, (2) class, (3) base classes
this also works for method lookup
own
120
Modules
Collection of stuff in foo.py file
functions, classes, variables
Importing modules:
import re; print re.match("[a-z]+", s)
from re import match; print match("[a-z]+", s)
try:
i = int("snakes")
print "the integer is", i
except ValueError:
print "oops! invalid value"
Other exceptions
EOFError is raised at the end of a file
IndexError happens if we use an invalid index for a
string/collection, e.g., if we try to get argv[1] if there is only one
command-line argument (counting starts from zero)
TypeError happens when, e.g., comparing two incomparable types
Catching Exceptions
def foo(x):
return 1/x
def bar(x):
try:
print foo(x)
except ZeroDivisionError, message:
print "Can’t divide by zero:", message
bar(0)
Try-finally: Cleanup
f = open(file)
try:
process_file(f)
finally:
f.close() # always executed
print "OK" # executed on success only
Raising Exceptions
raise IndexError
raise IndexError("k out of range")
raise IndexError, "k out of range"
try:
something
except: # catch everything
print "Oops"
raise # reraise
Raising Exceptions
>>> mode = "absolute"
>>> if mode == "canonical":
... smiles = "canonical"
... elif mode == "isomeric":
... smiles = "isomeric”
... elif mode == "absolute":
... smiles = "absolute"
... else:
... raise TypeError("unknown mode")
...
>>> smiles
' absolute '
>>>
“raise” is the Python way to raise exceptions
More on Exceptions
User-defined exceptions
subclass Exception or any other standard exception
Old Python: exceptions can be strings
WATCH OUT: compared by object identity, not ==
Last caught exception info:
sys.exc_info() == (exc_type, exc_value, exc_traceback)
Last uncaught exception (traceback printed):
sys.last_type, sys.last_value, sys.last_traceback
Printing exceptions: traceback module
File Objects
f = open(filename[, mode[, buffersize])
mode can be "r", "w", "a" (like C stdio); default "r"
append "b" for text translation mode
append "+" for read/write open
buffersize: 0=unbuffered; 1=line-buffered; buffered
methods:
read([nbytes]), readline(), readlines()
write(string), writelines(list)
seek(pos[, how]), tell()
flush(), close()
fileno()
Standard Library
Core:
os, sys, string, getopt, StringIO, struct,
pickle, ...
Regular expressions:
re module; Perl-5 style patterns and matching
rules
Internet:
socket, rfc822, httplib, htmllib, ftplib, smtplib,
...
Miscellaneous:
pdb (debugger), profile+pstats
Tkinter (Tcl/Tk interface), audio, *dbm, ...
Python 2.0: What's New
Augmented assignment: x += y
List comprehensions:
[s.strip() for s in f.readlines()]
Extended print: print >>sys.stderr, "Hello!"
Extended import: import foo as bar
Unicode strings: u"\u1234"
New re implementation (faster, Unicode)
Collection of cyclic garbage
XML, distutils
Python 2.1: What's New
From __future__ import nested_scopes
def make_adder(n):
def adder(x): return x+n
return adder
add2 = make_adder(2)
add2(10) == 12
Rich comparisons
Overload <, <=, ==, !=, >=, > separately
Warnings framework
Prepare for the future
Python 2.2: What's New
Iterators and Generators
from __future__ import generators
def inorder(tree):
if tree:
for x in inorder(tree.left): yield x
yield tree.label
for x in inorder(tree.right): yield x
Type/class unification
class mydict(dict): …
Fix division operator so 1/2 == 0.5; 1//2 == 0
Requires __future__ statement in Python 2.x
Change will be permanent in Python 3.0
URLs
http://www.python.org
official site
http://starship.python.net
Community
http://www.python.org/psa/bookstore/
(alias for http://www.amk.ca/bookstore/)
Python Bookstore
Further Reading
Example:
file_text = open("bankaccount.txt").read()
138
Line-by-line processing
Reading a file line-by-line:
for line in open("filename").readlines():
statements
Example:
count = 0
for line in open("bankaccount.txt").readlines():
count = count + 1
print "The file contains", count, "lines."
139
“import” and “from ... import ...”
>>> import math
math.cos
>>> from math import cos, pi
cos
>>> from math import *
140
Line-by-line processing
Reading a file line-by-line:
for line in open("filename").readlines():
statements
Example:
count = 0
for line in open("bankaccount.txt").readlines():
count = count + 1
print "The file contains", count, "lines."
141
Graphics
14
DrawingPanel
To create a window, create a drawingpanel and its graphical pen,
which we'll call g :
from drawingpanel import *
panel = drawingpanel(width, height)
g = panel.get_graphics()
... (draw shapes here) ...
panel.mainloop()
The window has nothing on it, but we can draw shapes and
lines on it by sending commands to g .
Example:
g.create_rectangle(10, 30, 60, 35)
g.create_oval(80, 40, 50, 70)
g.create_line(50, 50, 90, 70)
143
Graphical commands
Command Description
g.create_line(x1, y1, x2, y2) a line between (x1, y1), (x2, y2)
g.create_oval(x1, y1, x2, y2) the largest oval that fits in a box with
top-left corner at (x1, y1) and bottom-
left corner at (x2, y2)
g.create_rectangle(x1, y1, x2, y2) the rectangle with top-left corner at
(x1, y1), bottom-left at (x2, y2)
g.create_text(x, y, text="text") the given text at (x, y)
The above commands can accept optional outline and fill colors.
g.create_rectangle(10, 40, 22, 65, fill="red", outline="blue")
(200, 100)
144
Drawing with loops
We can draw many repetitions of the same item at different x/y
positions with for loops.
The x or y assignment expression contains the loop counter, i, so that
in each pass of the loop, when i changes, so does x or y.
from drawingpanel import *
window.mainloop()
145
What's Next?
14
Further programming
Lab exercises
Let's go downstairs to the basement computer labs!
All resources are available at the following URL:
http://faculty.washington.edu/stepp/cs4hs/
What next?
Arrays, data structures
Algorithms: searching, sorting, recursion, etc.
Objects and object-oriented programming
Graphical user interfaces, event-driven programming
147