Python Basics.pdf

FaizanAli561069 606 views 178 slides Oct 27, 2022
Slide 1
Slide 1 of 235
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117
Slide 118
118
Slide 119
119
Slide 120
120
Slide 121
121
Slide 122
122
Slide 123
123
Slide 124
124
Slide 125
125
Slide 126
126
Slide 127
127
Slide 128
128
Slide 129
129
Slide 130
130
Slide 131
131
Slide 132
132
Slide 133
133
Slide 134
134
Slide 135
135
Slide 136
136
Slide 137
137
Slide 138
138
Slide 139
139
Slide 140
140
Slide 141
141
Slide 142
142
Slide 143
143
Slide 144
144
Slide 145
145
Slide 146
146
Slide 147
147
Slide 148
148
Slide 149
149
Slide 150
150
Slide 151
151
Slide 152
152
Slide 153
153
Slide 154
154
Slide 155
155
Slide 156
156
Slide 157
157
Slide 158
158
Slide 159
159
Slide 160
160
Slide 161
161
Slide 162
162
Slide 163
163
Slide 164
164
Slide 165
165
Slide 166
166
Slide 167
167
Slide 168
168
Slide 169
169
Slide 170
170
Slide 171
171
Slide 172
172
Slide 173
173
Slide 174
174
Slide 175
175
Slide 176
176
Slide 177
177
Slide 178
178
Slide 179
179
Slide 180
180
Slide 181
181
Slide 182
182
Slide 183
183
Slide 184
184
Slide 185
185
Slide 186
186
Slide 187
187
Slide 188
188
Slide 189
189
Slide 190
190
Slide 191
191
Slide 192
192
Slide 193
193
Slide 194
194
Slide 195
195
Slide 196
196
Slide 197
197
Slide 198
198
Slide 199
199
Slide 200
200
Slide 201
201
Slide 202
202
Slide 203
203
Slide 204
204
Slide 205
205
Slide 206
206
Slide 207
207
Slide 208
208
Slide 209
209
Slide 210
210
Slide 211
211
Slide 212
212
Slide 213
213
Slide 214
214
Slide 215
215
Slide 216
216
Slide 217
217
Slide 218
218
Slide 219
219
Slide 220
220
Slide 221
221
Slide 222
222
Slide 223
223
Slide 224
224
Slide 225
225
Slide 226
226
Slide 227
227
Slide 228
228
Slide 229
229
Slide 230
230
Slide 231
231
Slide 232
232
Slide 233
233
Slide 234
234
Slide 235
235

About This Presentation

This PDF is Python beginners


Slide Content

INTRODUCTION
ASSISTANT PROFESSOR
GHULAM MUSTAFA SHORO
DEPARTMENT OF ELECTRONIC ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
UNIVERSITY OF SINDH

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H

SENG 424 Python Programming
»Course Details
▪Python Programming (Theory + Lab)
▪2 Credit Hours (Theory) per Week
▪1 Credit Hour (Lab) per Week
»Course Tutor: Ghulam Mustafa Shoro
BS -Software Engineering Part -II Second Semester
Day Theory Lab ( Comp Lab II)
Thursday2:00 PM –4:00 PM5:00 PM –7:00 PM

About This course
•Thiscourseaimstoteacheveryonethebasicsofprogramming
computersusingPython.Wecoverthebasicsofhowoneconstructsa
programfromaseriesofsimpleinstructionsinPython.
•Thecoursehasnopre-requisitesandavoidsallbutthesimplest
mathematics.Anyonewithmoderatecomputerexperienceshouldbe
abletomasterthematerialsinthiscourse.
•ThiscoursewillcoverChapters1-5ofthetextbook“Pythonfor
Everybody”.Onceastudentcompletesthiscourse,theywillbereadyto
takemoreadvancedprogrammingcourses.ThiscoursecoversPython3.

Textbooks

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
What is Python?
•Python is a popular programming language. It was created by Guido van
Rossum and released in 1991.
•It is used for:
▫Web Development (server-side),
▫Software Development,
▫Mathematics,
▫System Scripting.

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
What can Python do?
•Python can be used on a server to create web applications.
•Python can be used alongside software to create workflows.
•Python can connect to database systems. It can also read and modify
files.
•Python can be used to handle big data and perform complex
mathematics.
•Python can be used for rapid prototyping, or for production-ready
software development.

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Why Python?
•Python works on different platforms (Windows, Mac, Linux, Raspberry
Pi, etc.).
•Python has a simple syntax like the English language.
•Python has syntax that allows developers to write programs with fewer
lines than some other programming languages.
•Python runs on an interpreter system, meaning that code can be
executed as soon as it is written. This means that prototyping can be
very quick.
•Python can be treated in a procedural way, an object-oriented way or a
functional way.

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Good to Know
▪ThemostrecentmajorversionofPythonisPython3,whichweshallbe
usinginthistutorial.However,Python2,althoughnotbeingupdated
withanythingotherthansecurityupdates,isstillquitepopular.
▪InthistutorialPythonwillbewritteninatexteditor.Itispossibletowrite
PythoninanIntegratedDevelopmentEnvironment,suchasThonny,
Pycharm,NetbeansorEclipsewhichareparticularlyusefulwhen
managinglargercollectionsofPythonfiles.

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Python Syntax compared to other Programing Languages
•Python was designed for readability and has some similarities to the English
language with influence from mathematics.
•Python uses new lines to complete a command, as opposed to other
programming languages which often use semicolons or parentheses.
•Python relies on indentation, using whitespace, to define scope; such as the
scope of loops, functions and classes. Other programming languages often
use curly-brackets for this purpose.

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Chapter Two

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Constants
•Fixed valuessuch as numbers, letters, and strings are called
“constants” -because their value does not change
•Numericconstantsare as you expect
•Stringconstantsuse single-quotes (')
ordouble-quotes (")
>>>print123
123
>>> print98.6
98.6
>>> print 'Hello world'
Hello world

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Variables
▪A variableis a named place in the memory where a programmer can
store data and later retrieve the data using the variable“name”
▪Programmers get to choose the names of the variables
▪You can change the contents of a variablein a later statement
x=12.2
y=14
x= 100
12.2x
14y
100

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Python Variables
•Variables are containers for storing data values.
•Unlike other programming languages, Python has no command for declaring a variable.
•A variable is created the moment you first assign a value to it.
Example
x = 5
y = "John"
print(x)
print(y)
•Variables do not need to be declared with any typeandcan even change type after they have been set.
Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
•String variables can be declared either by using single or double quotes:
Example
x = "John"
# is the same as
x = 'John'

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Python Variable Name Rules
▪Can consist of letters, numbers, or underscores (but cannot start with a
number)
▪Case Sensitive
▪Good:spam eggs spam23 _speed
▪Bad:23spam #sign var.12
▪Different:spam SpamSPAM

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Variable Names
•A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).
Example
#Legal variable names:
myvar= "John"
my_var= "John"
_my_var= "John"
myVar= "John"
MYVAR = "John"
myvar2 = "John"
#Illegal variable names:
2myvar = "John"
my-var = "John"
my var = "John"

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Assign Value to Multiple Variables
•Python allows you to assign values to multiple variables in one line:
Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
•And you can assign the samevalue to multiple variables in one line:
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Output Variables
•The Python Print statement is often used to output variables
•To combine both text and a variable, Python uses the + character:
Example
x = "awesome"
print("Python is " + x)
•You can also use the + character to add a variable to another variable:
Example
x = "Python is "
y = "awesome"
z =x + y
print(z)
•For numbers, the + character works as a mathematical operator:
Example
x = 5
y = 10
print(x + y)
•If you try to combine a string and a number, Python will give you an error:
Example
x = 5
y = "John"
print(x + y)

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Global Variables
•Variables that are created outside of a function (as in all the examples above) are known as global variables.
•Global variables can be used by everyone, both inside of functions and outside.
Example
Create a variable outside of a function, and use it inside the function
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
•If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The
global variable with the same name will remain as it was, global and with the original value.
Example
Create a variable inside a function, with the same name as the global variable
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
The global Keyword
•Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function.
•To create a global variable inside a function, you can use the global keyword
Example
If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
•Also, use the global keyword if you want to change a global variable inside a function.
Example
To change the value of a global variable inside a function, refer to the variable by using the global keyword:
x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Python Indentation
•Indentation refers to the spaces at the beginning of a code line.
•Python uses indentation to indicate a block of code.
Example
•if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
•You must use the same number of spaces in the same block of code, otherwise Python will
give you an error:
Example
•Syntax Error:
•if 5 > 2:
•print("Five is greater than two!")
• print("Five is greater than two!")

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Reserved Words
You can NOT use reserved words as variable names / identifiers
and del for is raise assert elif
from lambda return break else
global not try class except if or while
continue import pass False
yield def finally in print True

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Statements
Assignment Statement
Assignment with expression
Print statement
x=2
x=x+2
printx
VariableOperator Constant Reserved Word
A statement is a unit of code that the Python interpreter can execute.

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Assignment Statements
•We assign a value to a variable using the assignmentstatement (=)
•Anassignment statementconsists of an expression on the right-
hand sideand a variableto store the result
x =3.9 * x* ( 1 -x)

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
A variable is a memory location
used to store a value (0.6).
Right side is an expression. Once
expression is evaluated, the result
is placed in (assigned to) x.
x =3.9 * x * ( 1 -x )
0.6x
0.6 0.6
0.4
0.936
0.936x

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
A variable is a memory location
used to store a value. The value
stored in a variable can be updated
by replacing the old value (0.6)
with a new value (0.93).
Right side is an expression. Once
expression is evaluated,the result
is placed in (assigned to) the
variable on the left side (i.e. x).
x =3.9 * x * ( 1 -x )
0.6 0.93x
0.93

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Operators and Operands
▪Because of the lack of mathematical
symbols on computer keyboards -we
use “computer-speak” to express the
classic math operations
▪Asterisk is multiplication
▪Exponentiation (raise to a power) looks
different from in math.
Mathematical Operators
+ Addition
− Subtraction
∗ Multiplication
/ Division
∗∗Power
% Remainder

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Numeric Expressions
Mathematical Operators
+ Addition
− Subtraction
∗ Multiplication
/ Division
∗∗Power
% Remainder
>>>x= 2
>>>x=x+ 2
>>> printx
4
>>>y= 440 *12
>>>print y
5280
>>>z=y/ 1000
>>>printz
5
>>>j = 23
>>>k=j%5
>>>print k
3
>>>print 4**3
64
523
4 R 3
20
3

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Order of Evaluation
•When we string operators together -Python must know which one to
do first
•This is called “operator precedence”
•Which operator “takes precedence” over the others
x= 1+2*3-4/ 5**6

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Operator Precedence Rules
•Highest precedence rule to lowest precedence rule
•Parenthesis are always respected
•Exponentiation (raise to a power)
•Multiplication, Division, and Remainder
•Addition and Subtraction
•Left to right
Parenthesis
Power
Multiplication
Addition
Left to Right

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Operator Precedence Rules
Parenthesis
Power
Multiplication
Addition
Left to Right
x = 1+2**3/4*5
1 +2 **3 /4 *5
1 +8 /4 *5
1 +2 *5
1 +10
11
Note 8/4 goes before 4*5
because of the left-right
rule.

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Operator Precedence
Parenthesis
Power
Multiplication
Addition
Left to Right
•Remember the rules --top to bottom
•When writing code -use parenthesis
•When writing code -keep mathematical expressions simple enough
that they are easy to understand
•Break long series of mathematical operations up to make them more
clear
Exam Question: x = 1 + 2 * 3 -4 / 5

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Integer Division
•Integer division truncates
•Floating point division produces
floating point numbers
>>>print10 / 2
5
>>>print9 / 2
4
>>>print99 / 100
0
>>>print10.0 / 2.0
5.0
>>>print 99.0 / 100.0
0.99This changes in Python 3.0

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Mixing Integer and Floating Numbers in Arithmetic Expressions
•When you perform an
operation where one
operand is an integer, and
the other operand is a
floating point the result is a
floating point
•The integer is converted to a
floating point before the
operation
>>>print99/100
0
>>> print99/ 100.0
0.99
>>> print99.0 /100
0.99
>>>print1+2*3/4.0 -5
-2.5
>>>

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Data Types in Python
•Integer(Examples: 0, 12, 5, -5)
•Float(Examples: 4.5, 3.99, 0.1 )
•String(Examples: “Hi”, “Hello”, “Hi there!”)
•Boolean(Examples: True, False)
•List (Example: [ “hi”, “there”, “you” ] )
•Tuple(Example: ( 4, 2, 7, 3) )

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Data Types
•In Python variables, literals, and
constants have a “data type”
•In Python variables are “dynamically”
typed. In some other languages you
must explicitly declare the type before
you use the variable
In C/C++:
int a;
float b;
a = 5
b = 0.43
In Python:
a = 5
a = “Hello”
a = [ 5, 2, 1]

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
More on “Types”
•In Python variables, literals, and
constants have a “type”
•Python knows the difference
between an integer number and a
string
•For example “+” means “addition”
if something is a number and
“concatenate” if something is a
string
>>> d = 1 + 4
>>> print d
5
>>> e = 'hello ' + 'there'
>>> print e
hello there
concatenate = put together

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
TypeMatters
•Python knows what “type”
everything is
•Some operations are prohibited
•You cannot “add 1” to a string
•We can ask Python what type
something is by using the type()
function.
>>> e = 'hello ' + 'there'
>>>e = e + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str'
and 'int' objects
>>>type(e)
<type 'str'>
>>> type('hello')
<type 'str'>
>>>type(1)
<type 'int'>
>>>

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Several Types of Numbers
•Numbers have two main types
•Integers are whole numbers: -14, -2, 0,
1, 100, 401233
•Floating Point Numbers have decimal
parts: -2.5 , 0.0, 98.6, 14.0
•There are other number types -they are
variations on float and integer
>>> x= 1
>>> type (x)
<type 'int'>
>>> temp= 98.6
>>>type(temp)
<type 'float'>
>>> type(1)
<type 'int'>
>>> type(1.0)
<type 'float'>
>>>

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Type Conversions
•When you put an integer and
floating point in an expression
the integer is implicitly
converted to a float
•You can control this with the
built-in functions int() and float()
>>>printfloat(99) / 100
0.99
>>> i= 42
>>> type(i)
<type 'int'>
>>> f = float(i)
>>>printf
42.0
>>>type(f)
<type 'float'>
>>>print1+2 *float(3) /4-5
-2.5
>>>

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
String Conversions
•You can also use int() and
float() to convert between
strings and integers
•You will get an errorif the
string does not contain
numeric characters
>>>sval= '123'
>>>type(sval)
<type 'str'>
>>>print sval+1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int'
>>>ival= int(sval)
>>>type(ival)
<type 'int'>
>>>print ival+ 1
124
>>> nsv= 'hello bob'
>>>niv= int(nsv)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int()

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
User Input
•We can instruct Python to
pause and read data from
the user using the
raw_input()function
•Theraw_input()function
returns a string
name=raw_input(‘Who are you?’)
print'Welcome ', name
Who are you? Chuck
Welcome Chuck

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Converting User Input
•If we want to read a
number from the user, we
must convert it from a
string to a number using a
type conversion function
•Later we will deal with
bad input data
inp=raw_input(‘Europe floor?’)
usf= int(inp)+1
print“US floor: ”, usf
Europe floor? 0
US floor : 1

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Comments in Python
•Anything after a #is ignored by Python
•Why comment?
•Describe what is going to happen in a sequence of code
•Document who wrote the code or other ancillary information
•Turn off a line of code -perhaps temporarily

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Python Comments
•Comments can be used to explain Python code.
•Comments can be used to make the code more readable.
•Comments can be used to prevent execution when testing code.
•Creating a Comment
•Comment starts with a #, and python will ignore them:
#This is a comment
print("Hello, World!")
Comments can be placed at the end of a line, and Python will ignore the rest of the line:
Example : print("Hello, World!") #This is a comment
Comments does not have to be text to explain the code, it can also be used to prevent Python
from executing code:
Example
#print("Hello, World!")
print("Cheers, Mate!")

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
# Get the name of the file and open it
name = raw_input("Enter file:")
handle = open(name, "r") # This is a file handle
text = handle.read()
words = text.split()

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
StringOperations
•Some operators apply to strings
•+ implies “concatenation”
•* implies “multiple
concatenation”
•Python knows when it is dealing
with a string or a number and
behaves appropriately
>>>print'abc'+'123‘
Abc123
>>>print'Hi'*5
HiHiHiHiHi

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Mnemonic Variable Names
•Since we programmers are given a choice in how we choose
our variable names, there is a bit of “best practice”
•We name variables to help us remember what we intend to
store in them (“mnemonic” = “memory aid”)
•This can confuse beginning students because well named
variables often “sound” so good that they must be keywords

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
x1q3z9ocd = 35.0
x1q3z9afd = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd
print x1q3p9afd
hours = 35.0
rate = 12.50
pay = hours * rate
print pay
a = 35.0
b = 12.50
c = a * b
print c
What is this
code doing?

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Exercise
Write a program to prompt the user for hours and rate per hour to
compute gross pay.
Enter Hours: 35
Enter Rate: 2.75
Pay: 96.25

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Summary
•Types (int, float, Boolean, string, list, tuple, …)
•Reserved words
•Variables (mnemonic)
•Operators and Operator precedence
•Division (integer and floating point)
•Conversion between types
•User input
•Comments (#)

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Chapter Three

Boolean Expressions
•A Boolean expression is an expression that is either true or false.
•The following examples use the operator ==, which compares two
operands and produces True if they are equal and False otherwise:
•>>> 5 == 5
•True
•>>> 5 == 6
•False
•{}

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Comparison Operators x = 5
if x == 5 :
print 'Equals 5‘
if x > 4 :
print 'Greater than 4’
if x >= 5 :
print 'Greater than or Equal 5‘
if x < 6 :
print 'Less than 6'
x != y # x is not equal to y
x > y # x is greater than y
x < y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y
x is y # x is the same as y
x is not y # x is not the same as y

Logical Operator
•There are three logical operators: and, or, and not. The semantics
(meaning) of these operators is like their meaning in English. For
example,
•x > 0 andx < 10
•is true only if x is greater than 0 and less than 10.
•n%2 == 0 orn%3 == 0 is true if either of the conditions is true, that is, if
the number is divisible by 2 or 3.
•Finally, the not operator negates a Boolean expression, so not(x > y) is
true if x > y is false; that is, if x is less than or equal to y.

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Conditional Steps
Program:
x = 5
ifx < 10:
print 'Smaller‘
if x > 20:
print'Bigger'
print'Finish'
x = 5
X < 10 ?
print 'Smaller'
X > 20 ?
print 'Bigger'
print 'Finish'
Yes
Yes

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
The IF Statement
x = 5
if x == 5 :
print 'Is 5‘
print 'Is Still 5'
print 'Third 5’
X == 5 ?
Yes
print 'Still 5'
print 'Third 5'
No print 'Is 5'

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Indentation Rules
•Increase indent after an if statement or for statement (after : )
•Maintain indent to indicate the scope of the block (which lines are
affected by the if/for)
•Reduce indent to back tothe level of the if statement or for statement
to indicate the end of the block
•Blank lines are ignored -they do not affect indentation
•Comments on a line by themselves are ignored w.r.t.indentation

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
increase / maintainafterifor for
decrease to indicate end of block
blank lines and comment lines ignored
x = 5
if x > 2 :
print 'Bigger than 2'
print 'Still bigger’
print 'Done with 2’
for iin range(5) :
print i
if i> 2 :
print 'Bigger than 2'
print 'Done with i', i
x = 5
if x > 2 :
# comments
print 'Bigger than 2'
# don’t matter
print 'Still bigger’
# but can confuse you
print 'Done with 2'
# if you don’t line
# them up

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Two Way Decisions
•Sometimes we want to
do one thing if a logical
expression is true and
something else if the
expression is false
•It is like a fork in the
road -we must choose
one or the other path
but not both
x > 2
print 'Bigger'
yesno
X = 4
print 'Not bigger'
print 'All Done'

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Two-way branch using else :
x > 2
print 'Bigger'
yesno
X = 4
print ‘Smaller'
print 'All Done'
x = 4
if x > 2 :
print 'Bigger'
else :
print 'Smaller'
print 'All done'

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Nested Decisions
x ==y
x < y
print 'All Done'
yes
yes no
no
Print ’Greater’
print ‘Equal'
Print ’Less’

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Nested Decisions
x = 42
if x > 1 :
print 'More than one'
if x < 100 :
print 'Less than 100'
print 'All done'
x > 1
print 'More than one'
x < 100
print 'All Done'
yes
yes
no
no
Print ’Less than 100’

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Chained Conditionals
ifx < 2 :
print 'Small'
elifx < 10 :
print 'Medium'
else:
print'LARGE'
print'All done'
x < 2 print 'Small'
yes
no
print 'All Done'
x<10 print 'Medium'
yes
print 'LARGE'
no

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Chained Conditional
# No Else
x = 5
if x < 2 :
print 'Small'
elif x < 10 :
print 'Medium'
print 'All done'
if x < 2 :
print 'Small'
elif x < 10 :
print 'Medium'
elif x < 20 :
print 'Big'
elif x< 40 :
print 'Large'
elif x < 100:
print 'Huge'
else :
print 'Ginormous'

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Multi-way Puzzles
Which will never print?
if x < 2 :
print 'Below 2'
elif x >= 2 :
print 'Two or more'
else :
print 'Something else'
if x < 2 :
print 'Below 2'
elif x < 20 :
print 'Below 20'
elif x < 10 :
print 'Below 10'
else :
print 'Something else'

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
The try/ exceptStructure
•You surround a dangerous section of code with tryandexcept.
•If the code in the tryworks -the exceptis skipped
•If the code in the try fails -it jumps to the exceptsection

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
astr = 'Hello Bob‘
istr = int(astr)
print 'First‘
istrastr= '123‘
istr = int(astr)
print 'Second', istr
$ python notry.py Traceback (most
recent call last): File "notry.py", line 2,
in <module> istr =
int(astr)ValueError: invalid literal for
int() with base 10: 'Hello Bob'

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
astr = 'Hello Bob'
try:
istr = int(astr)
except:
istr = -1
print 'First', istr
astr = '123'
try:
istr = int(astr)
except:
istr = -1
print 'Second', istr
When the first conversion fails -it
just drops into the except: clause and
the program continues.
When the second conversion
succeeds -it just skips the except:
clause and the program continues.
Output:
First -1
Second 123

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
try / except
astr = 'Bob'
try:
print 'Hello'
istr = int(astr)
print 'There'
except:
istr = -1
print 'Done', istr
astr = 'Bob'
print 'Hello'
print 'There'
istr = int(astr)
print 'Done', istr
istr = -1
Safety net

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Sample try / except
rawstr= raw_input('Enter a number:')
try:
ival= int(rawstr)
except:
ival= -1
if ival> 0 :
print 'Nice work’
else:
print 'Not a number’
Enter a number:42
Nice work
Enter a number: fourtytwo
Not a number

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Exercise
Write a pay computation program that gives the
employee 1.5 times the hourly rate for hours worked
above 40 hours (and regular 1.0 rate for less than 40
hours)
Enter Hours: 45
Enter Rate: 10
Pay: 475.0
475 = 40 * 10 + 5 * 15

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Exercise
Rewrite your pay program using try and except so that
your program handles non-numeric input gracefully.
Enter Hours: 20
Enter Rate: nine
Error, please enter numeric input
Enter Hours: forty
Error, please enter numeric input

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Summary
•Comparison operators == <= >= > < !=
•Logical operators: and or not
•Indentation
•One Way Decisions
•Two-way Decisions if : and else :
•Nested Decisions and Multiway decisions using elif
•Try / Except to compensate for errors

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Chapter Four

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Stored (and reused) Steps
Output:
Hello
Fun
Zip
Hello
Fun
Program:
defhello():
print 'Hello'
print'Fun'
hello()
print'Zip‘
hello()
We call these reusable pieces of code “functions”.
def
print 'Hello'
print 'Fun'
hello()
print “Zip”
hello():
hello()

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Python Functions
•There are two kinds of functions in Python
•Built-in functions that are provided as part of Python -raw_input(),
type(), float(), max(), min(), int(), str(), …
•Functions (user defined) that we define ourselves and then use
•We treat the built-in function names like reserved words (i.e. we avoid
them as variable names)

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Function Definition
•In Python a function is some reusable code that takes arguments(s) as
input does some computation and then returns a result or results
•We define a function using the defreserved word
•We call/invoke the function by using the function name, parenthesis
and arguments in an expression

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Max Function
>>>big=max('Hello world')
>>>printbig
>>> ‘w’
Afunctionis some
stored codethat we
use. A function takes
some inputand
produces anoutput.
max()
function
“Hello world”
(astring)
‘w’
(a string)

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Type Conversions
•When you put an integer and
floating point in an expression
the integer is implicitly
converted to a float
•You can control this with the
built-in functions int() and float()
>>>printfloat(99) /100
0.99
>>> i= 42
>>>type(i)
<type 'int'>
>>> f = float(i)
>>>printf
42.0
>>> type(f)
<type 'float'>
>>> print1+2*float(3) /4-5
-2.5
>>>

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
String Conversions
▪You can also use int() and
float() to convert between
strings and integers
▪You will get anerrorif the
string does not contain
numeric characters
>>>sval= '123'
>>>type(sval)
<type 'str'>
>>> print sval+1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int'
>>>ival=int(sval)
>>>type(ival)
<type 'int'>
>>> printival+1
124
>>> nsv= 'hello bob'
>>>niv=int(nsv)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int()

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Building our Own Functions
•We create a new functionusing the def keyword followed by the
functionname, optional parameters in parenthesis, and then we add a
colon.
•We indent the body of the function
•Thisdefinesthe function but does notexecute the body of the
function
defprint_lyrics():
print "I'm a lumberjack, and I'm okay."
print'I sleep all night and I work all day.'

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
x= 5
print'Hello'
defprint_lyrics():
print "I'm a lumberjack, and I'm okay."
print 'I sleep all night and I work all day.'
print 'Yo'
x=x+2
printx
Hello
Yo
7
print"I'm a lumberjack, and I'm okay."
print'I sleep all night and I work all day.'
print_lyrics():

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Definitionsand Uses
•Once we have defineda function, we can call(or invoke) it as many
times as we like
•This is the storeandreuse pattern

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
x= 5
print'Hello'
def print_lyrics():
print "I'm a lumberjack, and I'm okay."
print 'I sleep all night and I work all day.'
print 'Yo'
print_lyrics()
x=x+2
printx
Hello
Yo
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
7

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Arguments
•Anargumentis a value we pass into the functionas its inputwhen we
call the function
•We use argumentsso we can direct the functionto do different kinds
of work when we call it at differenttimes
•We put the argumentsin parenthesis after the nameof the function
big= max('Hello world')
Argument

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Parameters
•Aparameteris a variable
which we use inthe
functiondefinitionthat is a
“handle” that allows the
code in the functionto
access theargumentsfor a
particularfunction
invocation.
def greet(lang):
if lang== 'es':
print'Hola'
elif lang== 'fr':
print'Bonjour'
else:
print 'Hello‘
greet('en')
Hello
greet('es')
Hola
greet('fr')
Bonjour

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
ReturnValues
•Often a function will take its arguments, do some computation and
returna value to be used as the value of the function call in the calling
expression. Thereturnkeyword is used for this.
defgreet():
return"Hello "
printgreet(),"Glenn"
printgreet(),"Sally"
Hello Glenn
Hello Sally

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Return Value
•A “fruitful” functionis one
that produces a result(or a
returnvalue)
•Thereturn statement ends
thefunctionexecution and
“sends back” the resultof
thefunction
defgreet(lang):
if lang== 'es':
return 'Hola '
elif lang== 'fr':
return 'Bonjour '
else:
return 'Hello '
printgreet('en'),'Glenn'
Hello Glenn
printgreet('es'),'Sally'
Hola Sally
print greet('fr'),'Michael'
Bonjour Michael

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Arguments,Parameters, and Results
>>> big = max('Hello world‘)
>>>print big
>>>w
def max(inp):
blah
blah
forx iny:
blah
blah
return ‘w’
‘w’
Argument
Parameter
Result

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
MultipleParameters/Arguments
•We can define more than one
parameterin the function
definition
•We simply add more
argumentswhen we call the
function
•We match the number and
order of arguments and
parameters
defaddtwo(a, b):
added = a + b
return added
x = addtwo(3, 5)
print x
8

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Void Functions
•When a function does not return a value, we call it a "void" function
•Functions that return values are "fruitful" functions
•Void functions are "not fruitful"

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Functions –Code Reuse
•Organize your code into “paragraphs” -capture a complete thought
and “name it”
•Don’t repeat yourself -make it work once and then reuse it
•If something gets too long or complex, break up logical chunks and put
those chunks in functions
•Make a library of common stuff that you do over and over -perhaps
share this with your friends...

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
The range() function
•range()is a built-in function
that allows you to create a
sequence of numbers in a
range
•Very useful in “for” loops
which are discussed later in
the Iteration chapter
•Takes as an input 1, 2, or 3
arguments. See examples.
x = range(5)
print x
[0, 1, 2, 3, 4]
x = range(3, 7)
print x
[3, 4, 5, 6]
x = range(10, 1, -2)
print x
[10, 8, 6, 4, 2]

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Modules and the import statement
•A program can load a module
file by using the import
statement
•Use the name of the module
•Functions and variables
names in the module must be
qualified with the module
name. e.g. math.pi
importmath
radius = 2.0
area = math.pi* (radius ** 2)
12.5663706144
math.log(5)
1.6094379124341003
import sys
sys.exit()

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Summary
•Functions
•Built-In Functions:
•int(), float(), str(), type(), min(), max(), dir(), range(), raw_input(),…
•Defining functions: the def keyword
•Arguments, Parameters, Results, and Return values
•Fruitful and Void functions
•The range() function

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Chapter Five

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Repeated Steps
Program:
n =5
while n>0 :
print n
n = n –1
print'Blastoff!'
print n
Loops (repeated steps) have iteration variables that
change each time through a loop. Often these
iteration variables go through a sequence of numbers.
Output:
5
4
3
2
1
Blastoff!
0
n > 0 ?
n = n -1
No
print 'Blastoff'
Yes
n = 5
printn

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
An Infinite Loop
n= 5
while n>0:
print 'Lather'
print 'Rinse'
print 'Dry off!'
What is wrong with this loop?
n > 0 ?
Print 'Rinse'
No
print 'Dry off!'
Yes
n = 5
print'Lather'

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Another Loop
n= 0
while n>0:
print 'Lather'
print 'Rinse'
print 'Dry off!'
What does this loop do?
n > 0 ?
Print 'Rinse'
No
print 'Dry off!'
Yes
n = 0
print'Lather'

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Using continue in a loop
•The continue statement ends the current iteration and jumps to the
top of the loop and starts the next iteration
whileTrue:
line =raw_input('> ')
if line[0] =='#' :
continue
if line=='done' :
break
print line
print'Done!'
>hello there
hello there
> # don't print this
> print this!
print this!
>done
Done!

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
True?
….
No
print ‘Done'
Yes
n = 0
….
Break
whileTrue:
line=raw_input('> ')
if line=='done' :
break
print line
print'Done!'

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
True?
….
No
print ‘Done'
Yes
n = 0
….
Continue
while True:
line= raw_input('> ')
if line[0]=='#' :
continue
if line=='done' :
break
printline
print'Done!'

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Indefinite Loops
•While loops are called "indefinite loops"because they keep going
until a logical condition becomes False
•The loops we have seen so far are pretty easy to examine to see if
they will terminate or if they will be "infinite loops"
•Sometimes it is a little harder to be sure if a loop will terminate

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Definite Loops
•Quite often we have a listof items of the lines in a file-effectively
a finite set of things
•We can write a loop to run the loop once for each of the items in a
set using the Python forconstruct
•These loops are called "definite loops" because they execute an
exact number of times
•We say that "definite loops iterate through the members of a set"

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
A Simple Definite Loop
foriin[5, 4, 3, 2, 1] :
printi
print'Blastoff!'
5
4
3
2
1
Blastoff!

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
A Simple Definite Loop
friends=['Joseph', 'Glenn', 'Sally']
forfriendinfriends :
print'Happy New Year: ', friend
print 'Done!'
Happy New Year: Joseph
Happy New Year: Glenn
Happy New Year: Sally
Done!

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
A Simple Definite Loop
foriin[5, 4, 3, 2, 1]:
printi
print 'Blastoff!'
5
4
3
2
1
Blastoff!
Definite loops (for loops) have explicit iteration
variablesthat change each time through a loop. These
iteration variables move through the sequence or set.
Done?
No
print ‘Blast Off!'
Yes
print i
Move iahead

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
The range() function (revisited)
•range() is a built-in function
that allows you to create a
sequence of numbers in a
range
•Very useful in “for” loops
which are discussed later in
the Iteration chapter
•Takes as an input 1, 2, or 3
arguments. See examples.
x = range(5)
print x
[0, 1, 2, 3, 4]
x = range(3, 7)
print x
[3, 4, 5, 6]
x = range(10, 1, -2)
print x
[10, 8, 6, 4, 2]

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
A Simple Definite Loop iterating over a range
foriinrange(7, 0, -1) :
print i
print 'Blastoff!'
7
6
5
4
3
2
1
Blastoff!

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Looking at in
•The iteration variable
“iterates” though the
sequence
•Theblock (body)of code
is executed once for each
value inthesequence
•Theiteration variable
moves through all of the
values in thesequence
foriin[5, 4, 3, 2, 1] :
print i
Iteration variable
Five-element sequence

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Anatomy of a Loop
•The trick is “knowing” something
about the whole loop when you
are stuck writing code that only
sees one entry at a time
Set some variables to initial
values
Look for something or do
something to each entry
separately, updating a
variable.
for thing in data:
Look at the variables.

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Looping through a Set
print 'Before'
forthing in [9, 41, 12, 3, 74, 15] :
print thing
print'After'
Before
9
41
12
3
74
15
After

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Counting in a Loop
zork= 0
print 'Before', zork
forthing in[9, 41, 12, 3, 74, 15] :
zork= zork+ 1
printzork,thing
print'After', zork
Before 0
1 9
241
312
4 3
5 74
6 15
After 6
Tocounthow many times, we execute a loop we introduce a counter
variable that starts at 0 and we add one to it each time through the loop.

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Summing in a Loop
zork= 0
print 'Before', zork
forthingin[9, 41, 12, 3, 74, 15] :
zork= zork+ thing
print zork, thing
print'After', zork
Before 0
99
5041
6212
653
13974
15415
After 154
Toadd up avaluewe encounter in a loop, we introduce a sum variable that
starts at 0and we add the value to the sum each time through the loop.

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Finding the Average in a Loop
count = 0
sum = 0
print 'Before', count, sum
for value in [9, 41, 12, 3, 74, 15] :
count = count + 1
sum = sum + value
print count,sum,value
print 'After', count, sum,sum / count
Before 00
199
25041
36212
4653
513974
615415
After 615425
An average just combines the countingandsumpatterns
anddivides when the loop is done.

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Filtering in a Loop
print 'Before'
for value in [9, 41, 12, 3, 74, 15] :
if value> 20:
print 'Large number',value
print'After'
Before
Large number 41
Large number 74
After
We use an if statement inthe loopto catch / filter the
values we are looking for.

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Search Using a Boolean Variable
found = False
print 'Before', found
for valuein [9, 41, 12, 3, 74, 15] :
if value == 3 :
found = True
print found, value
print 'After', found
Before False
False9
False41
False12
True3
True74
True15
After True
If we just want to search and know if a value was found-we use a variablethat starts
at Falseand is set to Trueas soon as wefindwhat we are looking for.

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Finding the smallestvalue
smallest =None
print 'Before'
for value in[9, 41, 12, 3, 74, 15] :
If smallest isNone:
smallest = value
elif value < smallest:
smallest= value
printsmallest, value
print 'After', smallest
Before
99
941
912
33
374
315
After 3
We still have a variable that is the smallestso far. The first time through the
loop smallestisNone so we take the first valueto be the smallest.

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
The "is" and "is not" Operators
smallest=None
print 'Before'
forvaluein [3, 41, 12, 9, 74, 15] :
if smallestisNone:
smallest= value
elif value< smallest:
smallest= value
printsmallest, value
print 'After', smallest
•Python has an "is" operator
that can be used in logical
expressions
•Implies 'is the same as'
•Similar to, but stronger than
==
•'is not' also is a logical
operator

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Summary
•While loops (indefinite)
•Infinite loops
•Using break
•Using continue
•For loops (definite)
•Iteration variables
•Counting in loops
•Summing in loops
•Averaging in loops
•Searching in loops
•Detecting in loops
•Largest or smallest

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Chapter Six

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
String Data Type
•A string is a sequence of characters
•A string literal uses quotes ‘Hello’
or “Hello”
•For strings, + means “concatenate”
•When a string contains numbers, it
is still a string
•We can convert numbers in a string
into a number using int()
>>>str1 = "Hello“
>>>str2 = 'there‘
>>>bob = str1 + str2
>>>printbob
Hellothere
>>>str3 = '123‘
>>>str3 = str3 + 1
Traceback (most recent call last): File
"<stdin>", line 1, in
<module>TypeError: cannot
concatenate 'str' and 'int' objects
>>>x = int(str3) + 1
>>>printx
124

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Handling User Input
•We prefer to read data in
using stringsand then
parse and convert the data
as we need
•This gives us more control
over error situations
and/or bad user input
•Raw input numbers must
be convertedfrom strings
>>> name= raw_input('Enter:')
Enter:Chuck
>>>print name
Chuck
>>>apple= raw_input('Enter:')
Enter:100
>>>x =apple–10
Traceback (most recent call last): File
"<stdin>", line 1, in <module>TypeError:
unsupported operand type(s) for -: 'str'
and 'int‘
>>> x=int(apple) –10
>>>printx
90

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Looking Inside Strings
•We can get at any single character in
a string using an index specified in
square brackets
•The index value must be an integer
and starts at zero
•The index value can be an
expression that is computed
>>> fruit= 'banana‘
>>> letter = fruit[1]
>>> printletter
a
>>> n= 3
>>> w= fruit[n-1]
>>> printw
n
banana
012345

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
A Character Too Far
•You will get a python error if you
attempt to index beyond the end
of a string.
•So be careful when constructing
index values and slices
>>> zot= 'abc‘
>>> printzot[5]
Traceback (most recent call last):
File "<stdin>", line 1, in
<module>IndexError: string index
out of range
>>>

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
String Have Length
•There is a built-in function lenthat
gives us the length of a string
0
b
1
a
2
n
3
a
4
n
5
a
>>> fruit= 'banana‘
>>>print len(fruit)
6

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Len Function
>>> fruit= 'banana‘
>>>x= len(fruit)
>>>printx
6
A functionis some stored
codethat we use. A
function takes some input
and produces an output.
len()
function
'banana'
(a string)
6
(a number)

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Looping Through Strings
•Using a while statement and
an iteration variable, and the
lenfunction, we can construct
a loop to look at each of the
letters in a string individually
fruit = 'banana'
index=0
while index< len(fruit):
letter= fruit[index]
print index, letter
index = index+1
0 b
1 a
2 n
3 a
4 n
5 a

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Looping Through Strings using a “for” statement
•A definite loop using a for
statement is much more
elegant
•The iteration variable is
completely taken care of by
the forloop
fruit = 'banana'
forletterin fruit:
print letter
b
a
n
a
n
a

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Looping and Counting
•This is a simple loop that loops
through each letter in a string
and counts the number of
times the loop encounters the
'a' character.
word= 'banana‘
count=0
forletterin word :
if letter== 'a' :
count = count+1
printcount

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Looking Deeper into in
•Theiteration variable
“iterates” though the
sequence (ordered set)
•Theblock (body)of code is
executed once for each
valueinthe sequence
•Theiteration variable
moves through all of the
valuesin thesequence
forletterin 'banana’:
print letter
Iteration variable
Six-character string

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Done?
No
print ‘Blast Off!'
Yes
print Letter
Advance Letter
forletterin'banana':
print letter
banana
letter
Theiteration variable “iterates” though the string and the block
(body)of code is executed once for each value in the sequence

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
0
M
1
o
2
n
3
t
4
y
56
P
7
y
8
t
9
h
10
o
11
n
•We can also look at any
continuous section of a string
using a colon operator
•The second number is one
beyond the end of the slice -
“up to but not including”
•If the second number is
beyond the end of the string,
it stops at the end
Slicing Strings
>>>s='Monty Python‘
>>>prints[0:4]
Mont
>>>print s[6:7]
P
>>>print s[6:20]
Python

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Slicing Strings
0
M
1
o
2
n
3
t
4
y
56
P
7
y
8
t
9
h
10
o
11
n
•If we leave off the first
number or the last number of
the slice, it is assumed to be
the beginning or end of the
string respectively
>>>s='Monty Python‘
>>>prints[:2]
Mo
>>> prints[8:]
thon
>>>print s[:]
Monty Python

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
String Concatenation
•When the +operator is
applied to strings, it
means "concatenation"
>>> a= 'Hello‘
>>>b =a+'There‘
>>>print b
HelloThere
>>>c= a+' '+'There‘
>>>print c
Hello There

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
The String Formatting Operator: %
•Used for math when the
operand on the left is a
number the %is the
modulusoperator
•However, when the operand
to the left of the %operator
is a string then %is the
string format operator.
>>> 32%5
2
>>>b= “Gold”
>>> print “%s is a metal” %b
Gold is a metal

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
The String Format Operator: Dissected
s= “%s is a metal” %b
String formatting codeString formatting operator
format string

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
The string format operator with more than one value
being instead into the format string
b= “platinum”
a= 5
s = “%s is one of %d shiny metals” % (b, a)
prints
platinum is one of 5 shiny metals

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
String Formatting Codes
%s String
%c Character
%d Decimal (int)
%iInteger
%f Float
* Note: there are others, these are the most common ones.

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
String Formatting Codes Advanced Usage
%-6.2f
field width = 6
string format code symbol
left justify
number of decimal places = 2
type of formatting = float

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Using inas an Operator
•The inkeyword can also be
used to check to see if one
string is "in" another string
•The in expression is a logical
expression and returns True
or Falseand can be used in
anifstatement
>>> fruit= 'banana‘
>>> 'n'infruit
True
>>> 'm'infruit
False
>>> 'nan'in fruit
True
>>>if 'a'infruit :
print 'Found it!‘
Found it!

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
String Comparison
word=‘Blueberry'
if word<'banana':
print 'Your word,'+word +', comes before banana.‘
elifword >'banana':
print 'Your word,'+word+', comes after banana.‘
else:
print 'All right, bananas.'
ifword =='banana':
print ('All right, bananas.’)

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
String Library
•Python has a number of string
functionswhich are in thestring
library
•These functionsare already built into
every string -we invoke them by
appending the function to the string
variable
•Thesefunctionsdo not modify the
original string, instead they return a
new string that has been altered
>>>greet= 'Hello Bob'
>>>zap= greet.lower()
>>>print zap
hello bob
>>>printgreet
Hello Bob
>>> print 'Hi There'.lower()
hi there
>>>

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
The Directory Function –dir()
>>>stuff='Hello world‘
>>> type(stuff)
<type 'str‘>
>>>> dir(stuff)
['capitalize', 'center', 'count', 'decode', 'encode', 'endswith',
'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit',
'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip',
'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit',
'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title',
'translate', 'upper', 'zfill']

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
String Library
str.capitalize()
str.center(width[, fillchar])
str.endswith(suffix[, start[, end]])
str.find(sub[, start[, end]])
str.lstrip([chars])
str.join(x [, sep])
str.replace(old, new[, count])
str.lower()
str.rstrip([chars])
str.strip([chars])
str.upper()

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Searching String
•We use the find()function to
search for a substring within
another string
•find()finds the first
occuranceof the substring
•If the substring is not found,
find()returns -1
•Remember that string
position starts at zero
>>> fruit= 'banana'
>>> pos=fruit.find('na')
>>>printpos
2
>>> aa=fruit.find('z')
>>>print aa
-1
0
b
1
a
2
n
3
a
4
n
5
a

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Making Everything UPPER CASE
•You can make a copy of a string in
lower case or upper case
•Often when we are searching for a
string using find(), we first convert the
string to lower case so we can search a
string regardless of case
>>>greet= 'Hello Bob'
>>> nnn= greet.upper()
>>> printnnn
HELLO BOB
>>> www= greet.lower()
>>>print www
hello bob
>>>

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Search and Replace
•The replace() function
is like a “search and
replace” operation in
a word processor
•It replaces all
occurrencesof the
search stringwith the
replacement string
>>> greet = 'Hello Bob'
>>>nstr= greet.replace('Bob','Jane')
>>>printnstr
HelloJane
>>> greet = 'HelloBob'
>>> nstr= greet.replace('o','X')
>>>print nstr
HellXBXb
>>>

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Stripping Whitespace
•Sometimes we want to take a
string and remove whitespace
at the beginning and/or end
•lstrip()and rstrip()to the left
and right only
•strip() Removes both
beginning and ending
whitespace
>>> greet= ' Hello Bob '
>>> greet.lstrip()
'Hello Bob '
>>> greet.rstrip()
' Hello Bob'
>>> greet.strip()
'Hello Bob'
>>>

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Prefixes
>>>line= 'Please have a nice day'
>>>line.startswith('Please')
True
>>> line.startswith('p')
False

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Summary
•String type
•Indexing strings []
•Slicing strings [2:4]
•Looping through strings with forand while
•Concatenating strings with +
•inas an operator
•String comparison
•String library (Searching and Replacing text, Stripping white space )

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Chapter Seven

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Software
Input
and Output
Devices
Central
Processing
Unit
Main
Memory
Secondary
Memory
Files

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Opening a File
•Before we can read the contents of the file, we must tell Python
which file we are going to work with and what we will be doing
with the file
•This is done with the open() function
•open() returns a “file handle” -a variable used to perform
operations on the file
•Kind of like “File -> Open” in a Word Processor

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Using Open()
•handle= open(filename, mode)
•returns a handle use to manipulate the file
•filename is a string
•mode is optional and should be 'r' if we are planning reading the
file and 'w' if we are going to write to the file.
http://docs.python.org/lib/built-in-funcs.html
fhand= open('mbox.txt', 'r')

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
What is File Handle?
>>> fhand= open('mbox.txt')
>>>print fhand
<open file 'mbox.txt', mode 'r' at 0x1005088b0>

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
When Files are Missing
>>> fhand= open('stuff.txt')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno2] No such file or directory: 'stuff.txt'

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
The NewlineCharacter
•We use a special character to
indicate when a line ends
called the "newline"
•We represent it as \nin strings
•Newlineis still one character -
not two
>>>stuff= 'Hello\nWorld!'
>>> print stuff
Hello
World!
>>> stuff= 'X\nY'
>>>printstuff
X
Y
>>> len(stuff)
3

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
File Processing
•A text file can be thought of as a sequence of lines
From [email protected] Sat Jan 5 09:14:16 2008
Return-Path: <[email protected]>
Date: Sat, 5 Jan 2008 09:12:18 -0500To: [email protected]:
[email protected]: [sakai] svncommit: r39772 -
content/branches/Details:
http://source.sakaiproject.org/viewsvn/?view=rev&rev=39772

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
File Processing
•A text file has newlinesat the end of each line
From [email protected] Sat Jan 5 09:14:16 2008\n
Return-Path: <[email protected]>\n
Date: Sat, 5 Jan 2008 09:12:18 -0500\nTo:
[email protected]\nFrom:
[email protected]\nSubject: [sakai] svncommit: r39772 -
content/branches/\nDetails:
http://source.sakaiproject.org/viewsvn/?view=rev&rev=39772\n

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
File Handleas a Sequence
•A file handleopen for read can be treated
as a sequenceof strings where each line in
the file is a string in the sequence
•We can use the forstatement to iterate
through a sequence
•Remember -a sequenceis an ordered set
xfile= open('mbox.txt')
forcheeseinxfile:
print cheese

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Counting Lines in a File
•Open a fileread-only
•Use afor loop to read each line
•Countthe lines and print out
the number of lines
fhand= open('mbox.txt')
count= 0
forline in fhand:
count= count+ 1
print'Line Count:', count
Line Count: 132045

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Reading the *Whole*File
•We can readthe whole
file (newlines and all) into
a single string.
>>>fhand = open('mbox-short.txt')
>>>inp= fhand.read()
>>> printlen(inp)
94626
>>> printinp[:20]
From stephen.marquar

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Searching Through a File
•We can put an ifstatement
in our for loop to only print
lines that meet some
criteria
fhand= open('mbox-short.txt')
forlineinfhand:
if line.startswith('From:') :
print(line)

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
OOPS!
What are all these blank
lines doing here?
From: [email protected]
From: [email protected]
From: [email protected]
From: [email protected]...

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
OOPS!
What are all these blank
lines doing here?
The printstatement adds a
newlineto each line.
Each linefrom the file also
has a newlineat the end.
From: [email protected]\n\n
From: [email protected]\n\n
From: [email protected]\n\n
From: [email protected]\n

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Searching Through a File (fixed)
•We can strip the whitespace from
the right-hand side of the string
using rstrip() from the string
library
•The newline is considered "white
space" and is stripped
fhand= open('mbox-short.txt')
forlineinfhand:
line= line.rstrip()
if line.startswith('From:') :
print line

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Skipping with continue
•We can conveniently
skip a line by using the
continuestatement
fhand= open('mbox-short.txt')
forlineinfhand:
line= line.rstrip()
# Skip 'uninteresting lines'
if not line.startswith('From:') :
continue
print line# Process our 'interesting' line

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Usingin to select Lines
•We can look for a string
anywhere ina lineas our
selection criteria
fhand= open('mbox-short.txt')
forlineinfhand:
line= line.rstrip()
if not '@uct.ac.za' inline :
continue
printline

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Prompt for File Name
fname= raw_input('Enter the file name: ')
fhand= open(fname)
count = 0
forlineinfhand:
if line.startswith('Subject:') :
count= count+ 1
print'There were', count, 'subject lines in', fname
Enter the file name: mbox.txt
There were 1797 subject lines in mbox.txt

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Bad File Names fname= raw_input('Enter the file name: ')
try:
fhand= open(fname)
except:
print 'File cannot be opened:',fname
exit()
count = 0
forlinein fhand:
if line.startswith('Subject:') :
count= count+ 1
print'There were',count, 'subject lines in', fname
Enter the file name: nanaboo boo
File cannot be opened: nanaboo boo

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Summary
•Secondary storage
•Opening a file -file handle
•The newline character in files
•Reading a file line-by-line with a for loop
•Reading the whole file as a string
•Searching for lines
•Stripping white space
•Using continue
•Using in as an operator
•Reading a file and splitting
lines
•Prompting for file names
•Dealing with bad files

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Chapter Eight

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
AListis a kind of Collection
•A collectionallows us to put many values in a single “variable”
•A collectionis nice because we can carry many valuesaround in
one convenient package.
friends= [ 'Joseph', 'Glenn', 'Sally' ]
carryon=[ 'socks', 'shirt', 'perfume' ]

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
What is nota “Collection”
•Most of our variableshave one value in them -when we put a new
value in the variable-the old value is over written
>>>x= 2
>>>x = “Hello”
>>>x = 4
>>>printx
4

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
List Constants
•Listconstants are surrounded by
square brackets and the
elements in the list are
separated by commas.
•A listelement can be any
Python object -even another
list
•A listcan be empty
>>>print [1, 24, 76]
[1, 24, 76]
>>>print ['red', 'yellow', 'blue']
['red', 'yellow', 'blue']
>>>print ['red', 24, 98.6]
['red', 24, 98.6]
>>>print [ 1, [5, 6], 7]
[1, [5, 6], 7]
>>>print []
[]

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Using a List : an example
foriin[5, 4, 3, 2, 1]:
printi
print'Blastoff!'
5
4
3
2
1
Blastoff!

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Lists and definite loops
friends= ['Joseph', 'Glenn', 'Sally']
forfriendin friends :
print'Happy New Year: ', friend
print'Done!'
Happy New Year: Joseph
Happy New Year: Glenn
Happy New Year: Sally
Done!

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Looking Inside Lists
•Just like strings, we can get at any single element in a list using an
index specified insquare brackets
0
Joseph
1
Glenn
2
Sally
>>> friends= [ 'Joseph', 'Glenn', 'Sally' ]
>>> printfriends[1]
Glenn

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Lists are Mutable
•Strings are "immutable" -
we cannotchange the
contents of a string -we
must make a new stringto
make any change
•Lists are "mutable" -we can
changean element of a list
using the indexoperator
>>>fruit = 'Banana'
>>>fruit[0]= 'b'
Traceback
TypeError: 'str' object does not
support item assignment
>>>x = fruit.lower()
>>>printx
banana
>>>lotto = [2, 14, 26, 41, 63]
>>>print lotto
[2, 14, 26, 41, 63]
>>>lotto[2] = 28
>>>print lotto
[2, 14, 28, 41, 63]

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
How Long is a List?
•The len()function takes a listas
a parameter and returns the
number of elementsin the list
•Actually len()tells us the
number of elements of anyset
or sequence (i.e., such as a
string...)
>>> greet= 'Hello Bob'
>>> printlen(greet)
9
>>> x= [ 1, 2, 'joe', 99]
>>> print len(x)
4

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Using therangefunction
•The rangefunction returns a
list of numbersthat range
from zero to one less than the
parameter
>>>print range(4)
[0, 1, 2, 3]

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Using range in a for loop
friends= ['Joseph', 'Glenn', 'Sally']
foriinrange(len(friends)) :
friend= friends[i]
print'Happy New Year: ', friend
Happy New Year: Joseph
Happy New Year: Glenn
Happy New Year: Sally

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Concatenatinglists using +
•We can create a new list by adding
two existing lists together
>>>a= [1, 2, 3]
>>> b = [4, 5, 6]
>>>c= a+b
>>>print c
[1, 2, 3, 4, 5, 6]
>>>print a
[1, 2, 3]

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Repeating lists using *
•We can create a new list by multiplying
two existing lists together
>>> [6] *4
[6, 6, 6, 6]
>>>[1, 2, 3] *3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Lists can be slicedusing :
Remember: Just like in
strings, the second
number is "up to but not
including"
>>> t= [9, 41, 12, 3, 74, 15]
>>>t[1:3]
[41,12]
>>>t[:4]
[9, 41, 12, 3]
>>> t[3:]
[3, 74, 15]
>>> t[:]
[9, 41, 12, 3, 74, 15]

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
List Methods
>>> x= [1, 2, 3]
>>> type(x)
<type 'list'>
>>> dir(x)
['append', 'count', 'extend', 'index', 'insert', 'pop',
'remove', 'reverse', 'sort']
http://docs.python.org/tutorial/datastructures.html

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Building a list from scratch
•We can create an empty
listand then add
elements using the
appendmethod
•The list stays in order and
new elements are added
at the end of the list
>>> stuff= list()
>>> stuff.append('book')
>>> stuff.append(99)
>>>print stuff
['book', 99]
>>> stuff.append('cookie')
>>>print stuff
['book', 99, 'cookie']

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Is Somethingin a List?
•Python provides two
operators that let you
check if an item is in a
list
•These are logical
operators that return
Trueor False
•They do not modify the
list
>>>some = [1, 9, 21, 10, 16]
>>>9in some
True
>>> 15in some
False
>>> 20not in some
True

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
A Listis an Ordered Sequence
•A listcan hold many items
and keeps those items in the
order until we do something
to change the order
•A listcan be sorted(i.e., we
can change its order)
>>> friends= [ 'Joseph', 'Glenn', 'Sally' ]
>>> friends.sort()
>>> print friends
['Glenn', 'Joseph', 'Sally']
>>>print friends[1]
Joseph

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Built in Functionsand Lists
•There are a number of
functionsbuilt into
Python that take listsas
parameters
•Remember the loops we
built? These are much
simpler
>>> nums= [3, 41, 12, 9, 74, 15]
>>>print len(nums)
6
>>>print max(nums)
74
>>>print min(nums)
3
>>> print sum(nums)
154
>>>print sum(nums) / len(nums)
25

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Best Friends: Strings and Lists
>>> abc= 'With three words'
>>>stuff =abc.split()
>>> printstuff
['With', 'three', 'words']
>>> printlen(stuff)
3
>>>print stuff[0]
With
Splitbreaks a string into parts produces a list of strings.
We think of these as words. We can accessa particular word.

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
>>> line= 'A lot of spaces '
>>> etc= line.split()
>>>printetc
['A', 'lot', 'of', 'spaces']
>>> line= 'first;second;third'
>>> thing= line.split()
>>> printthing
['first;second;third']
>>> printlen(thing)
1
>>> thing= line.split(';')
>>> print thing['first', 'second', 'third']
>>> print len(thing)
3
You can specify what delimiter
character to use in the splitting.

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
From [email protected] SatJan 5 09:14:16 2008
fhand= open('mbox-short.txt')
for lineinfhand:
line= line.rstrip()
if not line.startswith('From ') :
continue
words= line.split()
print words[2]
Sat
Fri
Fri
Fri
...

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
The Double Split Pattern
•Sometimes we split a line one way and then grab one of the pieces
of the line and split that piece again
From [email protected] Sat Jan 5 09:14:16 2008
[email protected]
['stephen.marquard', 'uct.ac.za']
'uct.ac.za'
words = line.split()
email= words[1]
pieces=email.split('@')
printpieces[1]

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Mystery Problem...
[email protected] SatJan5 09:14:16 2008
fhand= open('mbox-short.txt')
forlineinfhand:
line= line.rstrip()
words=line.split()
if words[0]!= 'From' :
continue
print words[2]
Traceback (most recent call last): File "search8.py", line 5, in <module>
if words[0] != 'From' : continueIndexError:
list index out of range

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Summary
•Concept of a collection
•Lists and definite loops
•Indexing and lookup
•List mutability
•Functions: len, min, max, sum
•Slicing lists
•List method: append
•Sorting lists
•Splitting strings into lists of words
•Using split to parse strings

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Chapter Nine

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
What is a Collection?
•A collection is nice because we can put more than one value in them
and carry them all around in one convenient package.
•We have a bunch of values in a single “variable”
•We do this by having more than one place “in” the variable.
•We have ways of finding the different places in the variable

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
What is nota “Collection”
•Most of our variableshave one value in them -when we put a new
value in the variable-the old value is over written
>>>x= 2
>>>x= 4
>>>printx
4

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
A Story of Two Collections..
•List
•A linear collection of values that stay in order
•Dictionary
•A “bag” of values, each with its own label (key)
•In other words, a collection of Key/Value pairs

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Dictionaries
money
tissue
calculator
perfume
candy

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Dictionaries(Associative Arrays)
•Dictionaries allow us to do fast database-like operations in Python
•Dictionaries have different names in different languages
•Dictionaries –Python, Objective-C, Smalltalk, REALbasic
•Hashes –Ruby, Perl,
•Maps –C++, Java, Go, Clojure, Scala, OCaml, Haskell
•Property Bag -C#

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Dictionaries
•Lists index their entries
based on the position in
the list
•Dictionaries are like bags
-no order
•So, we index the things
we put in the dictionary
with a “lookup tag”
>>> purse= dict()
>>> printpurse
{}
>>> purse['money'] = 12
>>> purse['candy'] = 3
>>> purse['tissues'] = 75
>>> printpurse
{'money': 12, 'tissues': 75, 'candy': 3}
>>> printpurse['candy']
3
>>> purse['candy'] = purse['candy'] + 2
>>> printpurse
{'money': 12, 'tissues': 75, 'candy': 5}

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Comparing Lists and Dictionaries
•Dictionariesare like Listsexcept that they use keysinstead of numbersto look up values
>>> lst= list()
>>> lst.append(21)
>>> lst.append(183)
>>>printlst
[21, 183]
>>> lst[0]=23
>>>printlst
[23, 183]
>>> ddd=dict()
>>> ddd['age'] = 21
>>> ddd['course'] = 182
>>> printddd
{'course': 182, 'age': 21}
>>> ddd['age'] = 23
>>> printddd
{'course': 182, 'age': 23}

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Dictionary Literals (Constants)
•Dictionary literals use curly braces and have a list of key: valuepairs
•You can make an empty dictionaryusing empty curly braces
>>> j = { 'chuck' : 1, 'fred' : 42, 'jan': 100}
>>> printj
{'jan': 100, 'chuck': 1, 'fred': 42}
>>> o = { }
>>> printo
{}

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Dictionary Tracebacks
•It is an errorto reference a key which is not in the dictionary
•We can use the inoperator to see if a key is in the dictionary
>>> c = dict()
>>>printc['csev']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'csev'
>>> print'csev' inc
False

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
When we see a new name
•When we encounter a new name, we need to add a new entry in the dictionary
and if this the second or later time we have seen the name, we simply add one
to the count in the dictionaryunder that name
counts= dict()
names= ['csev', 'cwen', 'csev', 'zqian', 'cwen']
fornameinnames:
if namenot in counts:
counts[name] = 1
else :
counts[name] = counts[name] + 1
printcounts {'csev': 2, 'zqian': 1,'cwen': 2}

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
The get method for dictionary
•This pattern of checking to see if a keyis
already in a dictionary and assuming a default
value if the keyis not there is so common,
that there is a methodcalled get() that does
this for us
if namein counts:
print
counts[name]
else:
print0
Default value if key does not
exist (and no Traceback).
{'csev': 2, 'zqian': 1,'cwen': 2}
printcounts.get(name, 0)

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Simplified counting with get()
•We can use get() and provide a default value of zerowhen the keyis not yet in the
dictionary -and then just add one
counts = dict()
names= ['csev', 'cwen', 'csev', 'zqian', 'cwen']
fornamein names :
counts[name] = counts.get(name, 0)+ 1
print counts
Default {'csev': 2, 'zqian': 1,'cwen': 2}

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Counting Pattern
The general pattern to count the words in a line of text is to splitthe line into words, then
loop through the words and use a dictionaryto track the count of each word
independently.
counts= dict()
print'Enter a line of text:'
line = raw_input('')
words= line.split()
print'Words:', words
print 'Counting...'
forword inwords:
counts[word] = counts.get(word,0) + 1
print'Counts', counts

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Counting Words
python wordcount.py
Enter a line of text:
theclown ran afterthe car and thecar ran into thetent and thetent
fell down on theclown and thecar
Words: ['the', 'clown', 'ran', 'after', 'the', 'car', 'and', 'the', 'car', 'ran',
'into', 'the', 'tent', 'and', 'the', 'tent', 'fell', 'down', 'on', 'the', 'clown',
'and', 'the', 'car']
Counting...
Counts {'and': 3, 'on': 1, 'ran': 2, 'car': 3, 'into': 1, 'after': 1, 'clown': 2,
'down': 1, 'fell': 1, 'the': 7, 'tent': 2}

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Definite Loops and Dictionaries
•Even though dictionaries are not stored in order, we can write a for loop that
goes through all the entries in a dictionary -it goes through all the keys in the
dictionary and looks up the values
>>> counts= { 'chuck': 1 , 'fred': 42, 'jan': 100}
>>> forkeyincounts:
print key, counts[key]
jan100
chuck1
fred42
>>>

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Retrieving lists of Keys and Values
•You can get a list of keys,
valuesoritems (both)
from a dictionary
>>> jjj= { 'chuck' : 1 , 'fred' : 42, 'jan': 100}
>>> printlist(jjj)
['jan', 'chuck', 'fred']
>>> print jjj.keys()
['jan', 'chuck', 'fred']
>>> printjjj.values()
[100, 1, 42]
>>> printjjj.items()
[('jan', 100), ('chuck', 1), ('fred', 42)]
>>>
What is a 'tuple'? -coming soon...

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Bonus: Two Iteration Variables!
•We loop through the key-value
pairs in a dictionary using
*two* iteration variables
•Each iteration, the first variable
is the keyand the second
variable is the corresponding
valuefor the key
>>> jjj= { 'chuck' : 1 , 'fred' : 42, 'jan': 100}
>>> for aaa,bbbin jjj.items() :
print aaa, bbb
jan100
chuck1
fred42
>>>

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Summary
•What is a collection?
•Lists versus Dictionaries
•Dictionary constants
•The most common word: counts
•Using the get() method
•Definite loops and dictionaries
•list() function
•keys(), values(), and items() methods
•Using two iteration variables in a for
loop with a dictionary

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Chapter Ten

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Tuples are like lists
•Tuples are another kind of sequence that function much like a list -they
have elements which are indexed starting at 0
>>>x = ('Glenn', 'Sally', 'Joseph')
>>>printx[2]
Joseph
>>> y = ( 1, 9, 2 )
>>> print y
(1, 9, 2)
>>>printmax(y)
9
>>>for iterin y:
print iter,
>>> 1 9 2

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
..but.. Tuplesare "immutable"
•Unlike a list, once you create a tuple, youcannot alterits
contents -similar to a string
>>> x= [9, 8, 7]
>>> x[2] = 6
>>>printx
[9, 8, 6]
>>>
>>> y= 'ABC'
>>>y[2] ='D'
Traceback:'str' object
does not support
item assignment
>>>
>>> z= (5, 4, 3)
>>>z[2]= 0
Traceback:'tuple'
object does
not support item
assignment
>>>

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Thingsnotto do with tuples
>>> x= (3, 2, 1)
>>> x.sort()
Traceback:AttributeError :
'tuple' object has no attribute 'sort'
>>> x.append(5)
Traceback:AttributeError :
'tuple' object has no attribute 'append'
>>> x.reverse()
Traceback:AttributeError :
'tuple' object has no attribute 'reverse'
>>>

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
A Tale of Two Sequences
>>> l= list()
>>> dir(l)
['append', 'count', 'extend', 'index', 'insert', 'pop',
'remove', 'reverse', 'sort']
>>> t= tuple()
>>> dir(t)
['count', 'index']

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Tuples are more efficient
•Since Python does not have to build tuple structures to be
modifiable, they are simpler and more efficient in terms of
memory use and performance than lists
•So in our program when we are making "temporary variables",
we prefer tuples over lists.

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Tuplesand Assignment
•We can also put a tupleon the left-hand sideof an
assignment statement
•We can even omit the parenthesis
>>> (x, y)= (4, 'fred')
>>>print y
fred
>>> (a, b)= (99, 98)
>>>print a
99

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Tuplesand Dictionaries
•Theitems() method in
dictionaries returns a list
of (key, value)tuples
>>> d = dict()
>>> d['csev']= 2
>>> d['cwen']= 4
>>>for(k,v)ind.items():
printk, v
csev2
cwen4
>>> tups= d.items()
>>>printtups
[('csev', 2),('cwen', 4)]

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Tuplesare Comparable
•The comparison operatorswork with tuplesand other sequences if the first
item is equal, Python goes on to the next element, and so on, until it finds
elements that differ.
>>> (0, 1, 2) <(5, 1, 2)
True>>> (0, 1, 2000000) <(0, 3, 4)
True
>>> ( 'Jones', 'Sally' ) <('Jones', 'Fred')
False
>>> ( 'Jones', 'Sally') >('Adams', 'Sam')
True

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Sorting Lists of Tuples
•We can take advantage of the ability to sort a list of tuplesto get
a sorted version of a dictionary
•First, we sort the dictionary by the key using the items() method
>>> d= {'a':10, 'b':1, 'c':22}
>>> t= d.items()
print t
[('a', 10), ('c', 22), ('b', 1)]
>>> t.sort()
print t
[('a', 10), ('b', 1), ('c', 22)]

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Usingsorted()
We can do this even
more directly using the
built-in function sorted
that takes a sequence as
a parameter and returns
a sorted sequence
>>> d= {'a':10, 'b':1, 'c':22}
>>> d.items()
[('a', 10), ('c', 22), ('b', 1) ]
>>> t= sorted(d.items())
print t
[('a', 10), ('b', 1), ('c', 22)]
>>> fork, vin sorted(d.items()):
printk, v,
a 10 b 1 c 22

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Sortbyvalues instead of key
•If we could construct a
list of tuplesof the
form (value, key)we
could sortby value
•We do this with a for
loop that creates a list
of tuples
>>> c= {'a':10, 'b':1, 'c':22}
>>> tmp= list()
>>> fork, vin c.items() :
tmp.append( (v, k))
>>> print tmp
[(10, 'a'), (22, 'c'), (1, 'b')]
>>> tmp.sort(reverse=True)
>>> print tmp
[(22, 'c'), (10, 'a'), (1, 'b')]

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
fhand= open('romeo.txt')
counts= dict()
forlineinfhand:
words= line.split()
forwordinwords:
counts[word] = counts.get(word, 0 ) + 1
lst= list()
forkey, valincounts.items():
lst.append( (val, key))
lst.sort(reverse=True)
for val, keyin lst[:10] :
print key, val The top 10 most
common words.

Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Summary
•Tuple syntax
•Mutability (not)
•Comparability
•Sortable
•Tuples in assignment statements
•Using sorted()
•Sorting dictionaries by either key or value

ANY QUESTIONS?
GHULAM MUSTAFA SHORO
0332 -3216699
YOU CAN FIND ME AT:
[email protected]