Professional Documents
Culture Documents
1
PART 1
Python overview
WHAT IS PYTHON?
Python is a
high level,
object-oriented,
interpreted,
3
KEY FEATURES
4
ABOUT PYTHON
Name after ‘Monty Python’, a comedy group, depicting its ‘fun’ philosophy
5
USERS OF PYTHON
6
TRADITIONAL USES OF PYTHON
Embedded Scripting
Image processing
Artificial intelligence
GUI’s
Database Programming
Internet Scripting
System Administration
Automation
7
PYTHON 2 OR PYTHON 3?
Library support is more for Python 2.7 as it has been around longer
8
HOW TO GET PYTHON?
python --version
Python 3.5.2
9
PYTHON DOWNLOAD AND INSTALLATION
Latest is recommended
10
USING PYTHON
11
COMMENTS , LITERALS, VARIABLES
12
PYTHON IDENTIFIERS
13
OPERATIONS ON NUMBERS
Logical Operators
All 6 comparison operations are available(==, !=, <, <=, >, >=)
To combine logical expressions, use : and not or
14
PRECEDENCE
15
STRINGS - BASICS
.capitalize()
python -> Python
17
DEMONSTRATION
18
INDENTATION & BLOCKS
Indentation
Leading whitespace to shift some line starts to the right of others
Is used to determine grouping of statement in Python
Defines a ‘statement block’
Blocks
Start with a statement ending with ‘:’
All lines following it are indented forward
De-indenting to the previous level closes the block
Some editors, IDE’s automatically take care of indentation
Repeat: there are no curly braces { } in python for defining blocks
19
BASIC CONSTRUCTS
Conditions
if condition: statement
if condition: block
else
elif
Loops
for
while
break
continue
20
CONSTRUCTS : CONDITIONALS
if b<a :
print(“less”)
print(“value of a is “,a)
print(“value of b is “,b)
21
CONSTRUCTS : CONDITIONALS
if b<a :
print(“less”)
print(“value of a is “,a)
print(“value of b is “,b)
else:
22
CONSTRUCTS : CONDITIONALS
if a<10:
print(“hello”)
elif a<5:
print(“world”)
23
CONSTRUCTS : CONDITIONALS
if
elif
else
24
CONSTRUCTS : ITERATIONS
while <condition>:
block
All the statements of the block are executed if the condition is true
25
CONSTRUCTS : ITERATIONS
a=0
while a<10:
print(a)
a=a+1
26
CONSTRUCTS : ITERATIONS
block
The for loop iterates over an iterable, assigning subsequence elements of the sequence to the variable and then
executing the block
ctr=0
if x == “o” : ctr=ctr+1
print(ctr)
27
CONSTRUCTS : ITERATIONS
for x in range(10):
print(x)
28
CONSTRUCTS : ITERATIONS
range(10) # generates 0 to 9
# 3, 5 , 7 , 9
29
USE OF BREAK, CONTINUE, PASS
30
USE OF BREAK, CONTINUE, PASS
if letter == 'h':
break
31
USE OF BREAK, CONTINUE, PASS
if letter == 'h':
continue
32
USE OF BREAK, CONTINUE, PASS
pass statement in Python is used when a statement is required syntactically but you do not want
any command or code to execute.
if letter == 'h':
pass
33
TAKING INPUT FROM THE KEYBOARD
x=input()
x=input(“Enter a value”)
x=input(“Enter a value”)
or
34
GETTING DOWN TO PROGRAMMING
35
RUNNING A PYTHON SCRIPT
36
LAB EXERCISES
37
ASSIGNMENT
38
PART 2
Python Data Types
OBJECTIVES
40
NUMBERS
Operators and functions for numbers will work on all the above
41
NUMBERS : ASSIGNMENTS
a=10
a=b=c=20
42
NUMBERS : OPERATORS
+ - * /
43
NUMBERS : FUNCTIONS
a=int(5.3) # results in 5
a=int(“23”) # results in 23
# by default base is 10
44
NUMBERS : FUNCTIONS
45
NUMBERS : FUNCTIONS
46
NUMBERS : FUNCTIONS
q,r=divmod(5,3)
q becomes 1
r becomes 2
Functions in python can return multiple values in form of a sequence and the returned values
can be captured as above. The same can be implemented in user defined functions as well.
47
NUMBERS : FUNCTIONS
a=round(4.33) # returns 4
a=round(3.5) # returns 4
48
STRINGS
49
STRINGS : OPERATORS
if “e” in “hello”:
print(“found”)
for ch in “hello”:
print(ch)
50
STRINGS : FUNCTIONS
51
STRINGS : METHODS
s=“hello world”
Note: The string methods would return a new string rather than modifying the current one
52
STRINGS : METHODS
s.startswith(“he”)
s.endswith(“run”)
53
SEQUENCES
not in
54
SEQUENCES - EXAMPLE
s=“Hello”
55
SEQUENCES
56
SLICES IN DETAIL
b=a[2:7:2] # slice is a[2], a[4], a[6] the index gap is 2 for elements
a[start,end,stride]
slice starts from the index start, does not include the index end, and stride is the gap after which the
elements are selected. By default stride is 1
57
SLICES IN DETAIL
s=‘ABCDEF’
58
SLICES IN DETAIL
s=‘ABCDEF’
print(s[-1:0:-1])
59
SLICES IN DETAIL
s=‘ABCDEF’
60
TUPLES
a=10,20,30,40
a=(10,20,30,40)
a[0] is 10
We can use slicing and use ‘in’ to check for existence or iterate a tuple
61
TUPLES
a=(10,20,30,40)
b=(15,16)
c=a+b
print(c)
(10,20,30,40,15,16)
62
SETS
a={ 10,20,30,40 }
b={ 20,50,60 }
63
SET OPERATIONS
a={ 10,20,30,40 }
b={ 20,50,60 }
-- DEMONSTRATION
64
LISTS
a[0] # gives us 10
65
LISTS OPERATIONS
A[1] # Gives 20
A[2][1] # Gives 3
A[2:4] # Slicing
66
LISTS OPERATIONS
67
LISTS OPERATIONS
del A[x:y] # deletes a slice from the List and shifts accordingly
68
LISTS BUILDING BY COMPREHENSION
69
LISTS & STRINGS
s=“Hello”
a=list(s) # a=[‘H’,’e’,’l’,’l’,’o’]
# b=“H-e-l-l-o”
70
DICTIONARIES
Heterogeneous
Can be nested
Modifiable in place
71
DICTIONARY OPERATIONS
72
DICTIONARY OPERATIONS
73
DICTIONARY OPERATIONS
This dictionary is representing multiple records of student marks, with key as their name
74
DICTIONARY OPERATIONS
75
DICTIONARY OPERATIONS
76
DICTIONARY OPERATIONS
77
DICTIONARY & LISTS
A list is also a heterogeneous collection, so it can also contain any python type elements.
78
DICTIONARY & LISTS
79
LAB EXERCISES
Input a sentence and input a word. We have to find out how many times the word occurred in
the sentence.
Display all the words that are contained in a sentence. Words that come multiple times should
be displayed only once.
We wish to display only those words from the sentence that do not occur in a set of excluded
words ( like : this, and, is, not etc. ). The set of excuded words would be maintained in your
code, and the sentence is input from the keyboard. We have to display all words that do not
exist in this set, and we have to take care that multiple occurring words are displayed only
once.
From an input sentence, build a dictionary of words along with their frequency. Display the
words in sorted order along with their count.
80
ASSIGNMENT
Get a list of words with their count in a sentence. The words should be in sorted order
alphabetically. Words should not be repeated. Assume space as a separator for words.
81
PART 3
Python Modular Programming (user defined functions (UDF))
USER DEFINED FUNCTIONS
# main program
print(“Hello world”)
print(“End of my program”)
83
UDF : RETURNING VALUES
# main program
print(“Hello world”)
x=displayLine( ) # the function call returns 20 into x
print(“End of my program”)
84
UDF : RETURNING MULTIPLE VALUES
# main program
print(“Hello world”)
x , y=displayLine( ) # returns 20 into x and 30 into y
print(“End of my program”)
85
UDF : PASSING PARAMETERS
# main program
print(“Hello world”)
y=10
x=greater( 10 , y ) # 10 is first parameter and y the second one
86
UDF : PARAMETERS AND RETURN VALUES
87
UDF : VARIABLE SCOPE
88
LAB EXERCISES
Make a function that inputs a string and a word, and returns the number of times the word
occurred in the string.
f=factorial(5)
89
ASSIGNMENT
90
PART 4
Files and Lambda/Map/Zip/Filter
OBJECTIVES
File operations
92
FILES
93
FILES
Text files are usual files that we can open and read in a text editor
Binary files contain bytes structured into records as per the application
94
FILES
r+ rb+ : Open in read mode, and we can also update the contents
Note: After some content has been read from a file, any write command would update content at
the place where the file reference is at that point in time. So to update an information that has
been read, we may have to reposition the file reference location so that the update happens at
the correct location.
95
FILES
96
FILES
fo.seek(offset,0) # same
97
FILES - DEMO
Problem :
Read a text file and convert it to upper case and write to a second file.
98
ZIP
99
ZIP
L1=[1,2,3]
L2=[5,6,7]
print(x)
100
ZIP
101
ZIP
nList=[“Anurag”,”Deepti”,”Jack”,”Hina”]
102
MAP()
Results an iterable
Function should take same number of arguments as the number of input iterable(s)
103
MAP()
def sum(a,b):
return a+b
L1=[1,2,3]
L2=[5,6,7]
print(L)
104
MAP()
105
FILTER ( )
Returns an iterable
106
FILTER ( )
def even(a):
L1=[1,2,3,8,6,11,7]
107
LAMBDA ( )
108
LAMBDA ( )
lambda x : x * 5
( lambda x : x * 5 ) ( 7 )
109
LAMBDA ( )
square=lambda x : x * x
cube=lambda x : x * x * x
110
LAMBDA ( )
For instance we wanted to create a list by comprehension, that contains the sum of corresponding
elements of two lists
111
LAMBDA ( )
def sum(a,b):
return a+b
L1=[1,2,3]
L2=[5,6,7]
print(L)
112
LAMBDA ( )
We could compact our code by replacing the map function with a lambda, thus eliminating the need of
the sum function
L1=[1,2,3]
L2=[5,6,7]
print( L )
113
LAMBDA ( ) - EXERCISE
def even(a):
L1=[1,2,3,8,6,11,7]
print(L)
114
LAB EXERCISES
c) Filter the contents of the file based on a condition without having an interim list ( all values
>25 )
115
LAB EXERCISES
Consider a CSV file made through excel, containing student data such as rollno, name, gender and marks obtained such
as:
R010,Anurag,M,78
R012,Disha,F,67
R013,Gurvinder,M,72
Load this information into appropriate data structure so that we can query on a roll no and retrieve the name, gender or
marks.
Further write a function to get a list of names who have obtained higher than certain marks.
L=getHigherThan(60)
116
LAB EXERCISES
Now we have to build a dictionary of words along with their frequencies as they occur in the
article.txt after we have excluded the ignore words.
The final result should be sorted word list which do not occur in the ignore word list. And we wish to
get their frequency and density. Density is (frequency/total words) * 100
117
OBJECTIVES
Goals
Principles
Constructors, Destructors
Operator Overloading
118
PART 5
Object Oriented Programming
GOALS
Robustness
Adaptability
Reusability
120
PRINCIPLES
Modularity
Abstraction
Encapsulation
121
OBJECT ORIENTED BASICS
class – Is a template
122
CLASS
class simplest:
123
CLASS AS A NAMESPACE
class simplest:
124
CLASS AS A NAMESPACE - DEMO
class point:
pass
p=point()
125
CONSTRUCTOR
126
CONSTRUCTOR
class point:
self.x=a
self.y=b
print(p.x,p.y)
127
METHODS OF A CLASS
128
GIVING DEFAULT VALUES
class point:
self.x=a
self.y=b
p=point( )
129
ADDING A METHOD
class point:
self.x=a
self.y=b
130
OUR CLASS USAGE
131
DESTRUCTOR FUNCTION
def __del__(self):
The destructor function of a class is automatically called when an instantiated object of that class is
deleted from memory by a del statement or due to end of scope region
132
OPERATOR OVERLOADING
133
OPERATOR OVERLOADING
p+x
For object p, the __add__ method is called and value of x is sent as parameter, similar to saying :
p.__add__(x)
134
OPERATOR OVERLOADING
q=p+x
q= p.__add__(x)
Hence the __add__( ) method should return an appropriate value as is required by your application
on the LHS
135
METHODS RELATED TO +
__add__ # p+x
Where p is the object for whom the above functions are called.
136
METHODS RELATED TO -
__sub__
137
OVERLOADING LOGICAL OPERATORS
if p < q :
So whatever is the result of the function that will be used for the condition.
138
OVERLOADING LOGICAL OPERATORS
__eq__ , __ ne__
139
DOCUMENTING CLASSES
If a string is the very first line of a class, then it populates an attribute __doc__
140
DOCUMENTING CLASSES
class test:
def __init__(self):
print(test.__doc__)
141
LAB QUESTIONS
142
LAB QUESTIONS
2) In the class created in question 1, add a function getWC() to get the count of some words which
can be provided through a list sent as parameter. The usage of this function would be as
follows:
143
LAB QUESTIONS
144
ASSIGNMENT
import math
math.sqrt ( math.pow((x2-x1),2) + math.pow ((y2-y1),2) )
145
THANK YOU
146