0% found this document useful (0 votes)
18 views147 pages

Pythongoodppt 2024 07 04 09 15 51

The document provides an introduction to programming with Python, covering key programming languages, Python versions, and development environments. It explains programming basics, including syntax, operators, and data types, as well as how Python interprets code. Additionally, it discusses arrays, expressions, and mathematical commands used in Python programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views147 pages

Pythongoodppt 2024 07 04 09 15 51

The document provides an introduction to programming with Python, covering key programming languages, Python versions, and development environments. It explains programming basics, including syntax, operators, and data types, as well as how Python interprets code. Additionally, it discusses arrays, expressions, and mathematical commands used in Python programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 147

Introduction to Programming

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

 “Jython” is written in Java for the JVM


 “IronPython” is written in C# for the .Net environment

3
Development Environments
what IDE to use? http://stackoverflow.com/questions/81584

1.PyDev with Eclipse


2. Komodo
3. Emacs
4. Vim
5. TextMate
6. Gedit
7. Idle
8. PIDA (Linux)(VIM Based)
9. NotePad++ (Windows)
10.BlueFish (Linux)

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.

 console: The text box onto which output is printed.


 Some source code editors pop up the console as an external window,
and others contain their own console window.

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

 Python is instead directly interpreted into machine instructions.

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

** Exponent num = 9 ** 2 =81


8
Order Of Operation
 First level of precedence: top to bottom
 Second level of precedence

 If there are multiple operations that are on the same level then precedence goes
from left to right.

() Brackets (inner before outer)

** Exponent

*, /, % Multiplication, division, modulo

+, - 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

>>> 2+2==5 or 1+1==2 Output: True


>>> 2+2==5 and 1+1==2 Output: False
>>> not(2+2==5) and 1+1==2 Output: True


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

 precedence: Order in which operations are computed.


 * / % ** have a higher precedence than + -
1 + 3 * 4 is 13
 Parentheses can be used to force a certain order of evaluation.
(1 + 3) * 4 is 16

16
Format
 print('The area of the triangle is %0.2f' %area)
 This will the value of area upto 2 places of decimam

 print('The sum of {0} and {1} is {2}'.format(num1,


num2, sum))

 Enter first number: 21


 Enter second number: 13
 The sum of 21 and 13 is 34.0

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

 precedence: Order in which operations are computed.


 * / % ** have a higher precedence than + -
1 + 3 * 4 is 13
 Parentheses can be used to force a certain order of evaluation.
(1 + 3) * 4 is 16

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.

 Python doesn't have a native array data structure, but it has


the list which is much more general and can be used as a
multidimensional array quite easily.
 List basics
 A list in Python is just an ordered collection of items which can be of any
type.
 By comparison an array is an ordered collection of items of a single type -
so in principle a list is more flexible than an array but it is this flexibility that
makes things slightly harder when you want to work with a regular
structure.
 A list is also a dynamic mutable type and this means you can add and
delete elements from the list at any time. 22
Array
 For example:
 A = [['Roy',80,75,85,90,95],['John',75,80,75,85,100],['Dave',80,80,80,90,95]]

 In the above example A represents a 3*6 matrix where 3 is number


of rows and 6 is number of columns.
 # a is 2-D matrix with integers
 a = [['Roy',80,75,85,90,95], ['John',75,80,75,85,100], ['Dave',80,80,80,90,95]]

 #b is a nested list but not a matrix


 b= [['Roy',80,75,85,90,95], ['John',75,80,75], ['Dave',80,80,80,90,95]]

 In the above examples a is a matrix as well as nested list where


as b is a nested list but not a matrix.(elements are not equal

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

 precedence: Order in which operations are computed.


 * / % ** have a higher precedence than + -
1 + 3 * 4 is 13
 Parentheses can be used to force a certain order of evaluation.
(1 + 3) * 4 is 16

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

 The % operator computes the remainder from a division of integers.


3 43
4 ) 14 5 ) 218
12 20
2 18
15
3

28
Real numbers
 Python can also manipulate real numbers.
 Examples: 6.022 -15.9997 42.0 2.143e17

 The operators + - * / % ** ( ) all work for real numbers.


 The / produces an exact answer: 15.0 / 2.0 is 7.5
 The same rules of precedence also apply to real numbers:
Evaluate ( ) before * / % before + -

 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

 To use many of these commands, you must write the following at


the top of your Python program:
from math import *
30
Variables
 variable: A named piece of memory that can store a value.
 Usage:

Compute an expression's result,

store that result into a variable,

and use that variable later in the program.

 assignment statement: Stores a value into a variable.


 Syntax:
name = value

 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

 Exercise: Evaluate the quadratic equation for a given a, b, and c.


31
Variables
 No need to declare
 Need to assign (initialize)

use of uninitialized variable raises exception
 Not typed
if friendly: greeting = "hello world"
else: greeting = 12**2
print greeting
 Everything is a "variable":

Even functions, classes, modules

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

by add operator (1+1)


 a 2

 a = a+1 old reference deleted


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.

print (Item1, Item2, ..., ItemN)


 Prints several messages and/or expressions on the same 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

print ("What is your name: ")


name = input ()
OR
name = input ("What is your name: ")

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

 Exercise: Write a Python program that prompts the user for


his/her amount of money, then reports how many Nintendo Wiis
the person can afford, and how much more money he/she will
need to afford an additional Wii.

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

 Exercise: Write a Python program that prompts the user for


his/her amount of money, then reports how many Nintendo Wiis
the person can afford, and how much more money he/she will
need to afford an additional Wii.

39
Repetition (loops)
and Selection (if/else)

40
Control Flow
Things that are False
 The boolean value False

 The numbers 0 (integer), 0.0 (float) and 0j (complex).

 The empty string "".

 The empty list [], empty dictionary {} and empty set set().

Things that are True


 The boolean value True

 All non-zero numbers.

 Any string containing at least one character.

 A non-empty data structure.

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

 Exercise: Write a Python program that computes the factorial of an


integer.

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."

 Multiple conditions can be chained with elif ("else if"):


if condition:
statements
elif condition:
statements
else:
statements
48
Grouping Indentation
0

Bingo!

---

---

---

In Python: In C: 3

---

---

for i in range(20): for (i = 0; i < 20; i++) ---


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!\ ---

print "---" n"); } 12


---

} ---

---
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

 Logical expressions can be combined with logical operators:


Operator Example Result
and 9 != 6 and 2 < 3 True
or 2 == 3 or -1 < 5 True
not not 7 > 0 False

 Exercise: Write code to display and count the factors of a number.


51
Boolean Logic
Python expressions can have “and”s and “or”s:
if (ben <= 5 and chen >= 10 or
chen == 500 and ben != 5):
print “Ben and Chen“

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."

 A string can represent characters by preceding them with a backslash.



\t tab character

\n new line character

\" quotation mark character

\\ backslash character

Example: "Hello\tthere\nHow are you?"

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.

1. Create a Python List


>>> myList = ["The", "earth", "revolves", "around", "sun"]
>>> myList Output: ['The', 'earth', 'revolves', 'around', 'sun']

 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[:4] Output: ['Yes', 'The', 'earth', 'revolves']

 >>> myList[4:] ['around', 'sun', ['a', 'true'], 'statement', 'for', 'sure']

 >>> 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.

 Here we try to search the list for value ‘revolves’.


 >>> myList.index("revolves") Output: 3

 search a sub list :


 >>> myList.index(["a", "true"]) Output: 6

 If it is desired to just whether an element is present in a list, it can be done


in following way :
 >>> "sun" in myList Output: True

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']

 Here is how a sub list can be deleted :


 >>> myList.remove(["a", "true"])
 >>> myList ['The', 'earth', 'revolves', 'around', 'sun', '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.

 >>> myList ['The', 'earth', 'revolves', 'around', 'sun', 'for']

 >>> myList = myList + ["sure"]


 >>> myList ['The', 'earth', 'revolves', 'around', 'sun', 'for',
'sure']

 >>> myList += ["."]


 >>> myList ['The', 'earth', 'revolves', 'around', 'sun', 'for', 'sure', '.']
 >>> myList *= 2
 >>> myList
 ['The', 'earth', 'revolves', 'around', 'sun', 'for', 'sure', '.', 'The', 'earth',
'revolves', 'around', 'sun', 'for', 'sure', '.']

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

 Flexible arrays, not Lisp-like linked lists



a = [99, "bottles of beer", ["on", "the", "wall"]]
 Same operators as for strings

a+b, a*3, a[0], a[-1], a[1:], len(a)
 Item and slice assignment

a[0] = 98

a[1:2] = ["bottles", "of", "beer"]
-> [98, "bottles", "of", "beer", ["on", "the", "wall"]]

del a[-1] # -> [98, "bottles", "of", "beer"]
63
More List operation
mylist1= []
for i in range(10):
i=input("enter values")
mylist1=mylist1 +[i]
print(mylist1)

>>> a = range(5) # [0,1,2,3,4]


>>> a.append(5) # [0,1,2,3,4,5]
>>> a.pop() # [0,1,2,3,4]
5
>>> a.insert(0, 42) # [42,0,1,2,3,4]
>>> a.pop(0) # [0,1,2,3,4]
5.5
>>> a.reverse() # [4,3,2,1,0]
>>> a.sort() # [0,1,2,3,4]
64
Use [ ] to index items in the list

>>> 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

IndexError: list index out of range


>>> names[-1]
‘Yaqin'
Negative values
>>> names[-2] go backwards from

‘Chen' the last element.


>>> names[-3]
‘Ben'

65
zipping lists together
>>> names
['ben', 'chen', 'yaqin']

>>> gender = [0, 0, 1]

>>> zip(names, gender)


[('ben', 0), ('chen', 0), ('yaqin', 1)]

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)

extend() to extend all elements of a list to the another list

insert() to insert an element at the another index


remove() to remove an element from the list

pop() to remove elements return element at the given index

clear() to remove all elements from the list

index() to return the index of the first matched element

count() to count of number of elements passed as an argument

sort() to sort the elements in ascending order by default

reverse() to reverse order element in a list


copy() to return a copy of elements in a list

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

my_dict = {'name':‘Suraj, 'age': 26}


# update value
my_dict['age'] = 27 #Output: {'age': 27, 'name': ‘Sural'}
print(my_dict)
# add item
my_dict['address'] = ‘Delhi'
# Output: {'address': ‘Delhi', 'age': 27, 'name': ‘suraj'}print(my_dict)

72
Update: Merging Dictionaries

 What about concatenating dictionaries, like we did with lists?

There is something similar for dictionaries: the update method


update() merges the keys and values of one dictionary into another,
overwriting values of the same key:
>>> w={"house":"Haus","cat":"Katze","red":"rot"}

>>> w1 = {"red":"rouge","blau":"bleu"}
>>> w.update(w1)

>>> print w

{'house': 'Haus', 'blau': 'bleu', 'red': 'rouge', 'cat': 'Katze'}

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

False (“in” only checks the


>>> symbol_to_name["P"] keys,
Traceback (most recent call last): not the values.)
File "<stdin>", line 1, in <module>
KeyError: 'P'
>>> symbol_to_name.get("P", "unknown")
'unknown'
>>> symbol_to_name.get("C", "unknown")
'carbon'
[] lookup failures raise
an exception.
Use “.get()” if you want

to return a default value.

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']

>>> symbol_to_name.update( {"P": "phosphorous", "S": "sulfur"} )


>>> symbol_to_name.items()
[('C', 'carbon'), ('H', 'hydrogen'), ('O', 'oxygen'), ('N', 'nitrogen'), ('P', 'phosphorous'), ('S',
'sulfur'), ('Li', 'lithium'), ('He', 'helium')]

>>> del symbol_to_name['C']


>>> symbol_to_name {'H': 'hydrogen', 'O': 'oxygen', 'N': 'nitrogen', 'Li': 'lithium', 'He': '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

 To print “amit” print(a[“k1”]) output : amit


 To add element A[“branch”]=“CSE”
 To delete element del A[“branch”]
 To print keys print(A.keys())
 To print values print(A.values())

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

To print the complete list we use items method

print(A.items()) prints key:value combination

For i,j in items(): # I is for key and j is for value

print(“key is”+str(i)+ (“and its value is” + str(j)))

78
Set
Python offers a datatype called set whose elements must be unique.

It can be used to perform different set operations like union,


intersection, difference and symmetric difference.

A Set is an unordered collection data type that is iterable,


mutable, and has no duplicate elements.
Python’s set class represents the mathematical notion of
a set. The major advantage of using a set, as opposed to
a list, is that it has a highly optimized method for
checking whether a specific element is contained in the
set.
This is based on a data structure known as a hash table.

79
Set
# Program to perform different set operations like in mathematics

# define three sets


E = {0, 2, 4, 6, 8};
N = {1, 2, 3, 4, 5};

# 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)

# set symmetric difference


print("Symmetric difference of E and N is",E ^ N)

Union of E and N is {0, 1, 2, 3, 4, 5, 6, 8}


Intersection of E and N is {2, 4}
Difference of E and N is {0, 8, 6}
Symmetric difference of E and N is {0, 1, 3, 5, 6, 8}

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

 The empty tuple is written as two parentheses containing nothing −


 tup1 = ();

 To write a tuple containing a single value you have to include a


comma, even though there is only one value −
 tup1 = (50,);

 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]

Accessing Values in Tuples


 To access values in tuple, use the square brackets for slicing along
with the index or indices to obtain value available at that index.
 For example −
 tup1 = ('physics', 'chemistry', 1997, 2000)
 tup2 = (1, 2, 3, 4, 5, 6, 7 )
 print ("tup1[0]: ", tup1[0])
 print ("tup2[1:5]: ", tup2[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 −

 tup1 = (12, 34.56)


 tup2 = ('abc', 'xyz‘)
 # Following action is not valid for tuples
 # tup1[0] = 100
 # So let's create a new tuple as follows
 tup3 = tup1 + tup2
 print (tup3)
 When the above code is executed, it produces the following result

 (12, 34.56, 'abc', 'xyz')
87
print "list2[1:5]: ", list2[1:5]

Delete Tuple Elements


 Removing individual tuple elements is not possible.
 There is, of course, nothing wrong with putting together another
tuple with the undesired elements discarded.
 To explicitly remove an entire tuple, just use the del statement.
 For example

 tup = ('physics', 'chemistry', 1997, 2000)


 print (tup)
 del tup
 print ("After deleting tup : “)
 print (tup) Error message

88

print "list2[1:5]: ", list2[1:5]

Basic Tuples Operations

Python Expression Results Description

len((1, 2, 3)) 3 Length

(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation

('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition

3 in (1, 2, 3) True Membership

for x in (1, 2, 3): 123 Iteration


print (x)

89

print "list2[1:5]: ", list2[1:5]

Indexing, Slicing, and Matrixes


 Because tuples are sequences, indexing and slicing work the same
way for tuples as they do for strings.
 Assuming following input −
 L = ('spam', 'Spam', 'SPAM!')

Python Results Description


Expression
L[2] 'SPAM!' Offsets start at
zero
L[-2] 'Spam' Negative: count
from the right
L[1:] ['Spam', 'SPAM!'] Slicing fetches
sections

90

print "list2[1:5]: ", list2[1:5]

Built-in Tuple Functions


Sr. Function with Description
No.
1 cmp(tuple1, tuple2)Compares elements
of both tuples.
2 len(tuple)Gives the total length of the
tuple.
3 max(tuple)Returns item from the tuple
with max value.
4 min(tuple)Returns item from the tuple
with min value.
5 tuple(seq)Converts a list into tuple.

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 −

 print ('abc', -4.24e93, 18+6.6j, 'xyz‘)


 x, y = 1, 2

 print ("Value of x , y : ", x,y)


 ;When the above code is executed, it produces the following result

 abc -4.24e+93 (18+6.6j) xyz

 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']

>>> gender = [0, 0, 1]

>>> zip(names, gender)


[('ben', 0), ('chen', 0), ('yaqin', 1)]

93
Tuples assignment in For loop
data = [ ("C20H20O3", 308.371),
("C22H20O2", 316.393),
("C24H40N4O2", 416.6),
("C14H25N5O3", 311.38),
("C15H20O2", 232.3181)]

for (formula, mw) in data:


print "The molecular weight of %s is %s" % (formula, mw)

The molecular weight of C20H20O3 is 308.371


The molecular weight of C22H20O2 is 316.393
The molecular weight of C24H40N4O2 is 416.6
The molecular weight of C14H25N5O3 is 311.38
The molecular weight of C15H20O2 is 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

Very common in string interpolation:


>>> "%s lives in %s at latitude %.1f" % ("Andrew", "Sweden",
57.7056)
'Andrew lives in Sweden at latitude 57.7'

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

 Accessing an individual character of a string:


variableName [ index ]
 Example:
print name, "starts with", name[0]

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“

>>> line = " # This is a comment line \n"


>>> line.strip()
'# This is a comment line'
>>> line.rstrip()
' # This is a comment line'
>>> line.rstrip("\n")
' # This is a comment line '
>>>
99
String operators: in, not in
if "Br" in “Brother”:
print "contains brother“

email_address = “clin”
if "@" not in email_address:
email_address += "@brandeis.edu“

>>> line = " # This is a comment line \n"


>>> line.strip()
'# This is a comment line'
>>> line.rstrip()
' # This is a comment line'
>>> line.rstrip("\n")
' # This is a comment line '
>>>
100
More String methods
email.startswith(“c") endswith(“u”)
True/False

>>> "%[email protected]" % "clin"


'[email protected]'

>>> names = [“Ben", “Chen", “Yaqin"]


>>> ", ".join(names)
‘Ben, Chen, Yaqin‘

>>> “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

>>> "%[email protected]" % "clin"


'[email protected]'

>>> names = [“Ben", “Chen", “Yaqin"]


>>> ", ".join(names)
‘Ben, Chen, Yaqin‘

>>> “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

>>> "%[email protected]" % "clin"


'[email protected]'

>>> names = [“Ben", “Chen", “Yaqin"]


>>> ", ".join(names)
‘Ben, Chen, Yaqin‘

>>> “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

 A for loop can examine each character in a string in sequence.



Example:
for c in "booyah":
print c
Output:
b
o
o
y
a
h

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.

 chr(number)- converts a number into a string.


 Example: chr(99) is "c"

 Exercise: Write a program that performs a rotation cypher.


 e.g. "Attack" when rotated by 1 becomes "buubdl"

111
Functions, Procedures
def name(arg1, arg2, ...):
"""documentation""" # optional doc string
statements

return # from procedure


return expression # from function

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!

 To use methods of the instance, call using dot notation:


x.empty() # -> 1
x.push(1) # [1]
x.empty() # -> 0
x.push("hello") # [1, "hello"]
x.pop() # -> "hello" # [1]

 To inspect instance variables, use dot notation:


x.items # -> [1]

116
Sub classing
class FancyStack(Stack):
"stack with added ability to inspect inferior stack items"

def peek(self, n):


"peek(0) returns top; peek(-1) returns item below that; etc."
size = len(self.items)
assert 0 <= n < size # test precondition
return self.items[size-1-n]

117
Sub classing 2
class LimitedStack(FancyStack):
"fancy stack with limit on stack size"

def __init__(self, limit):


self.limit = limit
FancyStack.__init__(self) # base class constructor

def push(self, x):


assert len(self.items) < self.limit
FancyStack.push(self, x) # "super" method call

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

 On assignment via instance (self.x = ...):


 always makes an instance variable
 Class variables "default" for instance variables
 But...!
 mutable class variable: one copy shared by
all
 mutable instance variable: each instance its

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)

 Import with rename:


 import re as regex
 from re import match as m

 Before Python 2.0:



import re; regex = re; del re
Packages
 Collection of modules in directory
 Must have __init__.py file
 May contain subpackages
 Import syntax:
 from P.Q.M import foo; print foo()
 from P.Q import M; print M.foo()

 import P.Q.M; print P.Q.M.foo()

 import P.Q.M as M; print M.foo() # new


Basic Exception Handling

An “exception” is a (recognized type of) error, and “handling” is
what you do when that error occurs

General syntax:
try:
code-you-want-to-run
except exception1 [as variable1]:
exception1 block
...
except exceptionN [as variableN]:
exceptionN block

If an error occurs, if it's of exception type 1, then variable1
becomes an alias to the exception object, and then exception1
block executes. Otherwise, Python tries exception types 2 ... N
until the exception is caught, or else the program stops with an
unhandled exception (a traceback will be printed along with the
exception's text)

The optional [as variable] will not work with older Python
Exception example
 value-error.pl

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

 Learning Python: Lutz, Ascher (O'Reilly '98)


 Python Essential Reference: Beazley (New Riders '99)
 Programming Python, 2nd Ed.: Lutz (O'Reilly '01)
 Core Python Programming: Chun (Prentice-Hall '00)
 The Quick Python Book: Harms, McDonald (Manning '99)
 The Standard Python Library: Lundh (O'Reilly '01)
 Python and Tkinter Programming: Grayson (Manning '00)
 Python Programming on Win32:
Hammond, Robinson (O'Reilly '00)
 Learn to Program Using Python: Gauld (Addison-W. '00)
 And many more titles...
File processing
 Many programs handle data, which often comes from files.

 Reading the entire contents of a file:


variableName = open("filename").read()

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."

 Exercise: Write a program to process a file of DNA text, such as:


ATGCAATTGCTCGATTAG
 Count the percent of C+G present in the DNA.

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."

 Exercise: Write a program to process a file of DNA text, such as:


ATGCAATTGCTCGATTAG
 Count the percent of C+G present in the DNA.

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")

 The coordinate system is y-inverted:


(0, 0)

(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 = drawingpanel(500, 400)


g = window.get_graphics()

for i in range(1, 11):


x = 100 + 20 * i
y = 5 + 20 * i
g.create_oval(x, y, x + 50, y + 50, fill="red")

window.mainloop()

 Exercise: Draw the figure at right.

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

You might also like