3. What is Python ?
⢠Created by Guido Van Rossum in 1989
⢠Named after Montyâs Flying Circus
⢠Multi-purpose (Web, GUI, Scripting, etc.)
⢠Object Oriented
⢠Interpreted
⢠Strongly typed and Dynamically typed
⢠Focus on readability and productivity
4. Imp. Features of Python
⢠Everything is an Object
⢠Interactive Shell
⢠Strong Introspection
⢠Cross Platform
⢠CPython, Jython, IronPython, PyPy
5. Who Uses Python
⢠Python is a general purpose programming language,
almost anyone can use Python
Some of the common (but not limited to) uses of Python :-
⢠Data Scientists - probably the largest portion of python community
⢠Game Developers - ( pygame, renâpy âŚ)
⢠Educators - since it is readable and easy to learn
⢠Network Admins/Systems Administrators/Security Testers - makes a good
alternative to bash scripting.
⢠Web Developers - django, flask, etcâŚ
⢠IOT Developers - Raspberry PI, serial communication
6. Pythonâs Technical Strengths?
⢠Has a Good Standard Library
⢠Easy to Learn - What attracts everyone
⢠Multi-paradigm - OOP, imperative, procedural, and some parts of
functional programming
⢠The large and active community - this makes a lot of libraries
available. From useful packages to c++ library bindings.
7. Pythonâs Technical Strengths?
⢠Python syntax is easy to learn.
⢠Itâs more readable, as the syntax is simple.
⢠It supports object oriented programming which is itâs biggest
strengths.
⢠Python is both free and open-source.
⢠Python runs on all major operating systems like Microsoft Windows,
Linux, and Mac OS X.
⢠Python doesn't have pointers like other C-based languages, making it
much more reliable.
8. Some World-Class Software Companies That Use Python
⢠Industrial Light and Magic.
⢠Google.
⢠Facebook.
⢠Instagram.
⢠NASA
⢠Youtube
⢠Spotify.
⢠Quora.
⢠Netflix.
⢠Dropbox.
⢠BitTorrent
⢠And many moreâŚâŚâŚ.
9. Releases :-
⢠Created in 1989 by Guido Van Rossum
⢠Python 1.0 released in 1994
⢠Python 2.0 released in 2000
⢠Python 3.0 released in 2008
⢠Python 2.7 is the recommended version
⢠3.0 adoption has taken place
⢠3.6 and 3.7 are the current versions being adoptedâŚ..
10. 4 Major Versions of Python
⢠âPythonâ or âCPythonâ is written in C/C++
- Version 2.7 came out in mid-2010
- Version 3.1.2 came out in early 2010
⢠âJythonâ is written in Java for the JVM
⢠âIronPythonâ is written in C# for the .Net environment
11. Python Experts View
⢠Simple and Easy to Learn
⢠Free and Open Source
⢠High Level Language
⢠Python is Portable
⢠Supports Different Programming Paradigm
- 4 different types of Programming Paradigm used in Python
- Object Oriented Approach
- You can create Objects and Classes in Python
- Procedure Oreinted
- Step by Step execution
- Can group your code in a function
- Functional Approach
- Allows to perform Parallel Processing
- Imperative Oriented
- Mostly used for Data Manipulation of Data Structures
12. Installing Python
⢠www.python.org
⢠Download Python 3.7
⢠After Downloading you have three options to use Python
⢠Python CLI
⢠Text Editor
⢠Python IDE
14. Python Variables and their Data Types
⢠Name="Ganesh"
⢠print (Name)
⢠salary=2987.54
⢠print (salary)
⢠#Assignments of Variables
⢠a=10
⢠b=10
⢠c=10
⢠print (a,b,c)
15. Python Variables and their Data Types
⢠#Multiple Assignments1
⢠a=b=c=10
⢠print (a,b,c)
⢠print (a+b+c)
⢠# Mutiple Assignments2
⢠x,y,z=10,20,30
⢠print (x,z)
⢠print (x+z)
16. Python Tokens
⢠Python Token is a basic component of source code
⢠Keywords/Identifiers/Literals/ Operators
⢠Keywords
⢠Special Reserve Words
⢠Convey a special meaning to compiler/Interpretor
⢠Cannot be used as variables
⢠Ex :- if / while / for /class /continue / break / else etc
⢠Identifiers
⢠Name used to identify a variable
⢠Ex : num = 10 (num is a identifier)
⢠Rules for identifiers : only _ used as special character to name an identifier
keywords cannot be used as name of identifiers
Python is case-sensitive (Name is diff. from name)
Identifier can start only with with character or _
17. Python Tokens
⢠Literals
⢠Constants(data) given / used for variables
⢠4 types
string
- name=âGaneshâ
name= âGaneshâ
name=âââMy Name
is ganesh
and I stay in puneâââ
Numeric
int/long/float/complex
Boolean
- have just 2 values : True / False
Special
- Special Literal is None
- Used to specify to the field that is not created
- equivalent of null in âcâ is None in Python
20. Python Operators
⢠Comparison Operators : Used to compare 2 values and returns true
or false
<
>
!=
==
Ex : print (11>10)
print (2==2)
print(10>11)
print(11>11)
print (2!=3)
21. Python Operators
⢠Logical Operators
and
or
not
⢠Ex 1. print (20> 2 and 10 > 3)
2. print (20>21 or 10 >3)
3. a= not 7>8
print (a)
22. Python Operators
⢠Bitwise Operators : Used to perform Bitwise Calculations
&
>> - right shift
<< - left shift
~
|
⢠Pipe Symbol (|)
⢠Ex 1. print (7|5) â 7
2. print (7|8) â 15
3. print (4|6) - ?
23. Bitwise Operators
& operator
EX 1. print (7&5) - 5
print (9&8) - ?
>> Right Shift
Ex 1. print (10>>2) â 2
print (13>>3) - 1
<< Left Shift
Ex 1. print (15 <<2) - 120
print (8<<2) â 32
24. ⢠Identity Operators
- Test if two operands share an identity
Two identity Operators â is , is not
Ex : n=10
print(n is 10) - true
print( n is not 10) - false
25. ⢠Membership Operator : Test whether a value is member of a
sequence or not
Sequence may be a list or tuple or string
Two Operators : in , not in
Ex : animals=["dog","cat","fox","elephant"]
val=("goat" not in animals)
print (val)
val=("goat" in animals)
print (val)
26. Data Types in Python
⢠Two Data Types
- mutable
- immutable
- Mutable datatypes can be changed
- Immutable datatypes cannot be changed or modified
Mutable â Lists / Dictionaries / sets
Immutable â Numbers / Strings / Tuples
27. Numbers :
⢠Python automatically converts a number from one type to another if needs
⢠Functions like int() , long(), float(), complex() to change datatypes
⢠Ex :
message="Hello"
print (type(message)) - class string
no1=100
fl1=123.45
print (type(no1)) - class int
print (type(fl1)) - class float
28. String :
⢠Aything defined in single or double quotes is string
⢠Ex :
str1="Ganesh Bhosale"
print (str1)
print (str1[1])
Print Substring :
print(str1[4:9])
29. String :
⢠Python Uses Special syntax to format multiple strings and numbers
Ex :
Print ( âThe item {} is used {} timesâ.format(n1,n2))
-- {} are placeholders which are substituted with n1 and n2
Ex :
str1=âHelloâ
cnt=5
print(âThe String %s appears %i timesâ%(str1,cnt))
31. String Functions
⢠count()
word="Welcome to Python Programming"
cnt=word.count("o")
print(cnt)
⢠word.upper() - converts into uppercase
⢠max(word) â gives max ascii value
⢠min(word) - gives min ascii value
32. Python Lists
⢠The most basic data structure in Python is the sequence.
⢠Each element of a sequence is assigned a number â
⢠its position or index.
⢠The first index is zero, the second index is one, and so forth.
⢠Python has six built-in types of sequences, but the most common
ones are lists and tuples
⢠There are certain things you can do with all sequence types.
⢠These operations include indexing, slicing, adding, multiplying,
and checking for membership.
⢠In addition, Python has built-in functions for finding the length
of a sequence and for finding its largest and smallest elements.
33. Python Lists
⢠This list is a most versatile datatype available in Python which
can be written as a list of comma-separated values (items)
between square brackets.
⢠The items in a list need not be of the same type
⢠Creating a list is as simple as putting different comma-separated
values between square brackets.
Ex:
sub_list=[âMathsâ,âPhysicsâ,âChemistryâ,âEnglishâ]
num_list=[1,2,33,55,65]
mix_list=[âGaneshâ,48,âNileshâ,27]
34. Python Lists
Accessing Lists
⢠print(sub_list[0])
⢠print(num_list[2])
⢠print (mix_list[1])
Updating Lists
sub_list[2]=100;
print(sub_list)
Delete List Elements
del sub_list[2]
print (sub_list)
35. Basic List Operations
⢠length
⢠Concatenation
⢠Repetition
⢠Membership
⢠Iteration
Indexing / Slicing / Matrices on list :
print (sub_list[2])
print (sub_list[2:5]
37. Built-in Functions on list
⢠append()
- appends object at end of the list
list1=[âganeshâ,â123â,ânew2008â]
print (list1)
list1.append(â2018â)
print (list1)
list1.insert(2,âHelloâ) --- insertion of element in list
Print list2
⢠count()
- counts no of times object occurs in the list
list1=[âganeshâ,â123â,ânew2008â,â123â]
print (list1.count(â123â))
38. Built-in Functions on list
⢠extend()
- appends the contents of seq to list
list1=[âganeshâ,â123â,ânew2008â]
list2=[â3333â,âttttttâ]
list1.extend(list2)
print (list1)
40. Tuples
⢠The empty tuple is written as two parentheses containing nothing
Tup1 = ()
Tup1=(50,) â write a tuple
⢠Like string indices, tuple indices start at 0, and they can be sliced,
concatenated, and so on.
41. Tuples
⢠A tuple is a sequence of immutable Python objects.
⢠Tuples are sequences, just like lists.
⢠The differences between tuples and lists are, the tuples cannot be
changed unlike lists and tuples use parentheses, whereas lists use
square brackets.
⢠Creating a tuple is as simple as putting different comma-separated
values.
Ex :
Tuple1=("Sunday","Monday","Tuesday")
print (Tuple1)
Tuple2=(1,2,3,4,5,6)
print (Tuple2)
Tuple3="a","b","c","d"
print (Tuple3)
42. Accessing Values in Tuples
⢠Tuple1=("Sunday","Monday","Tuesday")
Print Tuple1[0] - Access the first Element
43. Updating Tuples
⢠Tuples are immutable which means you cannot update or change
the values of tuple elements.
⢠You are able to take portions of existing tuples to create new
tuples as the following â
t1=(22,55.78)
print (t1)
t2=(âGaneshâ,âBhosaleâ)
print (t2)
t1[1]=100 # not valid for tuples
SoâŚ
t3=t1 + t2
print (t3)
44. Delete Tuple Elements
⢠Removing individual tuple elements is not possible.
⢠Use del statement to delete entire tuple
Tup1=(âGaneshâ,âManishâ,âNileshâ)
print (Tup1)
del Tup1
print Tup1
45. Basic Tuples Operations
⢠Tuples respond to the + and * operators much like strings;
they mean concatenation and repetition here too,
except that the result is a new tuple, not a string.
Ex :
Tuple3=(âSundayâ,âMondayâ,âTuesdayâ)
Length -> print (len(tuple3))
Concatenation -> (1,2,3) + (4,5,6)
Repetition -> (âPythonâ,) * 5
Membership -> (print (5 in t2))
Iteration -> for names in (Tuple3) :
print (names)
46. Indexing, Slicing, and Matrixes
⢠Because tuples are sequences, indexing and slicing
work the same way for tuples as they do for strings.
Assuming following input
name=(âGaneshâ,âBalajiâ,âBhosaleâ)
1. print (name[2])
2. print (name[-2])
3. print (name[1:])
47. Python Dictionaries
⢠Python dictionary is an unordered collection of items.
⢠While other compound data types have only value as an element, a
dictionary has a key: value pair.
⢠Dictionaries are optimized to retrieve values when the key is known.
48. Python Dictionaries
⢠Dictionaries are the most Flexible Built-in data types in Python
⢠Items are stored and Fetched by Key , instead of by Positional
Parameters
50. ⢠Dictionary are mutable.
⢠We can add new items or change the value of existing items using
assignment operator.
⢠If the key is already present, value gets updated, else a new key: value
pair is added to the dictionary.
52. Python Dictionaries
⢠print (len(mydata)) - prints length of dictionary
⢠print (mydata.keys()) - prints all keys of dictionary
⢠print (mydata.values()) â prints all the values
Update
mydata[1] = "Joy"
print (mydata)
mydata.update({1:"Mangesh"})
54. ⢠Mathematically a set is a collection of items not in any particular
order.
⢠A Python set is similar to this mathematical definition with below
additional conditions.
⢠The elements in the set cannot be duplicates.
⢠The elements in the set are immutable(cannot be modified) but the
set as a whole is mutable.
⢠There is no index attached to any element in a python set.
⢠So they do not support any indexing or slicing operation.
Python Set
55. Set Operations
⢠The sets in python are typically used for mathematical operations like
union, intersection, difference and complement etc.
⢠We can create a set, access itâs elements and carry out these
mathematical operations
56. Creating a set
⢠A set is created by using the set() function or placing all the elements
within a pair of curly braces.
WeekDays=set([âMonâ,âTueâ,âWedâ,âThuâ,âFriâ,âSatâ,âSunâ])
Months={âJanâ,âFebâ,âMarâ,âAprâ}
Dates={21,25,31}
print(WeekDays)
print(Months)
print(Dates)
57. Accessing Values in a Set
⢠We cannot access individual values in a set.
⢠We can only access all the elements together as shown above.
⢠But we can also get a list of individual elements by looping through
the set.
days=set(["Mon","Tue","Wed","Thu"])
print(days)
for d in days:
print(d)
58. Adding Items to a Set
⢠We can add elements to a set by using add() method.
⢠Again as discussed there is no specific index attached to the newly
added element.
days=set(["Mon","Tue","Wed","Thu"])
days.add(âFriâ)
print(days)
59. Removing Item from a Set
⢠We can remove elements from a set by using discard() method.
⢠Again as discussed there is no specific index attached to the newly
added element.
days=set(["Mon","Tue","Wed","Thuâ,âFriâ,âSatâ,âSunâ])
days.discard(âSunâ)
print(days)
60. So Python Set
⢠A set is a unordered collection of Items
⢠Every Element is unique (no duplicates) and must be immutable
Declare
myset1={1,2,3,4,5,6}
myset2={2,4,6,8}
print (myset1)
print (myset2)
- Perform Union
print (myset1 | myset2)
- Perform Intersection
- print (myset1 & myset2)
66. For loop in python
⢠Syntax
for var in (list)
print var
Ex :
1. for no in range(1,11):
print (no)
list1=[âappleâ,âbananaâ,âmangoâ]
2. for names in list1 :
print names
3. for no in range(10):
print(no)
4. for no in range(0,30,2):
print(no) â prints even numbers from 1 to 30
67. While loop in python
⢠Syntax
while (condition) :
print
Ex :
i=0
while i<=10:
print (i)
i+=1
68. Break in python
i=0
while i<=10:
if (i==3) :
break
print (i)
i+=1
for i in range(10) :
if(i==5):
break
print(i)
i+=1
69. Continue in python
⢠i=0
⢠while i<=10:
⢠i+=1
⢠if(i==5):
⢠continue
⢠print(i)
⢠i+=1
71. Python - Functions
⢠A function is a block of organized,
reusable code that is used to perform a single, related action.
⢠Functions provide better modularity for your application and a high
degree of code reusing.
⢠As we already know, Python gives you many built-in functions like
print(), etc. but we can also create your own functions.
⢠These functions are called user-defined functions.
72. Defining a Function
⢠Function blocks begin with the keyword def followed by the function
name and parentheses ( ( ) ).
⢠Any input parameters or arguments should be placed within these
parentheses.
⢠You can also define parameters inside these parentheses.
⢠The first statement of a function can be an optional statement - the
documentation string of the function or docstring.
⢠The code block within every function starts with a colon (:) and is
indented.
⢠The statement return [expression] exits a function, optionally passing
back an expression to the caller.
⢠A return statement with no arguments is the same as return None.
73. ⢠All functions in Python have a return value, even if no return line
inside the code
⢠Functions without a return return the special value None
⢠None is a special constant in the language
⢠None is used like NULL, void, or nil in other languages
⢠None is also logically equivalent to False
74. Syntax
⢠def functionname(parameters) :
âfunction docstringâ
âfunction suiteâ
return [expr]
⢠Parameters have a positional behavior and you need to inform them
in the same order that they were defined.
⢠Ex :
75. Ex1 :
# define the function as follows :
def show(str):
print(str)
return ;
# call the function as follows :
show("Hello Ganesh")
78. ⢠import math
⢠print(math.sqrt(16))
⢠#print(math.pi)
⢠#print(math.cos(0))
⢠#print(dir(math))
⢠#print(help(math))
⢠#print(help(math(cos)))
⢠print (math.pow(2,5))
⢠#print (dir(math)) - will show you all the functions in Math Module
⢠help("modules") # to see list of all modules installed
⢠print(math.floor(2.3))
⢠print(math.ceil(2.3))
⢠import calendar
⢠cal=calendar.month(2018,11)
79. ⢠There is no function overloading in Python
⢠Unlike C++, a Python function is specified by its name alone
The number, order, names, or types of arguments cannot be used to distinguish between two
functions with the same name
⢠Two different functions canât have the same name, even if they
have different arguments
81. ⢠You can provide default values for a functionâs arguments
⢠These arguments are optional when the function is called
def myfun(b, c=3, d="hello"):
return b + c
z=myfun(5,3,"hello")
print(z)
c=myfun(5,3)
print(c)
x=myfun(5)
print(x)
82. Keyword Arguments
⢠Can call a function with some/all of its arguments out of order as long
as you specify their names
def test1(x,y,z):
return(2*x,4*y,8*z)
x=test1(1,2,3)
print (x)
y=test1(z=4, y=2, x=3)
print(y)
c=test1(-2, z=-4, y=-3)
print(c)
83. ⢠Can be combined with defaults, too
def furr(x=1,y=2,z=3):
return(2*x,4*y,8*z)
check=furr()
print(check)
check=furr(z=100)
print(check)
84. Functions are first-class objects
Functions can be used as any other datatype, eg:
⢠Arguments to function
⢠Return values of functions
⢠Assigned to variables
⢠Parts of tuples, lists, etc
def sq(x):
return x*x
def app(q, x):
return q(x)
res=app(sq, 5)
print(res)
85. Lambda in Python
⢠A lambda function is a small anonymous function.
⢠This function can have any number of arguments but only one
expression, which is evaluated and returned.
⢠One is free to use lambda functions wherever function objects are
required.
⢠You need to keep in your knowledge that lambda functions are
syntactically restricted to a single expression.
Syntax : lambda arguments : expression
86. Example
⢠A lambda function that adds 10 to the number passed in as an
argument, and print the result:
x=lambda a:a+10
print(x(5))
87. ⢠Lambda functions can take any number of arguments:
Example
⢠A lambda function that multiplies argument a with argument b and
print the result:
x=lambda a,b : a+b
print(x(2,3))
88. A lambda function that sums argument a, b, and c and print the result:
res=lambda a,b,c : a*b*c
print(res(1,2,3))
89. Ex : Use Lambda Function within function
def myfunc(n):
return lambda a : a * n
x=myfunc(10)
print(x(5))
90. ⢠Ex 1 :
Write a function to double the value you pass
Write a function to triple the value you pass
91. Lambda Notation
⢠Pythonâs lambda creates anonymous functions
x=app(lambda z: z * 4, 7)
print(x)
g=app(lambda x:x**2,3)
print(g)
Note: only one expression in the lambda body; its value is
always returned
⢠Python supports functional programming idioms: map, filter,
closures, continuations, etc.
94. What are Modules?
⢠Modules are files containing Python definitions and statements (ex.
name.py)
⢠A moduleâs definitions can be imported into other modules by using
âimport nameâ
⢠The moduleâs name is available as a global variable value
⢠To access a moduleâs functions, type âname.function()â
95. More on Modules
ď Modules can contain executable statements along with function definitions
ď Each module has its own private symbol table used as the global symbol
table by all functions in the module
ď Modules can import other modules
ď Each module is imported once per interpreter session
ď reload(name)
ď Can import names from a module into the importing moduleâs symbol
table
ď from mod import m1, m2 (or *)
ď m1()
96. Standard Modules
ď Python comes with a library of standard modules described in the
Python Library Reference
ď Some are built into interpreter
ď import math
ď print(math.sqrt(16))
ď sys.path determines the interpretersâs search path for modules, with
the default path taken from PYTHONPATH
ď Can be modified with append() (ex. Sys.path.append(âSOMEPATHâ)
97. Modules
⢠When a Python program starts it only has access to a basic functions
and classes.
⢠i.e (âintâ,âstringâ,âlenâ,âclassâ,âsumâ,ârangeâ,âdictâ)
⢠âModulesâ contain additional functionality.
⢠Use âimportâ to tell Python to load a module.
>>> import math
100. âimportâ and âfrom ... import ...â
>>> import math
math.cos
>>> from math import cos, pi
cos
>>> from math import *
101. ⢠print (dir(math)) - will show you all the functions in Math Module
⢠To see all the functions in math module
⢠Google => functions in math module
Import math
print(math.floor(2.3))
print(math.ceil(2.3))
import calendar
cal=calendar.month(2018,11)
#print(cal)
calendar.isleap(2016)
102. Importing * From a Package
⢠* does not import all submodules from a package
⢠Ensures that the package has been imported, only importing the
names of the submodules defined in the package
⢠import sound.effects.echo
import sound.effects.surround
from sound.effects import *
104. File I/O
⢠Python provides basic functions and methods necessary to
manipulate files by default.
⢠We can do most of the file manipulation using a file object.
105. Mode Description
'r' Open a file for reading only.
'w' Open a file for writing only.
'a' Open a file for appending data. Data are
written to the end of the file.
'rb' Open a file for reading binary data.
'wb' Open a file for writing binary data.
106. Open File
⢠Open files for Reading
fh1=open("data1.txt","r")
str1=fh1.read()
print(str1)
fh1.close()
108. Check for File Existence
⢠import os.path
⢠if os.path.isfile("data9.txt"):
⢠print("File exists")
⢠else:
⢠print("File not Present....")
109. ⢠Write a function check_stats that accepts a file name as a parameter
and that reports the longest line in the file.
⢠example input file, data3.txt:
Hello Everyone
Welcome to Python Programming
For Vodaphone in Prdentia
Today is the 3rd Day
Beware the JubJub bird
110. def input_stats(filename): # Function definition
input = open(filename) # open file
longest = "â # Declare Null String
for line in input: # loop for accessing file contents
if len(line) > len(longest):
longest = line
print("Longest line =", len(longest)) # Print Longest Line
print(longest)
input_stats("data3.txt") # Call Function
112. String Splitting
⢠split breaks a string into tokens that you can loop over.
name.split() # break by whitespace
name.split(delimiter) # break by delimiter
Ex :
⢠name = "Ganesh,B,Bhosaleâ
namelist=name.split()
print(namelist)
namelist2=name.split(",")
print(namelist2)
113. Using for loop =>
name = "Ganesh B Bhosale"
for word in name.split() :
print(word)
⢠join performs the opposite of a split
delimiter.join(list of tokens)
str=",".join(name.split(" "))
print(str)
114. Splitting into Variables
⢠If you know the number of tokens, you can split them directly into
a sequence of variables.
var1, var2, ..., varN = string.split()
⢠may want to convert type of some tokens: type(value)
str = âGanesh 49 25000.28"
name, age, money = s.split()
print(name)
print(age)
print(money)
115. Exercise
⢠Suppose we have this hours.txt data:
10023 Joy 8.5 7.1 8.6 4.1 9.2
40156 Rahul 7.0 9.6 6.5 4.9 8.8
78945 Ganesh 8.0 8.0 8.0 8.0 7.5
Compute each worker's total hours and hours/day.
Assume each worker works exactly five days.
Soln =>
116. input = open("hours.txt","r")
for line in input:
id, name, mon, tue, wed, thu, fri = line.split()
# cumulative sum of this employee's hours
hours = float(mon) + float(tue) + float(wed) + float(thu) + float(fri)
print(name, "ID", id, "worked",
hours, "hours: ", hours/5, "/ day")
117. Writing Files
name1 = open("filename", "w") # opens file for write (deletes
previous contents)
name2 = open("filename", "a")# opens file for append (new data
goes after previous data)
name.write(str) - writes the given string to the file
name.close() - saves file once writing is done
118. Ex1:
out = open("output.txt", "w")
out.write("Hello, world!n")
out.write("How are you?")
out.close()
pr=open("output.txt").read()
print(pr)
119. ⢠Ex2:
outfile1=open("out.txt","a")
str=input("Enter String to Write")
outfile1.write("My Name is Anthonyn")
outfile1.write("How Are Youn")
outfile1.write("How is your brother Amar an Akbarn")
outfile1.close()
rd=open("out.txt","r")
for text in rd:
print(text)
120. Exercise :
⢠Accept Employee Details from User and create Data file
(atleast 5 Records)
⢠Accept Employee Name and Display Details and store in list/Tuple
121. What is Exception?
⢠An exception is an event, which occurs during the execution of a
program that disrupts the normal flow of the program's instructions.
⢠In general, when a Python script encounters a situation that it cannot
cope with, it raises an exception.
⢠An exception is a Python object that represents an error.
⢠When a Python script raises an exception, it must either handle the
exception immediately otherwise it terminates and quits.
122. Handling an exception
⢠If you have some suspicious code that may raise an exception,
you can defend your program by placing the suspicious code in
a try: block.
⢠After the try: block, include an except: statement, followed by a
block of code which handles the problem as elegantly as possible.
Syntax ->
123. try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
124. Example 1
⢠The program opens a file, writes content in the, file and comes out
gracefully because there is no problem at all â
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print ("Error: can't find file or read data")
else:
print ("Written content in the file successfully")
fh.close()
125. Example 1
⢠This example tries to open a file where you do not have write
permission, so it raises an exception -
try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")
except IOError:
print ("Error: can't find file or read data")
else:
print ("Written content in the file successfully")
126. Exception Names and their Descriptions --- locals()[__builtins__]
1.Exception
Base class for all exceptions
2.StopIteration
Raised when the next() method of an iterator does not point
to any object.
3.SystemExit
Raised by the sys.exit() function.
4.StandardError
Base class for all built-in exceptions except StopIteration
and SystemExit.
5.ArithmeticError
Base class for all errors that occur for numeric calculation
127. 6.ZeroDivisionError
Raised when division or modulo by zero takes place for all
numeric types.
7.KeyboardInterrupt
Raised when the user interrupts program execution,
usually by pressing Ctrl+c.
8.IOError
Raised when an input/ output operation fails,
such as the print statement or the open() function
when trying to open a file that does not exist.
9.IOError
Raised for operating system-related errors.
10.RuntimeError
Raised when a generated error does not fall into any category.
128. Here are few important points about the above-mentioned syntax â
⢠A single try statement can have multiple except statements.
⢠This is useful when the try block contains statements that may throw
different types of exceptions.
⢠You can also provide a generic except clause, which handles any
exception.
⢠After the except clause(s), you can include an else-clause.
⢠The code in the else-block executes if the code in the try: block does
not raise an exception.
⢠The else-block is a good place for code that does not need the try:
block's protection.
129. The try-finally Clause
⢠You can use a finally: block along with a try: block.
⢠The finally block is a place to put any code that must execute,
whether the try-block raised an exception or not.
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print ("Error: can't find file or read data")
130. Argument of an Exception
⢠An exception can have an argument, which is a value that gives
additional information about the problem.
⢠The contents of the argument vary by exception.
⢠You capture an exception's argument by supplying a variable in the
except clause
133. Understanding Object-Oriented Basics
⢠OOP allows representation of real-life objects as software objects
(e.g., a dictionary as an object)
⢠Object: A single software unit that combines attributes and
methods
⢠Attribute: A "characteristic" of an object; like a variable associated
with a kind of object
⢠Method: A "behavior" of an object; like a function associated with a
kind of object
⢠Class: Code that defines the attributes and methods of a kind of
object (A class is a collection of variables and functions working with
these variables)
134. Fundamental Concepts of OOP
⢠Information hiding
⢠Abstraction
⢠Encapsulation
⢠Modularity
⢠Polymorphism
⢠Inheritance
135. Classes and Objects
⢠Python is an object oriented programming language.
⢠Almost everything in Python is an object, with its properties and
methods.
⢠A Class is like an object constructor, or a "blueprint" for creating
objects.
136. Create a Class
class MyClass:
x = 5
Create Object
p1 = MyClass()
print(p1.x)
⢠Class: Code that defines the attributes and methods of a kind of object
⢠Instantiate: To create an object; A single object is called an Instance
Creating Classes for Objects
137. The __init__() Function
⢠The examples above are classes and objects in their simplest form,
and are not really useful in real life applications.
⢠To understand the meaning of classes we have to understand the
built-in __init__() function.
⢠All classes have a function called __init__(), which is always executed
when the class is being initiated.
⢠Use the __init__() function to assign values to object properties, or
other operations that are necessary to do when the object is being
created:
138. Create a class named Person, use the __init__() function to
assign values for name and age:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person(âGanesh", 49)
print(p1.name)
print(p1.age)
139. Object Methods
⢠Objects can also contain methods.
⢠Methods in objects are functions that belongs to the object
Lets create a method in the Person class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
Note : The Self parameter is a reference to the class itself, used to access the variables inside
140. Modify Object Properties
class Person:
def __init__(somename, name, age):
somename.name = name
somename.age = age
def myfunc(somename):
print("Hello my name is " + somename.name+ str(somename.age))
p1 = Person(âGanesh", 49)
p1.myfunc()
# Modify
p1.age=50
p1.myfunc()
145. ⢠1. Identify the Problems in Log File (Date and Time)
⢠Identify Fake Email Addresses
⢠Correct and Wrong Phone Numbers from data
⢠Update Student DB by Search and Replace
147. What is Regex ?
⢠Regular expression is a sequence of character(s) mainly used to find
and replace patterns in a string or file.
⢠They are supported by most of the programming languages
like python, perl, R, Java and many others.
⢠Regular Expression is Special Text String for describing a Search
Pattern
⢠Search and Replace
⢠Display in Proper Format
148. Regular expressions use two types of characters:
a) Meta characters: As the name suggests, these characters have a
special meaning, similar to * in wild card.
b) Literals (like a,b,1,2âŚ)
⢠In Python, we have module âreâ that helps with regular expressions.
⢠So you need to import library re before you can use regular
expressions in Python.
149. The most common uses of regular expressions are:
ďź Search a string (search and match)
ďź Finding a string (findall)
ďź Break string into a sub strings (split)
ďź Replace part of a string (sub)
150. ⢠The âreâ package provides multiple methods to perform queries on an
input string.
⢠Some most commonly used methods, lets discuss:
ďźre.match()
ďźre.search()
ďźre.findall()
ďźre.split()
ďźre.sub()
ďźre.compile()
151. re.match(pattern, string):
⢠This method finds match if it occurs at start of the string.
⢠For example, calling match() on the string âGB Bhosaleâ and looking
for a pattern âGBâ will match.
⢠However, if we look for only Bhosale, the pattern will not match.
import re
result = re.match(r'GB', 'GB Bhosale Vedics GB')
print(result.group(0))
⢠Above, it shows that pattern match has been found.
⢠To print the matching string use method group (It helps to return the
matching string).
⢠ârâ used at the start of the pattern string, to designate a python raw string.
152. start() and end() to know the start and end position of
matching pattern in the string.
import re
result = re.match('GB', 'GB Bhosale Vedics GB')
print(result.start())
print(result.end())
156. Search and Replace â re.sub()
Import re
result=re.sub(r'India','the World','GB is the Common Man in India')
print(result)
157. Most commonly used operators in Regular Expressions
. Matches with any single character except newline ânâ.
? match 0 or 1 occurrence of the pattern to its left
+ 1 or more occurrences of the pattern to its left
* 0 or more occurrences of the pattern to its left
w Matches with a alphanumeric character whereas W (upper case W) matches non alphanumeric character.
d Matches with digits [0-9] and /D (upper case D) matches with non-digits.
s Matches with a single white space character (space, newline, return, tab, form) and S (upper case S) matches
any non-white space character.
b boundary between word and non-word and /B is opposite of /b
[..] Matches any single character in a square bracket and [^..] matches any single character not in square bracket
It is used for special meaning characters like . to match a period or + for plus sign.
^ and $ ^ and $ match the start or end of the string respectively
{n,m} Matches at least n and at most m occurrences of preceding expression if we write it as {,m} then it will return
at least any minimum occurrence to max m preceding expression.
a| b Matches either a or b
( ) Groups regular expressions and returns matched text
t, n, r Matches tab, newline, return
158. Assertion
⢠An assertion is a sanity-check that you can turn on or turn off when
you are done with your testing of the program.
⢠The easiest way to think of an assertion is to liken it to a raise-
if statement (or to be more accurate, a raise-if-not statement).
⢠An expression is tested, and if the result comes up false, an exception
is raised.
⢠Assertions are carried out by the assert statement, the newest
keyword to Python, introduced in version 1.5.
⢠Programmers often place assertions at the start of a function to check
for valid input, and after a function call to check for valid output
159. The assert Statement
⢠When it encounters an assert statement, Python evaluates the
accompanying expression, which is hopefully true.
⢠If the expression is false, Python raises an AssertionError exception.
⢠Syntax - assert Expression[, Arguments]
⢠If the assertion fails, Python uses ArgumentExpression as the
argument for the AssertionError.
⢠AssertionError exceptions can be caught and handled like any other
exception using the try-except statement, but if not handled, they will
terminate the program and produce a traceback.
160. Example 1
def check_value(no) :
assert (no >=10),"Value Large than 10"
return (no)
print(check_value(5))
print(check_value(15))
163. SQLite - Python
⢠SQLite3 can be integrated with Python using sqlite3 module, which
was written by Gerhard Haring.
It provides an SQL interface compliant with the DB-API 2.0
specification described by PEP 249.
⢠You do not need to install this module separately because it is
shipped by default along with Python version 2.5.x onwards.
⢠To use sqlite3 module, you must first create a connection object that
represents the database and then optionally you can create a cursor
object, which will help you in executing all the SQL statements.
165. Connect To Database
import sqlite3
conn = sqlite3.connect('test.db')
Print("Opened database successfullyâ)
Run the above program to create our database test.db in the current
directory.
You can change your path as per your requirement.
Keep the above code in sqlite.py file
If the database is successfully created, then it will display the following
message.
166. Create a Table
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
conn.execute('''CREATE TABLE COMPANY
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL);''')
print "Table created successfully";
conn.close()
167. INSERT Operation
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Paul', 32, 'California', 20000.00 )");
conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (2, 'Allen', 25, 'Texas', 15000.00 )");
conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (3, 'Teddy', 23, 'Norway', 20000.00 )");
conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 )");
conn.commit()
print "Records created successfully";
conn.close()