SlideShare a Scribd company logo
1 of 235
Download to read offline
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) perWeek
▪ 1 Credit Hour (Lab) perWeek
» CourseTutor: Ghulam Mustafa Shoro
BS - Software Engineering Part - II Second Semester
Day Theory Lab ( Comp Lab II)
Thursday 2:00 PM – 4:00 PM 5:00 PM – 7:00 PM
About This course
• This course aims to teach everyone the basics of programming
computers using Python. We cover the basics of how one constructs a
program from a series of simple instructions in Python.
• The course has no pre-requisites and avoids all but the simplest
mathematics. Anyone with moderate computer experience should be
able to master the materials in this course.
• This course will cover Chapters 1-5 of the textbook “Python for
Everybody”. Once a student completes this course, they will be ready to
take more advanced programming courses. This course covers Python 3.
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
▪The most recent major version of Python is Python 3, which we shall be
using in this tutorial. However, Python 2, although not being updated
with anything other than security updates, is still quite popular.
▪In this tutorial Python will be written in a text editor. It is possible to write
Python in an Integrated Development Environment, such as Thonny,
Pycharm, Netbeans or Eclipse which are particularly useful when
managing larger collections of Python files.
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 values such as numbers, letters, and strings are called
“constants” - because their value does not change
• Numeric constants are as you expect
• String constants use single-quotes (')
or double-quotes (")
>>> print 123
123
>>> print 98.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 variable is 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 variable in a later statement
x = 12.2
y = 14
x = 100
12.2
x
14
y
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 type and can 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 Spam SPAM
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 same value 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
print x
Variable Operator 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 assignment statement (=)
• An assignment statement consists of an expression on the right-
hand side and a variable to 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.6
x
0.6 0.6
0.4
0.936
0.936
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. 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.93
x
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
>>> print x
4
>>> y = 440 * 12
>>> print y
5280
>>> z = y / 1000
>>> print z
5
>>> j = 23
>>> k = j % 5
>>> print k
3
>>> print 4 ** 3
64
5 23
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
>>> print 10 / 2
5
>>> print 9 / 2
4
>>> print 99 / 100
0
>>> print 10.0 / 2.0
5.0
>>> print 99.0 / 100.0
0.99
This 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
>>> print 99 / 100
0
>>> print 99 / 100.0
0.99
>>> print 99.0 / 100
0.99
>>> print 1 + 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
Type Matters
• 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()
>>> print float(99) / 100
0.99
>>> i = 42
>>> type(i)
<type 'int'>
>>> f = float(i)
>>> print f
42.0
>>> type(f)
<type 'float'>
>>> print 1 + 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 error if 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
• The raw_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
String Operations
• 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 and x < 10
• is true only if x is greater than 0 and less than 10.
• n%2 == 0 or n%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
if x < 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 to the 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 / maintain after if or 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 i in 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'
yes
no
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'
yes
no
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
if x < 2 :
print 'Small'
elif x < 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 / except Structure
• You surround a dangerous section of code with try and except.
• If the code in the try works - the except is skipped
• If the code in the try fails - it jumps to the except section
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:
def hello():
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 def reserved 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')
>>> print big
>>> ‘w’
A function is some
stored code that we
use. A function takes
some input and
produces an output.
max()
function
“Hello world”
(a string)
‘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()
>>> print float(99) / 100
0.99
>>> i = 42
>>> type(i)
<type 'int'>
>>> f = float(i)
>>> print f
42.0
>>> type(f)
<type 'float'>
>>> print 1 + 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 error if 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
Building our Own Functions
• We create a new function using the def keyword followed by the
function name, optional parameters in parenthesis, and then we add a
colon.
• We indent the body of the function
• This defines the function but does not execute the body of the
function
def print_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'
def print_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
print x
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
Definitions and Uses
• Once we have defined a function, we can call (or invoke) it as many
times as we like
• This is the store and reuse 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
print x
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
• An argument is a value we pass into the function as its input when we
call the function
• We use arguments so we can direct the function to do different kinds
of work when we call it at different times
• We put the arguments in parenthesis after the name of 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
• A parameter is a variable
which we use in the
function definition that is a
“handle” that allows the
code in the function to
access the arguments for a
particular function
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
Return Values
• Often a function will take its arguments, do some computation and
return a value to be used as the value of the function call in the calling
expression. The return keyword is used for this.
def greet():
return "Hello "
print greet(), "Glenn"
print greet(), "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” function is one
that produces a result (or a
return value)
• The return statement ends
the function execution and
“sends back” the result of
the function
def greet(lang):
if lang == 'es':
return 'Hola '
elif lang == 'fr':
return 'Bonjour '
else:
return 'Hello '
print greet('en'),'Glenn'
Hello Glenn
print greet('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
for x in y:
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
Multiple Parameters / Arguments
• We can define more than one
parameter in the function
definition
• We simply add more
arguments when we call the
function
• We match the number and
order of arguments and
parameters
def addtwo(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
import math
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
print n
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
while True:
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
while True:
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
print line
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 list of 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 for construct
• 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
for i in [5, 4, 3, 2, 1] :
print i
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']
for friend in 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
A Simple Definite Loop
for i in [5, 4, 3, 2, 1] :
print i
print 'Blastoff!'
5
4
3
2
1
Blastoff!
Definite loops (for loops) have explicit iteration
variables that change each time through a loop. These
iteration variables move through the sequence or set.
Done?
No
print ‘Blast Off!'
Yes
print i
Move i ahead
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
for i in range(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
• The block (body) of code
is executed once for each
value in the sequence
• The iteration variable
moves through all of the
values in the sequence
for i in [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'
for thing 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
for thing in [9, 41, 12, 3, 74, 15] :
zork = zork + 1
print zork, thing
print 'After', zork
Before 0
1 9
2 41
3 12
4 3
5 74
6 15
After 6
To count how 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
for thing in [9, 41, 12, 3, 74, 15] :
zork = zork + thing
print zork, thing
print 'After', zork
Before 0
9 9
50 41
62 12
65 3
139 74
154 15
After 154
To add up a value we encounter in a loop, we introduce a sum variable that
starts at 0 and 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 0 0
1 9 9
2 50 41
3 62 12
4 65 3
5 139 74
6 154 15
After 6 154 25
An average just combines the counting and sum patterns
and divides 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 in the loop to 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 value in [9, 41, 12, 3, 74, 15] :
if value == 3 :
found = True
print found, value
print 'After', found
Before False
False 9
False 41
False 12
True 3
True 74
True 15
After True
If we just want to search and know if a value was found - we use a variable that starts
at False and is set to True as soon as we find what 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 smallest value
smallest = None
print 'Before'
for value in [9, 41, 12, 3, 74, 15] :
If smallest is None :
smallest = value
elif value < smallest :
smallest = value
print smallest, value
print 'After', smallest
Before
9 9
9 41
9 12
3 3
3 74
3 15
After 3
We still have a variable that is the smallest so far. The first time through the
loop smallest is None so we take the first value to 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'
for value in [3, 41, 12, 9, 74, 15] :
if smallest is None :
smallest = value
elif value < smallest :
smallest = value
print smallest, 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
>>> print bob
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
>>> print x
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 strings and 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 converted from 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
>>> print x
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]
>>> print letter
a
>>> n = 3
>>> w = fruit[n - 1]
>>> print w
n
b a n a n a
0 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
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‘
>>> print zot[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 len that
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)
>>> print x
6
A function is some stored
code that 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
len function, 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 for loop
fruit = 'banana'
for letter in 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
for letter in word :
if letter == 'a' :
count = count + 1
print count
Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Looking Deeper into in
• The iteration variable
“iterates” though the
sequence (ordered set)
• The block (body) of code is
executed once for each
value in the sequence
• The iteration variable
moves through all of the
values in the sequence
for letter in '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
for letter in 'banana' :
print letter
b a n a n a
letter
The iteration 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
5 6
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‘
>>> print s[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
5 6
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‘
>>> print s[:2]
Mo
>>> print s[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
modulus operator
• 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 code String 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)
print s
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)
%i Integer
%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 in as an Operator
• The in keyword 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 False and can be used in
an if statement
>>> fruit = 'banana‘
>>> 'n' in fruit
True
>>> 'm' in fruit
False
>>> 'nan' in fruit
True
>>> if 'a' in fruit :
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.‘
elif word > 'banana':
print 'Your word,' + word + ', comes after banana.‘
else:
print 'All right, bananas.'
if word == '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
functions which are in the string
library
• These functions are already built into
every string - we invoke them by
appending the function to the string
variable
• These functions do 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
>>> print greet
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
occurance of the substring
• If the substring is not found,
find() returns -1
• Remember that string
position starts at zero
>>> fruit = 'banana'
>>> pos = fruit.find('na')
>>> print pos
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()
>>> print nnn
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
occurrences of the
search string with the
replacement string
>>> greet = 'Hello Bob'
>>> nstr = greet.replace('Bob','Jane')
>>> print nstr
Hello Jane
>>> greet = 'Hello Bob'
>>> nstr = greet.replace('o','X')
>>> print nstr
HellX BXb
>>>
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 for and while
• Concatenating strings with +
• in as 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: [Errno 2] 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 Newline Character
• We use a special character to
indicate when a line ends
called the "newline"
• We represent it as n in strings
• Newline is still one character -
not two
>>> stuff = 'HellonWorld!'
>>> print stuff
Hello
World!
>>> stuff = 'XnY'
>>> print stuff
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 stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
Return-Path: <postmaster@collab.sakaiproject.org>
Date: Sat, 5 Jan 2008 09:12:18 -0500To: source@collab.sakaiproject.orgFrom:
stephen.marquard@uct.ac.zaSubject: [sakai] svn commit: 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 newlines at the end of each line
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008n
Return-Path: <postmaster@collab.sakaiproject.org>n
Date: Sat, 5 Jan 2008 09:12:18 -0500nTo:
source@collab.sakaiproject.orgnFrom:
stephen.marquard@uct.ac.zanSubject: [sakai] svn commit: r39772 -
content/branches/nDetails:
http://source.sakaiproject.org/viewsvn/?view=rev&rev=39772n
Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
File Handle as a Sequence
• A file handle open for read can be treated
as a sequence of strings where each line in
the file is a string in the sequence
• We can use the for statement to iterate
through a sequence
• Remember - a sequence is an ordered set
xfile = open('mbox.txt')
for cheese in xfile:
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 file read-only
• Use a for loop to read each line
• Count the lines and print out
the number of lines
fhand = open('mbox.txt')
count = 0
for line 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 read the whole
file (newlines and all) into
a single string.
>>> fhand = open('mbox-short.txt')
>>> inp = fhand.read()
>>> print len(inp)
94626
>>> print inp[: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 if statement
in our for loop to only print
lines that meet some
criteria
fhand = open('mbox-short.txt')
for line in fhand:
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: stephen.marquard@uct.ac.za
From: louis@media.berkeley.edu
From: zqian@umich.edu
From: rjlowe@iupui.edu...
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 print statement adds a
newline to each line.
Each line from the file also
has a newline at the end.
From: stephen.marquard@uct.ac.zann
From: louis@media.berkeley.edunn
From: zqian@umich.edunn
From: rjlowe@iupui.edun
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')
for line in fhand:
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
continue statement fhand = open('mbox-short.txt')
for line in fhand:
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
Using in to select Lines
• We can look for a string
anywhere in a line as our
selection criteria
fhand = open('mbox-short.txt')
for line in fhand:
line = line.rstrip()
if not '@uct.ac.za' in line :
continue
print line
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
for line in fhand:
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
for line in fhand:
if line.startswith('Subject:') :
count = count + 1
print 'There were', count, 'subject lines in', fname
Enter the file name: na na boo boo
File cannot be opened: na na boo 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
A List is a kind of Collection
• A collection allows us to put many values in a single “variable”
• A collection is nice because we can carry many values around 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 not a “Collection”
• Most of our variables have 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
>>> print x
4
Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
List Constants
• List constants are surrounded by
square brackets and the
elements in the list are
separated by commas.
• A list element can be any
Python object - even another
list
• A list can 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
for i in [5, 4, 3, 2, 1] :
print i
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']
for friend in 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 in square brackets
0
Joseph
1
Glenn
2
Sally
>>> friends = [ 'Joseph', 'Glenn', 'Sally' ]
>>> print friends[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 cannot change the
contents of a string - we
must make a new string to
make any change
• Lists are "mutable" - we can
change an element of a list
using the index operator
>>> fruit = 'Banana'
>>> fruit[0] = 'b'
Traceback
TypeError: 'str' object does not
support item assignment
>>> x = fruit.lower()
>>> print x
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 list as
a parameter and returns the
number of elements in the list
• Actually len() tells us the
number of elements of any set
or sequence (i.e., such as a
string...)
>>> greet = 'Hello Bob'
>>> print len(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 the range function
• The range function returns a
list of numbers that 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']
for i in range(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
Concatenating lists 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 sliced using :
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
list and then add
elements using the
append method
• 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 Something in a List?
• Python provides two
operators that let you
check if an item is in a
list
• These are logical
operators that return
True or False
• They do not modify the
list
>>> some = [1, 9, 21, 10, 16]
>>> 9 in some
True
>>> 15 in some
False
>>> 20 not in some
True
Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
A List is an Ordered Sequence
• A list can hold many items
and keeps those items in the
order until we do something
to change the order
• A list can 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 Functions and Lists
• There are a number of
functions built into
Python that take lists as
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()
>>> print stuff
['With', 'three', 'words']
>>> print len(stuff)
3
>>> print stuff[0]
With
Split breaks a string into parts produces a list of strings.
We think of these as words. We can access a 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()
>>> print etc
['A', 'lot', 'of', 'spaces']
>>> line = 'first;second;third'
>>> thing = line.split()
>>> print thing
['first;second;third']
>>> print len(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 stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
fhand = open('mbox-short.txt')
for line in fhand:
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 stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
stephen.marquard@uct.ac.za
['stephen.marquard', 'uct.ac.za']
'uct.ac.za'
words = line.split()
email = words[1]
pieces = email.split('@')
print pieces[1]
Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Mystery Problem...
From stephen.marquard@uct.ac.za Sat Jan5 09:14:16 2008
fhand = open('mbox-short.txt')
for line in fhand:
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 not a “Collection”
• Most of our variables have one value in them - when we put a new
value in the variable - the old value is over written
>>> x = 2
>>> x = 4
>>> print x
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()
>>> print purse
{}
>>> purse['money'] = 12
>>> purse['candy'] = 3
>>> purse['tissues'] = 75
>>> print purse
{'money': 12, 'tissues': 75, 'candy': 3}
>>> print purse['candy']
3
>>> purse['candy'] = purse['candy'] + 2
>>> print purse
{'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
• Dictionaries are like Lists except that they use keys instead of numbers to look up values
>>> lst = list()
>>> lst.append(21)
>>> lst.append(183)
>>> print lst
[21, 183]
>>> lst[0] = 23
>>> print lst
[23, 183]
>>> ddd = dict()
>>> ddd['age'] = 21
>>> ddd['course'] = 182
>>> print ddd
{'course': 182, 'age': 21}
>>> ddd['age'] = 23
>>> print ddd
{'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 : value pairs
• You can make an empty dictionary using empty curly braces
>>> j = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}
>>> print j
{'jan': 100, 'chuck': 1, 'fred': 42}
>>> o = { }
>>> print o
{}
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 error to reference a key which is not in the dictionary
• We can use the in operator to see if a key is in the dictionary
>>> c = dict()
>>> print c['csev']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'csev'
>>> print 'csev' in c
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 dictionary under that name
counts = dict()
names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']
for name in names :
if name not in counts:
counts[name] = 1
else :
counts[name] = counts[name] + 1
print counts {'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 key is
already in a dictionary and assuming a default
value if the key is not there is so common,
that there is a method called get() that does
this for us
if name in counts:
print
counts[name]
else :
print 0
Default value if key does not
exist (and no Traceback).
{'csev': 2, 'zqian': 1, 'cwen': 2}
print counts.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 zero when the key is not yet in the
dictionary - and then just add one
counts = dict()
names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']
for name in 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 split the line into words, then
loop through the words and use a dictionary to 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...'
for word in words:
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:
the clown ran after the car and the car ran into the tent and the tent
fell down on the clown and the car
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}
>>> for key in counts:
print key, counts[key]
jan 100
chuck 1
fred 42
>>>
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,
values or items (both)
from a dictionary
>>> jjj = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}
>>> print list(jjj)
['jan', 'chuck', 'fred']
>>> print jjj.keys()
['jan', 'chuck', 'fred']
>>> print jjj.values()
[100, 1, 42]
>>> print jjj.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 key and the second
variable is the corresponding
value for the key
>>> jjj = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}
>>> for aaa,bbb in jjj.items() :
print aaa, bbb
jan 100
chuck 1
fred 42
>>>
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')
>>> print x[2]
Joseph
>>> y = ( 1, 9, 2 )
>>> print y
(1, 9, 2)
>>> print max(y)
9
>>> for iter in 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.. Tuples are "immutable"
• Unlike a list, once you create a tuple, you cannot alter its
contents - similar to a string
>>> x = [9, 8, 7]
>>> x[2] = 6
>>> print x
[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
Things not to 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
Tuples and Assignment
• We can also put a tuple on the left-hand side of 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
Tuples and Dictionaries
• The items() method in
dictionaries returns a list
of (key, value) tuples
>>> d = dict()
>>> d['csev'] = 2
>>> d['cwen'] = 4
>>> for (k,v) in d.items():
print k, v
csev 2
cwen 4
>>> tups = d.items()
>>> print tups
[('csev', 2), ('cwen', 4)]
Ghulam Mustafa Shoro
U N I V E R S I T Y O F S I N D H
Tuples are Comparable
• The comparison operators work with tuples and 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 tuples to 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
Using sorted()
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)]
>>> for k, v in sorted(d.items()):
print k, 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
Sort by values instead of key
• If we could construct a
list of tuples of the
form (value, key) we
could sort by value
• We do this with a for
loop that creates a list
of tuples
>>> c = {'a':10, 'b':1, 'c':22}
>>> tmp = list()
>>> for k, v in 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()
for line in fhand:
words = line.split()
for word in words:
counts[word] = counts.get(word, 0 ) + 1
lst = list()
for key, val in counts.items():
lst.append( (val, key) )
lst.sort(reverse=True)
for val, key in 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:
gm.shoro@usindh.edu.pk
Python Basics.pdf

More Related Content

What's hot

Fundamentals of Python Programming
Fundamentals of Python ProgrammingFundamentals of Python Programming
Fundamentals of Python ProgrammingKamal Acharya
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programmingSrinivas Narasegouda
 
Python Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaPython Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaEdureka!
 
Python Programming ppt
Python Programming pptPython Programming ppt
Python Programming pptismailmrribi
 
Python Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaPython Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaEdureka!
 
Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming LanguageDipankar Achinta
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming LanguageTahani Al-Manie
 
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Python Tutorial | Python Tutorial for Beginners | Python Training | EdurekaPython Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Python Tutorial | Python Tutorial for Beginners | Python Training | EdurekaEdureka!
 
Lesson 03 python statement, indentation and comments
Lesson 03   python statement, indentation and commentsLesson 03   python statement, indentation and comments
Lesson 03 python statement, indentation and commentsNilimesh Halder
 
Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3Chariza Pladin
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python amiable_indian
 

What's hot (20)

Fundamentals of Python Programming
Fundamentals of Python ProgrammingFundamentals of Python Programming
Fundamentals of Python Programming
 
Begin with Python
Begin with PythonBegin with Python
Begin with Python
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
 
Python Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaPython Programming Tutorial | Edureka
Python Programming Tutorial | Edureka
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Python Programming ppt
Python Programming pptPython Programming ppt
Python Programming ppt
 
Python programming
Python  programmingPython  programming
Python programming
 
Python Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaPython Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | Edureka
 
Python ppt
Python pptPython ppt
Python ppt
 
Python introduction
Python introductionPython introduction
Python introduction
 
Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming Language
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming Language
 
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Python Tutorial | Python Tutorial for Beginners | Python Training | EdurekaPython Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
 
Lesson 03 python statement, indentation and comments
Lesson 03   python statement, indentation and commentsLesson 03   python statement, indentation and comments
Lesson 03 python statement, indentation and comments
 
Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3
 
Programming with Python
Programming with PythonProgramming with Python
Programming with Python
 
Beginning Python Programming
Beginning Python ProgrammingBeginning Python Programming
Beginning Python Programming
 
Python final ppt
Python final pptPython final ppt
Python final ppt
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
Python basics
Python basicsPython basics
Python basics
 

Similar to Python Basics.pdf

Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.supriyasarkar38
 
Python basics_ part1
Python basics_ part1Python basics_ part1
Python basics_ part1Elaf A.Saeed
 
modul-python-part1.pptx
modul-python-part1.pptxmodul-python-part1.pptx
modul-python-part1.pptxYusuf Ayuba
 
Python (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualizePython (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualizeIruolagbePius
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdfsamiwaris2
 
python programming for beginners and advanced
python programming for beginners and advancedpython programming for beginners and advanced
python programming for beginners and advancedgranjith6
 
INTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptxINTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptxNimrahafzal1
 
IoT-Week1-Day1-Lab.pptx
IoT-Week1-Day1-Lab.pptxIoT-Week1-Day1-Lab.pptx
IoT-Week1-Day1-Lab.pptxafsheenfaiq2
 
Python Basics by Akanksha Bali
Python Basics by Akanksha BaliPython Basics by Akanksha Bali
Python Basics by Akanksha BaliAkanksha Bali
 
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdfPy-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdfshetoooelshitany74
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programmingChetan Giridhar
 
Python week 2 2019 2020 for g10 by eng.osama ghandour
Python week 2 2019 2020 for g10 by eng.osama ghandourPython week 2 2019 2020 for g10 by eng.osama ghandour
Python week 2 2019 2020 for g10 by eng.osama ghandourOsama Ghandour Geris
 

Similar to Python Basics.pdf (20)

Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.
 
Python basics_ part1
Python basics_ part1Python basics_ part1
Python basics_ part1
 
modul-python-part1.pptx
modul-python-part1.pptxmodul-python-part1.pptx
modul-python-part1.pptx
 
Python (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualizePython (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualize
 
Python Module-1.1.pdf
Python Module-1.1.pdfPython Module-1.1.pdf
Python Module-1.1.pdf
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdf
 
Unit -1 CAP.pptx
Unit -1 CAP.pptxUnit -1 CAP.pptx
Unit -1 CAP.pptx
 
python programming for beginners and advanced
python programming for beginners and advancedpython programming for beginners and advanced
python programming for beginners and advanced
 
INTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptxINTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptx
 
python_class.pptx
python_class.pptxpython_class.pptx
python_class.pptx
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
IoT-Week1-Day1-Lab.pptx
IoT-Week1-Day1-Lab.pptxIoT-Week1-Day1-Lab.pptx
IoT-Week1-Day1-Lab.pptx
 
Python Basics by Akanksha Bali
Python Basics by Akanksha BaliPython Basics by Akanksha Bali
Python Basics by Akanksha Bali
 
Python fundamentals
Python fundamentalsPython fundamentals
Python fundamentals
 
python-ppt.ppt
python-ppt.pptpython-ppt.ppt
python-ppt.ppt
 
python-ppt.ppt
python-ppt.pptpython-ppt.ppt
python-ppt.ppt
 
Python made easy
Python made easy Python made easy
Python made easy
 
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdfPy-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programming
 
Python week 2 2019 2020 for g10 by eng.osama ghandour
Python week 2 2019 2020 for g10 by eng.osama ghandourPython week 2 2019 2020 for g10 by eng.osama ghandour
Python week 2 2019 2020 for g10 by eng.osama ghandour
 

Recently uploaded

High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 

Recently uploaded (20)

High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 

Python Basics.pdf

  • 1. INTRODUCTION ASSISTANT PROFESSOR GHULAM MUSTAFA SHORO DEPARTMENT OF ELECTRONIC ENGINEERING FACULTY OF ENGINEERING & TECHNOLOGY UNIVERSITY OF SINDH
  • 2. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H
  • 3. SENG 424 Python Programming » Course Details ▪ Python Programming (Theory + Lab) ▪ 2 Credit Hours (Theory) perWeek ▪ 1 Credit Hour (Lab) perWeek » CourseTutor: Ghulam Mustafa Shoro BS - Software Engineering Part - II Second Semester Day Theory Lab ( Comp Lab II) Thursday 2:00 PM – 4:00 PM 5:00 PM – 7:00 PM
  • 4. About This course • This course aims to teach everyone the basics of programming computers using Python. We cover the basics of how one constructs a program from a series of simple instructions in Python. • The course has no pre-requisites and avoids all but the simplest mathematics. Anyone with moderate computer experience should be able to master the materials in this course. • This course will cover Chapters 1-5 of the textbook “Python for Everybody”. Once a student completes this course, they will be ready to take more advanced programming courses. This course covers Python 3.
  • 6. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H
  • 7. 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.
  • 8. 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.
  • 9. 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.
  • 10. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Good to Know ▪The most recent major version of Python is Python 3, which we shall be using in this tutorial. However, Python 2, although not being updated with anything other than security updates, is still quite popular. ▪In this tutorial Python will be written in a text editor. It is possible to write Python in an Integrated Development Environment, such as Thonny, Pycharm, Netbeans or Eclipse which are particularly useful when managing larger collections of Python files.
  • 11. 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.
  • 12. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Chapter Two
  • 13. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Constants • Fixed values such as numbers, letters, and strings are called “constants” - because their value does not change • Numeric constants are as you expect • String constants use single-quotes (') or double-quotes (") >>> print 123 123 >>> print 98.6 98.6 >>> print 'Hello world' Hello world
  • 14. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Variables ▪ A variable is 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 variable in a later statement x = 12.2 y = 14 x = 100 12.2 x 14 y 100
  • 15. 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 type and can 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'
  • 16. 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 Spam SPAM
  • 17. 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"
  • 18. 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 same value to multiple variables in one line: Example x = y = z = "Orange" print(x) print(y) print(z)
  • 19. 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)
  • 20. 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)
  • 21. 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)
  • 22. 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!")
  • 23. 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
  • 24. 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 print x Variable Operator Constant Reserved Word A statement is a unit of code that the Python interpreter can execute.
  • 25. 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 assignment statement (=) • An assignment statement consists of an expression on the right- hand side and a variable to store the result x = 3.9 * x * ( 1 - x )
  • 26. 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.6 x 0.6 0.6 0.4 0.936 0.936 x
  • 27. 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.93 x 0.93
  • 28. 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
  • 29. 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 >>> print x 4 >>> y = 440 * 12 >>> print y 5280 >>> z = y / 1000 >>> print z 5 >>> j = 23 >>> k = j % 5 >>> print k 3 >>> print 4 ** 3 64 5 23 4 R 3 20 3
  • 30. 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
  • 31. 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
  • 32. 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.
  • 33. 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
  • 34. 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 >>> print 10 / 2 5 >>> print 9 / 2 4 >>> print 99 / 100 0 >>> print 10.0 / 2.0 5.0 >>> print 99.0 / 100.0 0.99 This changes in Python 3.0
  • 35. 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 >>> print 99 / 100 0 >>> print 99 / 100.0 0.99 >>> print 99.0 / 100 0.99 >>> print 1 + 2 * 3 / 4.0 - 5 -2.5 >>>
  • 36. 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) )
  • 37. 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]
  • 38. 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
  • 39. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Type Matters • 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'> >>>
  • 40. 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'> >>>
  • 41. 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() >>> print float(99) / 100 0.99 >>> i = 42 >>> type(i) <type 'int'> >>> f = float(i) >>> print f 42.0 >>> type(f) <type 'float'> >>> print 1 + 2 * float(3) / 4 - 5 -2.5 >>>
  • 42. 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 error if 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()
  • 43. 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 • The raw_input() function returns a string name = raw_input(‘Who are you?’) print 'Welcome ', name Who are you? Chuck Welcome Chuck
  • 44. 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
  • 45. 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
  • 46. 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!")
  • 47. 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()
  • 48. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H String Operations • 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
  • 49. 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
  • 50. 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?
  • 51. 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
  • 52. 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 (#)
  • 53. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Chapter Three
  • 54. 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 • {}
  • 55. 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
  • 56. 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 and x < 10 • is true only if x is greater than 0 and less than 10. • n%2 == 0 or n%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.
  • 57. 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 if x < 10: print 'Smaller‘ if x > 20: print 'Bigger' print 'Finish' x = 5 X < 10 ? print 'Smaller' X > 20 ? print 'Bigger' print 'Finish' Yes Yes
  • 58. 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'
  • 59. 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 to the 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
  • 60. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H increase / maintain after if or 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 i in 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
  • 61. 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' yes no X = 4 print 'Not bigger' print 'All Done'
  • 62. 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' yes no X = 4 print ‘Smaller' print 'All Done' x = 4 if x > 2 : print 'Bigger' else : print 'Smaller' print 'All done'
  • 63. 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’
  • 64. 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’
  • 65. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Chained Conditionals if x < 2 : print 'Small' elif x < 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
  • 66. 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'
  • 67. 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'
  • 68. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H The try / except Structure • You surround a dangerous section of code with try and except. • If the code in the try works - the except is skipped • If the code in the try fails - it jumps to the except section
  • 69. 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'
  • 70. 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
  • 71. 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
  • 72. 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
  • 73. 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
  • 74. 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
  • 75. 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
  • 76. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Chapter Four
  • 77. 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: def hello(): 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()
  • 78. 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)
  • 79. 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 def reserved word • We call/invoke the function by using the function name, parenthesis and arguments in an expression
  • 80. 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') >>> print big >>> ‘w’ A function is some stored code that we use. A function takes some input and produces an output. max() function “Hello world” (a string) ‘w’ (a string)
  • 81. 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() >>> print float(99) / 100 0.99 >>> i = 42 >>> type(i) <type 'int'> >>> f = float(i) >>> print f 42.0 >>> type(f) <type 'float'> >>> print 1 + 2 * float(3) / 4 - 5 -2.5 >>>
  • 82. 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 error if 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()
  • 83. 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 function using the def keyword followed by the function name, optional parameters in parenthesis, and then we add a colon. • We indent the body of the function • This defines the function but does not execute the body of the function def print_lyrics(): print "I'm a lumberjack, and I'm okay." print 'I sleep all night and I work all day.'
  • 84. 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' x = x + 2 print x Hello Yo 7 print "I'm a lumberjack, and I'm okay." print 'I sleep all night and I work all day.' print_lyrics():
  • 85. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Definitions and Uses • Once we have defined a function, we can call (or invoke) it as many times as we like • This is the store and reuse pattern
  • 86. 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 print x Hello Yo I'm a lumberjack, and I'm okay. I sleep all night and I work all day. 7
  • 87. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Arguments • An argument is a value we pass into the function as its input when we call the function • We use arguments so we can direct the function to do different kinds of work when we call it at different times • We put the arguments in parenthesis after the name of the function big = max('Hello world') Argument
  • 88. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Parameters • A parameter is a variable which we use in the function definition that is a “handle” that allows the code in the function to access the arguments for a particular function 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
  • 89. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Return Values • Often a function will take its arguments, do some computation and return a value to be used as the value of the function call in the calling expression. The return keyword is used for this. def greet(): return "Hello " print greet(), "Glenn" print greet(), "Sally" Hello Glenn Hello Sally
  • 90. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Return Value • A “fruitful” function is one that produces a result (or a return value) • The return statement ends the function execution and “sends back” the result of the function def greet(lang): if lang == 'es': return 'Hola ' elif lang == 'fr': return 'Bonjour ' else: return 'Hello ' print greet('en'),'Glenn' Hello Glenn print greet('es'),'Sally' Hola Sally print greet('fr'),'Michael' Bonjour Michael
  • 91. 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 for x in y: blah blah return ‘w’ ‘w’ Argument Parameter Result
  • 92. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Multiple Parameters / Arguments • We can define more than one parameter in the function definition • We simply add more arguments when we call the function • We match the number and order of arguments and parameters def addtwo(a, b): added = a + b return added x = addtwo(3, 5) print x 8
  • 93. 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"
  • 94. 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...
  • 95. 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]
  • 96. 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 import math radius = 2.0 area = math.pi * (radius ** 2) 12.5663706144 math.log(5) 1.6094379124341003 import sys sys.exit()
  • 97. 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
  • 98. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Chapter Five
  • 99. 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 print n
  • 100. 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'
  • 101. 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'
  • 102. 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 while True: 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!
  • 103. 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 while True: line = raw_input('> ') if line == 'done' : break print line print 'Done!'
  • 104. 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 print line print 'Done!'
  • 105. 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
  • 106. 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 list of 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 for construct • 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"
  • 107. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H A Simple Definite Loop for i in [5, 4, 3, 2, 1] : print i print 'Blastoff!' 5 4 3 2 1 Blastoff!
  • 108. 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'] for friend in friends : print 'Happy New Year: ', friend print 'Done!' Happy New Year: Joseph Happy New Year: Glenn Happy New Year: Sally Done!
  • 109. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H A Simple Definite Loop for i in [5, 4, 3, 2, 1] : print i print 'Blastoff!' 5 4 3 2 1 Blastoff! Definite loops (for loops) have explicit iteration variables that change each time through a loop. These iteration variables move through the sequence or set. Done? No print ‘Blast Off!' Yes print i Move i ahead
  • 110. 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]
  • 111. 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 for i in range(7, 0, -1) : print i print 'Blastoff!' 7 6 5 4 3 2 1 Blastoff!
  • 112. 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 • The block (body) of code is executed once for each value in the sequence • The iteration variable moves through all of the values in the sequence for i in [5, 4, 3, 2, 1] : print i Iteration variable Five-element sequence
  • 113. 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.
  • 114. 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' for thing in [9, 41, 12, 3, 74, 15] : print thing print 'After' Before 9 41 12 3 74 15 After
  • 115. 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 for thing in [9, 41, 12, 3, 74, 15] : zork = zork + 1 print zork, thing print 'After', zork Before 0 1 9 2 41 3 12 4 3 5 74 6 15 After 6 To count how 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.
  • 116. 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 for thing in [9, 41, 12, 3, 74, 15] : zork = zork + thing print zork, thing print 'After', zork Before 0 9 9 50 41 62 12 65 3 139 74 154 15 After 154 To add up a value we encounter in a loop, we introduce a sum variable that starts at 0 and we add the value to the sum each time through the loop.
  • 117. 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 0 0 1 9 9 2 50 41 3 62 12 4 65 3 5 139 74 6 154 15 After 6 154 25 An average just combines the counting and sum patterns and divides when the loop is done.
  • 118. 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 in the loop to catch / filter the values we are looking for.
  • 119. 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 value in [9, 41, 12, 3, 74, 15] : if value == 3 : found = True print found, value print 'After', found Before False False 9 False 41 False 12 True 3 True 74 True 15 After True If we just want to search and know if a value was found - we use a variable that starts at False and is set to True as soon as we find what we are looking for.
  • 120. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Finding the smallest value smallest = None print 'Before' for value in [9, 41, 12, 3, 74, 15] : If smallest is None : smallest = value elif value < smallest : smallest = value print smallest, value print 'After', smallest Before 9 9 9 41 9 12 3 3 3 74 3 15 After 3 We still have a variable that is the smallest so far. The first time through the loop smallest is None so we take the first value to be the smallest.
  • 121. 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' for value in [3, 41, 12, 9, 74, 15] : if smallest is None : smallest = value elif value < smallest : smallest = value print smallest, 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
  • 122. 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
  • 123. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Chapter Six
  • 124. 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 >>> print bob 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 >>> print x 124
  • 125. 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 strings and 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 converted from 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 >>> print x 90
  • 126. 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] >>> print letter a >>> n = 3 >>> w = fruit[n - 1] >>> print w n b a n a n a 0 1 2 3 4 5
  • 127. 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‘ >>> print zot[5] Traceback (most recent call last): File "<stdin>", line 1, in <module>IndexError: string index out of range >>>
  • 128. 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 len that 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
  • 129. 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) >>> print x 6 A function is some stored code that we use. A function takes some input and produces an output. len() function 'banana' (a string) 6 (a number)
  • 130. 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 len function, 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
  • 131. 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 for loop fruit = 'banana' for letter in fruit : print letter b a n a n a
  • 132. 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 for letter in word : if letter == 'a' : count = count + 1 print count
  • 133. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Looking Deeper into in • The iteration variable “iterates” though the sequence (ordered set) • The block (body) of code is executed once for each value in the sequence • The iteration variable moves through all of the values in the sequence for letter in 'banana’ : print letter Iteration variable Six-character string
  • 134. 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 for letter in 'banana' : print letter b a n a n a letter The iteration variable “iterates” though the string and the block (body) of code is executed once for each value in the sequence
  • 135. 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 5 6 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‘ >>> print s[0:4] Mont >>> print s[6:7] P >>> print s[6:20] Python
  • 136. 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 5 6 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‘ >>> print s[:2] Mo >>> print s[8:] thon >>> print s[:] Monty Python
  • 137. 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
  • 138. 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 modulus operator • 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
  • 139. 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 code String formatting operator format string
  • 140. 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) print s platinum is one of 5 shiny metals
  • 141. 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) %i Integer %f Float * Note: there are others, these are the most common ones.
  • 142. 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
  • 143. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Using in as an Operator • The in keyword 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 False and can be used in an if statement >>> fruit = 'banana‘ >>> 'n' in fruit True >>> 'm' in fruit False >>> 'nan' in fruit True >>> if 'a' in fruit : print 'Found it!‘ Found it!
  • 144. 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.‘ elif word > 'banana': print 'Your word,' + word + ', comes after banana.‘ else: print 'All right, bananas.' if word == 'banana': print ('All right, bananas.’)
  • 145. 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 functions which are in the string library • These functions are already built into every string - we invoke them by appending the function to the string variable • These functions do 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 >>> print greet Hello Bob >>> print 'Hi There'.lower() hi there >>>
  • 146. 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']
  • 147. 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()
  • 148. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H
  • 149. 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 occurance of the substring • If the substring is not found, find() returns -1 • Remember that string position starts at zero >>> fruit = 'banana' >>> pos = fruit.find('na') >>> print pos 2 >>> aa = fruit.find('z') >>> print aa -1 0 b 1 a 2 n 3 a 4 n 5 a
  • 150. 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() >>> print nnn HELLO BOB >>> www = greet.lower() >>> print www hello bob >>>
  • 151. 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 occurrences of the search string with the replacement string >>> greet = 'Hello Bob' >>> nstr = greet.replace('Bob','Jane') >>> print nstr Hello Jane >>> greet = 'Hello Bob' >>> nstr = greet.replace('o','X') >>> print nstr HellX BXb >>>
  • 152. 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' >>>
  • 153. 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
  • 154. 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 for and while • Concatenating strings with + • in as an operator • String comparison • String library (Searching and Replacing text, Stripping white space )
  • 155. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Chapter Seven
  • 156. 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
  • 157. 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
  • 158. 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')
  • 159. 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>
  • 160. 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: [Errno 2] No such file or directory: 'stuff.txt'
  • 161. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H The Newline Character • We use a special character to indicate when a line ends called the "newline" • We represent it as n in strings • Newline is still one character - not two >>> stuff = 'HellonWorld!' >>> print stuff Hello World! >>> stuff = 'XnY' >>> print stuff X Y >>> len(stuff) 3
  • 162. 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 stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 Return-Path: <postmaster@collab.sakaiproject.org> Date: Sat, 5 Jan 2008 09:12:18 -0500To: source@collab.sakaiproject.orgFrom: stephen.marquard@uct.ac.zaSubject: [sakai] svn commit: r39772 - content/branches/Details: http://source.sakaiproject.org/viewsvn/?view=rev&rev=39772
  • 163. 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 newlines at the end of each line From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008n Return-Path: <postmaster@collab.sakaiproject.org>n Date: Sat, 5 Jan 2008 09:12:18 -0500nTo: source@collab.sakaiproject.orgnFrom: stephen.marquard@uct.ac.zanSubject: [sakai] svn commit: r39772 - content/branches/nDetails: http://source.sakaiproject.org/viewsvn/?view=rev&rev=39772n
  • 164. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H File Handle as a Sequence • A file handle open for read can be treated as a sequence of strings where each line in the file is a string in the sequence • We can use the for statement to iterate through a sequence • Remember - a sequence is an ordered set xfile = open('mbox.txt') for cheese in xfile: print cheese
  • 165. 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 file read-only • Use a for loop to read each line • Count the lines and print out the number of lines fhand = open('mbox.txt') count = 0 for line in fhand: count = count + 1 print 'Line Count:', count Line Count: 132045
  • 166. 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 read the whole file (newlines and all) into a single string. >>> fhand = open('mbox-short.txt') >>> inp = fhand.read() >>> print len(inp) 94626 >>> print inp[:20] From stephen.marquar
  • 167. 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 if statement in our for loop to only print lines that meet some criteria fhand = open('mbox-short.txt') for line in fhand: if line.startswith('From:') : print (line)
  • 168. 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: stephen.marquard@uct.ac.za From: louis@media.berkeley.edu From: zqian@umich.edu From: rjlowe@iupui.edu...
  • 169. 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 print statement adds a newline to each line. Each line from the file also has a newline at the end. From: stephen.marquard@uct.ac.zann From: louis@media.berkeley.edunn From: zqian@umich.edunn From: rjlowe@iupui.edun
  • 170. 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') for line in fhand: line = line.rstrip() if line.startswith('From:') : print line
  • 171. 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 continue statement fhand = open('mbox-short.txt') for line in fhand: line = line.rstrip() # Skip 'uninteresting lines' if not line.startswith('From:') : continue print line # Process our 'interesting' line
  • 172. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Using in to select Lines • We can look for a string anywhere in a line as our selection criteria fhand = open('mbox-short.txt') for line in fhand: line = line.rstrip() if not '@uct.ac.za' in line : continue print line
  • 173. 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 for line in fhand: 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
  • 174. 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 for line in fhand: if line.startswith('Subject:') : count = count + 1 print 'There were', count, 'subject lines in', fname Enter the file name: na na boo boo File cannot be opened: na na boo boo
  • 175. 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
  • 176. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Chapter Eight
  • 177. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H A List is a kind of Collection • A collection allows us to put many values in a single “variable” • A collection is nice because we can carry many values around in one convenient package. friends = [ 'Joseph', 'Glenn', 'Sally' ] carryon = [ 'socks', 'shirt', 'perfume' ]
  • 178. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H What is not a “Collection” • Most of our variables have 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 >>> print x 4
  • 179. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H List Constants • List constants are surrounded by square brackets and the elements in the list are separated by commas. • A list element can be any Python object - even another list • A list can 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 [] []
  • 180. 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 for i in [5, 4, 3, 2, 1] : print i print 'Blastoff!' 5 4 3 2 1 Blastoff!
  • 181. 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'] for friend in friends : print 'Happy New Year: ', friend print 'Done!' Happy New Year: Joseph Happy New Year: Glenn Happy New Year: Sally Done!
  • 182. 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 in square brackets 0 Joseph 1 Glenn 2 Sally >>> friends = [ 'Joseph', 'Glenn', 'Sally' ] >>> print friends[1] Glenn
  • 183. 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 cannot change the contents of a string - we must make a new string to make any change • Lists are "mutable" - we can change an element of a list using the index operator >>> fruit = 'Banana' >>> fruit[0] = 'b' Traceback TypeError: 'str' object does not support item assignment >>> x = fruit.lower() >>> print x banana >>> lotto = [2, 14, 26, 41, 63] >>> print lotto [2, 14, 26, 41, 63] >>> lotto[2] = 28 >>> print lotto [2, 14, 28, 41, 63]
  • 184. 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 list as a parameter and returns the number of elements in the list • Actually len() tells us the number of elements of any set or sequence (i.e., such as a string...) >>> greet = 'Hello Bob' >>> print len(greet) 9 >>> x = [ 1, 2, 'joe', 99] >>> print len(x) 4
  • 185. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Using the range function • The range function returns a list of numbers that range from zero to one less than the parameter >>> print range(4) [0, 1, 2, 3]
  • 186. 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'] for i in range(len(friends)) : friend = friends[i] print 'Happy New Year: ', friend Happy New Year: Joseph Happy New Year: Glenn Happy New Year: Sally
  • 187. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Concatenating lists 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]
  • 188. 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]
  • 189. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Lists can be sliced using : 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]
  • 190. 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
  • 191. 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 list and then add elements using the append method • 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']
  • 192. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Is Something in a List? • Python provides two operators that let you check if an item is in a list • These are logical operators that return True or False • They do not modify the list >>> some = [1, 9, 21, 10, 16] >>> 9 in some True >>> 15 in some False >>> 20 not in some True
  • 193. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H A List is an Ordered Sequence • A list can hold many items and keeps those items in the order until we do something to change the order • A list can be sorted (i.e., we can change its order) >>> friends = [ 'Joseph', 'Glenn', 'Sally' ] >>> friends.sort() >>> print friends ['Glenn', 'Joseph', 'Sally'] >>> print friends[1] Joseph
  • 194. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Built in Functions and Lists • There are a number of functions built into Python that take lists as 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
  • 195. 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() >>> print stuff ['With', 'three', 'words'] >>> print len(stuff) 3 >>> print stuff[0] With Split breaks a string into parts produces a list of strings. We think of these as words. We can access a particular word.
  • 196. 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() >>> print etc ['A', 'lot', 'of', 'spaces'] >>> line = 'first;second;third' >>> thing = line.split() >>> print thing ['first;second;third'] >>> print len(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.
  • 197. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 fhand = open('mbox-short.txt') for line in fhand: line = line.rstrip() if not line.startswith('From ') : continue words = line.split() print words[2] Sat Fri Fri Fri ...
  • 198. 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 stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 stephen.marquard@uct.ac.za ['stephen.marquard', 'uct.ac.za'] 'uct.ac.za' words = line.split() email = words[1] pieces = email.split('@') print pieces[1]
  • 199. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Mystery Problem... From stephen.marquard@uct.ac.za Sat Jan5 09:14:16 2008 fhand = open('mbox-short.txt') for line in fhand: 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
  • 200. 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
  • 201. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Chapter Nine
  • 202. 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
  • 203. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H What is not a “Collection” • Most of our variables have one value in them - when we put a new value in the variable - the old value is over written >>> x = 2 >>> x = 4 >>> print x 4
  • 204. 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
  • 205. 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
  • 206. 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#
  • 207. 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() >>> print purse {} >>> purse['money'] = 12 >>> purse['candy'] = 3 >>> purse['tissues'] = 75 >>> print purse {'money': 12, 'tissues': 75, 'candy': 3} >>> print purse['candy'] 3 >>> purse['candy'] = purse['candy'] + 2 >>> print purse {'money': 12, 'tissues': 75, 'candy': 5}
  • 208. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Comparing Lists and Dictionaries • Dictionaries are like Lists except that they use keys instead of numbers to look up values >>> lst = list() >>> lst.append(21) >>> lst.append(183) >>> print lst [21, 183] >>> lst[0] = 23 >>> print lst [23, 183] >>> ddd = dict() >>> ddd['age'] = 21 >>> ddd['course'] = 182 >>> print ddd {'course': 182, 'age': 21} >>> ddd['age'] = 23 >>> print ddd {'course': 182, 'age': 23}
  • 209. 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 : value pairs • You can make an empty dictionary using empty curly braces >>> j = { 'chuck' : 1 , 'fred' : 42, 'jan': 100} >>> print j {'jan': 100, 'chuck': 1, 'fred': 42} >>> o = { } >>> print o {}
  • 210. 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 error to reference a key which is not in the dictionary • We can use the in operator to see if a key is in the dictionary >>> c = dict() >>> print c['csev'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'csev' >>> print 'csev' in c False
  • 211. 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 dictionary under that name counts = dict() names = ['csev', 'cwen', 'csev', 'zqian', 'cwen'] for name in names : if name not in counts: counts[name] = 1 else : counts[name] = counts[name] + 1 print counts {'csev': 2, 'zqian': 1, 'cwen': 2}
  • 212. 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 key is already in a dictionary and assuming a default value if the key is not there is so common, that there is a method called get() that does this for us if name in counts: print counts[name] else : print 0 Default value if key does not exist (and no Traceback). {'csev': 2, 'zqian': 1, 'cwen': 2} print counts.get(name, 0)
  • 213. 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 zero when the key is not yet in the dictionary - and then just add one counts = dict() names = ['csev', 'cwen', 'csev', 'zqian', 'cwen'] for name in names : counts[name] = counts.get(name, 0) + 1 print counts Default {'csev': 2, 'zqian': 1, 'cwen': 2}
  • 214. 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 split the line into words, then loop through the words and use a dictionary to 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...' for word in words: counts[word] = counts.get(word,0) + 1 print 'Counts', counts
  • 215. 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: the clown ran after the car and the car ran into the tent and the tent fell down on the clown and the car 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}
  • 216. 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} >>> for key in counts: print key, counts[key] jan 100 chuck 1 fred 42 >>>
  • 217. 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, values or items (both) from a dictionary >>> jjj = { 'chuck' : 1 , 'fred' : 42, 'jan': 100} >>> print list(jjj) ['jan', 'chuck', 'fred'] >>> print jjj.keys() ['jan', 'chuck', 'fred'] >>> print jjj.values() [100, 1, 42] >>> print jjj.items() [('jan', 100), ('chuck', 1), ('fred', 42)] >>> What is a 'tuple'? - coming soon...
  • 218. 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 key and the second variable is the corresponding value for the key >>> jjj = { 'chuck' : 1 , 'fred' : 42, 'jan': 100} >>> for aaa,bbb in jjj.items() : print aaa, bbb jan 100 chuck 1 fred 42 >>>
  • 219. 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
  • 220. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Chapter Ten
  • 221. 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') >>> print x[2] Joseph >>> y = ( 1, 9, 2 ) >>> print y (1, 9, 2) >>> print max(y) 9 >>> for iter in y: print iter, >>> 1 9 2
  • 222. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H ..but.. Tuples are "immutable" • Unlike a list, once you create a tuple, you cannot alter its contents - similar to a string >>> x = [9, 8, 7] >>> x[2] = 6 >>> print x [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 >>>
  • 223. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Things not to 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' >>>
  • 224. 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']
  • 225. 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.
  • 226. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Tuples and Assignment • We can also put a tuple on the left-hand side of an assignment statement • We can even omit the parenthesis >>> (x, y) = (4, 'fred') >>> print y fred >>> (a, b) = (99, 98) >>> print a 99
  • 227. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Tuples and Dictionaries • The items() method in dictionaries returns a list of (key, value) tuples >>> d = dict() >>> d['csev'] = 2 >>> d['cwen'] = 4 >>> for (k,v) in d.items(): print k, v csev 2 cwen 4 >>> tups = d.items() >>> print tups [('csev', 2), ('cwen', 4)]
  • 228. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Tuples are Comparable • The comparison operators work with tuples and 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
  • 229. 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 tuples to 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)]
  • 230. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Using sorted() 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)] >>> for k, v in sorted(d.items()): print k, v, a 10 b 1 c 22
  • 231. Ghulam Mustafa Shoro U N I V E R S I T Y O F S I N D H Sort by values instead of key • If we could construct a list of tuples of the form (value, key) we could sort by value • We do this with a for loop that creates a list of tuples >>> c = {'a':10, 'b':1, 'c':22} >>> tmp = list() >>> for k, v in 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')]
  • 232. 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() for line in fhand: words = line.split() for word in words: counts[word] = counts.get(word, 0 ) + 1 lst = list() for key, val in counts.items(): lst.append( (val, key) ) lst.sort(reverse=True) for val, key in lst[:10] : print key, val The top 10 most common words.
  • 233. 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
  • 234. ANY QUESTIONS? GHULAM MUSTAFA SHORO 0332 - 3216699 YOU CAN FIND ME AT: gm.shoro@usindh.edu.pk