SlideShare a Scribd company logo
1 of 174
Python Programming
Python
• A readable
• Dynamic
• pleasant
• Flexible
• Fast and powerful language
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
Imp. Features of Python
• Everything is an Object
• Interactive Shell
• Strong Introspection
• Cross Platform
• CPython, Jython, IronPython, PyPy
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
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.
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.
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……….
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…..
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
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
Installing Python
• www.python.org
• Download Python 3.7
• After Downloading you have three options to use Python
• Python CLI
• Text Editor
• Python IDE
Development Environments
1. PyDev with Eclipse
2. Komodo
3. Emacs
4. Vim
5. TextMate
6. Gedit
7. Idle
8. PIDA (Linux)(VIM Based)
9. NotePad++ (Windows)
10.BlueFish (Linux)
11. Geany
12. Python Interactive Shell
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)
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)
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 _
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
Python Tokens
• Operators
Categories :
Arithmetic Operator
Assignment Operator
Comparison Operator
Logical Operator
Bitwise Operator
Identity Operator
Membership Operator
Python Operators
Arithmetic Operators
+
-
*
%
/
• Assignment Operators
=
+=
-=
*=
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)
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)
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) - ?
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
• 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
• 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)
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
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
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])
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))
Some String Functions
• find()
name="Ganesh Bhosale"
print (name.find("esh"))
• replace()
str=name.replace("Ganesh","Manish")
print (str)
• split()
str="Ganesh,Balaji,Bhosale"
print (str)
str2=str.split(',')
print (str2) - ['Ganesh', 'Balaji', 'Bhosale’]
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
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.
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]
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)
Basic List Operations
• length
• Concatenation
• Repetition
• Membership
• Iteration
Indexing / Slicing / Matrices on list :
print (sub_list[2])
print (sub_list[2:5]
Built-in Functions on list
• len(list)
• max(list)
• min(list
• list(seq)
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”))
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)
Tuples
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.
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)
Accessing Values in Tuples
• Tuple1=("Sunday","Monday","Tuesday")
Print Tuple1[0] - Access the first Element
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)
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
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)
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:])
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.
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
Declaration 1:
mydata={1:”Ganesh”, 2:”Manish”, 3:”Nilesh”}
print (mydata[2])
Declaration 2:
mydata={name:”Johny”,1:[1,2,3]}
print (mydata[1])
• 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.
• my_name_dict = {'name’:’Ganesh', 'age’: 48}
• update value
my_name_dict['age'] = 47
print(my_name_dict)
• add item
my_name_dict['address'] = ‘Pune’
print(my_dict)
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"})
Python Sets
• 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
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
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)
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)
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)
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)
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)
Python Set
- Difference
print (myset1 - myset2)
print (myset2 – myset1)
Flow Control in Python
• If – else
• Nested if-else
• for
• while
• break
• continue
If-else flow control
• Syntax
if <condition> :
statements
else:
statements
Nested if-else
• Syntax
if (condition):
statements1
elif (condition) :
statements2
else
statement3
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
While loop in python
• Syntax
while (condition) :
print
Ex :
i=0
while i<=10:
print (i)
i+=1
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
Continue in python
• i=0
• while i<=10:
• i+=1
• if(i==5):
• continue
• print(i)
• i+=1
Python Functions
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.
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.
• 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
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 :
Ex1 :
# define the function as follows :
def show(str):
print(str)
return ;
# call the function as follows :
show("Hello Ganesh")
Ex2 :
def add_numbers(n1,n2) :
print(n1+n2)
return
add_numbers(10,20)
Ex3 : d:file1.py
d:file2.py
d:disp_numbers.py
d:add_numbers.py
Ex3:
def add_f(a,y=20):
return(a+y)
n1=add_f(10)
print("return is ",n1)
n2=add_f(100,200)
print("return is ",n2)
Ex4 :
def disp_list(list2):
for var in list2:
return (list2);
i+=1
list1=[1,2,3,5,4,33]
list3=disp_list(list1)
print("List3 is ",list3)
• 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)
• 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
• def myfunc(a,b):
• return (a+b)
•
• z=myfunc(10,20)
• print(z)
• def myfunc(str,b):
• return str
• x=myfunc("Ganesh",20)
• print(x)
• 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)
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)
• 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)
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)
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
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))
• 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))
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))
Ex : Use Lambda Function within function
def myfunc(n):
return lambda a : a * n
x=myfunc(10)
print(x(5))
• Ex 1 :
Write a function to double the value you pass
Write a function to triple the value you pass
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.
Lambda Notation
• f = lambda x,y : 2 * x + y
• l=f(3,4)
• print(l)
Modules in Python
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()”
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()
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’)
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
import the math module
import math
math.pi
3.1415926535897931
math.cos(0)
1.0
math.cos(math.pi)
-1.0
dir(math)
['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh',
'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos',
'cosh', 'degrees', 'e', 'exp', 'fabs', 'factorial', 'floor', 'fmod',
'frexp', 'fsum', 'hypot', 'isinf', 'isnan', 'ldexp', 'log', 'log10',
'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan',
'tanh', 'trunc']
help(math)
help(math.cos)
Ex:
• 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))
“import” and “from ... import ...”
>>> import math
math.cos
>>> from math import cos, pi
cos
>>> from math import *
• 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)
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 *
File Handling
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.
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.
Open File
• Open files for Reading
fh1=open("data1.txt","r")
str1=fh1.read()
print(str1)
fh1.close()
fh3=open("data3.txt","r")
for line in fh3:
print(line)
Check for File Existence
• import os.path
• if os.path.isfile("data9.txt"):
• print("File exists")
• else:
• print("File not Present....")
• 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
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
Recall String Methods
len(str)
upper, lower,
capitalize
find
strip
• name = " Ganesh B Bhosale "
• print(name.upper())
• print(name.lower())
• print(name.capitalize())
• print(name.lower())
• x=name.find("Bhosale")
• print(x)
• print(len(name))
• str=name.strip() # trim spaces
• print(len(str))
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)
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)
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)
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 =>
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")
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
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)
• 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)
Exercise :
• Accept Employee Details from User and create Data file
(atleast 5 Records)
• Accept Employee Name and Display Details and store in list/Tuple
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.
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 ->
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.
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()
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")
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
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.
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.
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")
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
def temp_convert(var):
try:
return int(var)
except ValueError:
print "The argument does not contain numbersn", var
• # Call above function here.
temp_convert("xyz")
Classes and Objects
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)
Fundamental Concepts of OOP
• Information hiding
• Abstraction
• Encapsulation
• Modularity
• Polymorphism
• Inheritance
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.
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
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:
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)
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
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()
• class Puppy(object):
• def __init__(self):
• self.name = []
• self.color = []
• def __setitem__(self, name, color):
• self.name.append(name)
• self.color.append(color)
• def __getitem__(self, name):
• if name in self.name:
• return self.color[self.name.index(name)]
• else:
• return None
• dog = Puppy()
• dog['Max'] = 'brown'
• dog['Ruby'] = 'yellow'
• print ("Max is", dog['Max'])
Exercise :
• 1. Create a Employee Class.
• 2. Create Multiple Employee Objects and Store their Details in a file
Regular Expressions
• Why ?
• What ?
• Basic Operations
• Examples
• 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
• Regular Expressions Compatible with
• Java
• Ruby
• C#
• Groovy
• PHP
• Swift
• Scala
• Perl
• Unix
• Javascript
• etc
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
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.
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)
• 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()
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.
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())
Searching Pattern
Import re
result = re.search(‘Vedics', 'GB Bhosale Vedics GB Vedics ')
print(result.group(0))
Re.findall()
Import re
result = re.findall('GB', 'GB Bhosale Vedics GB')
print(result)
Re.split()
Import re
result=re.split(r’y','Analytics')
print(result)
# Multiple Splits
result=re.split(r’y','Analytics VidhyaVihar')
print(result)
Search and Replace – re.sub()
Import re
result=re.sub(r'India','the World','GB is the Common Man in India')
print(result)
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
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
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.
Example 1
def check_value(no) :
assert (no >=10),"Value Large than 10"
return (no)
print(check_value(5))
print(check_value(15))
Example 1
def KelvinToFahrenheit(Temp):
assert (Temp >= 0),"Colder than absolute zero!"
return ((Temp-273)*1.8)+32
print (KelvinToFahrenheit(27))
#print (KelvinToFahrenheit(273))
#print (int(KelvinToFahrenheit(505.78)))
#print (KelvinToFahrenheit(-5))
Database with Python
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.
Python sqlite3 module APIs
• sqlite3.connect(database [,timeout ,other optional arguments])
• connection.cursor([cursorClass])
• cursor.execute(sql [, optional parameters])
Ex :cursor.execute("insert into people values (?, ?)", (who, age))
• connection.commit()
• connection.rollback()
• connection.close()
• cursor.fetchone()
• cursor.fetchall()
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.
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()
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()
SELECT Operation
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
cursor = conn.execute("SELECT id, name, address, salary from COMPANY")
for row in cursor:
print "ID = ", row[0]
print "NAME = ", row[1]
print "ADDRESS = ", row[2]
print "SALARY = ", row[3], "n"
print "Operation done successfully";
conn.close()
UPDATE Operation
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
conn.execute("UPDATE COMPANY set SALARY = 25000.00 where ID = 1")
conn.commit
print "Total number of rows updated :", conn.total_changes
cursor = conn.execute("SELECT id, name, address, salary from COMPANY")
for row in cursor:
print "ID = ", row[0]
print "NAME = ", row[1]
print "ADDRESS = ", row[2]
print "SALARY = ", row[3], "n"
print "Operation done successfully";
conn.close()
DELETE Operation
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
conn.execute("DELETE from COMPANY where ID = 2;")
conn.commit()
print "Total number of rows deleted :", conn.total_changes
cursor = conn.execute("SELECT id, name, address, salary from COMPANY")
for row in cursor:
print "ID = ", row[0]
print "NAME = ", row[1]
print "ADDRESS = ", row[2]
print "SALARY = ", row[3], "n"
print "Operation done successfully";
conn.close()
• import sqlite3
• conn = sqlite3.connect('test.db')
• print("Opened database successfully")
• #conn.execute('''create table emp1
• # (empno int primary key,
• # ename text not null,
• # salary real);''')
•
• #print ("Table Successfully Created")
• #conn.execute('Insert into emp1 values(1010,"Ganesh",4000);')
• #conn.execute('Insert into emp1 values(1020,"Manish",6000);')
• #conn.execute('Insert into emp1 values(1030,"Nilesh",7000);')
• #conn.execute('Insert into emp1 values(1040,"Joy",45000);')
• conn.commit()
• print("Records Inserted Successfully...")
• cur=conn.execute('select empno,ename,salary from emp1;')
• print("EmpnottEmpNamettSalary")
• fp=open("datafile.txt","w")
• for row in cur:
• #print(row[0],"tt",row[1],"t",row[2])
• #fp.write(str(row)+"n")
• fp.write("empnot"+str(row[0]))
• fp.write("tempnamet"+row[1])
• fp.write("tSalaryt"+str(row[2]))
• fp.write("n")
•
• fp.close()
• # Display all tables created in sqlite
•
• con = sqlite3.connect(r'test.db')
• mycur = con.cursor()
• mycur.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;")
• available_table=(mycur.fetchall())
• print(available_table)
• conn.close()
Questions / Doubts /Message /
Warnings/Suggesstions ?
Thanks for Your Co-operation and Support

More Related Content

What's hot

1. python programming
1. python programming1. python programming
1. python programmingsreeLekha51
 
Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3Chariza Pladin
 
Intro to Python Workshop San Diego, CA (January 19, 2013)
Intro to Python Workshop San Diego, CA (January 19, 2013)Intro to Python Workshop San Diego, CA (January 19, 2013)
Intro to Python Workshop San Diego, CA (January 19, 2013)Kendall
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPTShivam Gupta
 
Introduction to-python
Introduction to-pythonIntroduction to-python
Introduction to-pythonAakashdata
 
Introduction to Python Pandas for Data Analytics
Introduction to Python Pandas for Data AnalyticsIntroduction to Python Pandas for Data Analytics
Introduction to Python Pandas for Data AnalyticsPhoenix
 
Ground Gurus - Python Code Camp - Day 3 - Classes
Ground Gurus - Python Code Camp - Day 3 - ClassesGround Gurus - Python Code Camp - Day 3 - Classes
Ground Gurus - Python Code Camp - Day 3 - ClassesChariza Pladin
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...Maulik Borsaniya
 
Introduction about Python by JanBask Training
Introduction about Python by JanBask TrainingIntroduction about Python by JanBask Training
Introduction about Python by JanBask TrainingJanBask Training
 
Most Asked Python Interview Questions
Most Asked Python Interview QuestionsMost Asked Python Interview Questions
Most Asked Python Interview QuestionsShubham Shrimant
 
What is Python?
What is Python?What is Python?
What is Python?PranavSB
 

What's hot (20)

Python - the basics
Python - the basicsPython - the basics
Python - the basics
 
Python basic
Python basicPython basic
Python basic
 
Python Intro
Python IntroPython Intro
Python Intro
 
1. python programming
1. python programming1. python programming
1. python programming
 
Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3
 
Intro to Python Workshop San Diego, CA (January 19, 2013)
Intro to Python Workshop San Diego, CA (January 19, 2013)Intro to Python Workshop San Diego, CA (January 19, 2013)
Intro to Python Workshop San Diego, CA (January 19, 2013)
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPT
 
Python with data Sciences
Python with data SciencesPython with data Sciences
Python with data Sciences
 
Introduction to-python
Introduction to-pythonIntroduction to-python
Introduction to-python
 
Python Tutorial Part 2
Python Tutorial Part 2Python Tutorial Part 2
Python Tutorial Part 2
 
Introduction to Python Pandas for Data Analytics
Introduction to Python Pandas for Data AnalyticsIntroduction to Python Pandas for Data Analytics
Introduction to Python Pandas for Data Analytics
 
Ground Gurus - Python Code Camp - Day 3 - Classes
Ground Gurus - Python Code Camp - Day 3 - ClassesGround Gurus - Python Code Camp - Day 3 - Classes
Ground Gurus - Python Code Camp - Day 3 - Classes
 
Python ppt
Python pptPython ppt
Python ppt
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
 
Introduction about Python by JanBask Training
Introduction about Python by JanBask TrainingIntroduction about Python by JanBask Training
Introduction about Python by JanBask Training
 
Most Asked Python Interview Questions
Most Asked Python Interview QuestionsMost Asked Python Interview Questions
Most Asked Python Interview Questions
 
Programming
ProgrammingProgramming
Programming
 
Python final ppt
Python final pptPython final ppt
Python final ppt
 
Python basics
Python basicsPython basics
Python basics
 
What is Python?
What is Python?What is Python?
What is Python?
 

Similar to Python programming

web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh MalothBhavsingh Maloth
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programmingChetan Giridhar
 
modul-python-part1.pptx
modul-python-part1.pptxmodul-python-part1.pptx
modul-python-part1.pptxYusuf Ayuba
 
python presntation 2.pptx
python presntation 2.pptxpython presntation 2.pptx
python presntation 2.pptxArpittripathi45
 
prakash ppt (2).pdf
prakash ppt (2).pdfprakash ppt (2).pdf
prakash ppt (2).pdfShivamKS4
 
Python presentation of Government Engineering College Aurangabad, Bihar
Python presentation of Government Engineering College Aurangabad, BiharPython presentation of Government Engineering College Aurangabad, Bihar
Python presentation of Government Engineering College Aurangabad, BiharUttamKumar617567
 
Fundamentals of Python Programming
Fundamentals of Python ProgrammingFundamentals of Python Programming
Fundamentals of Python ProgrammingKamal Acharya
 
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
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methodsPranavSB
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdfsamiwaris2
 

Similar to Python programming (20)

intro to python.pptx
intro to python.pptxintro to python.pptx
intro to python.pptx
 
Python Demo.pptx
Python Demo.pptxPython Demo.pptx
Python Demo.pptx
 
Python Demo.pptx
Python Demo.pptxPython Demo.pptx
Python Demo.pptx
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 
Python-Basics.pptx
Python-Basics.pptxPython-Basics.pptx
Python-Basics.pptx
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programming
 
Python Programming 1.pptx
Python Programming 1.pptxPython Programming 1.pptx
Python Programming 1.pptx
 
modul-python-part1.pptx
modul-python-part1.pptxmodul-python-part1.pptx
modul-python-part1.pptx
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
Python 01.pptx
Python 01.pptxPython 01.pptx
Python 01.pptx
 
python presntation 2.pptx
python presntation 2.pptxpython presntation 2.pptx
python presntation 2.pptx
 
prakash ppt (2).pdf
prakash ppt (2).pdfprakash ppt (2).pdf
prakash ppt (2).pdf
 
Python1
Python1Python1
Python1
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Python presentation of Government Engineering College Aurangabad, Bihar
Python presentation of Government Engineering College Aurangabad, BiharPython presentation of Government Engineering College Aurangabad, Bihar
Python presentation of Government Engineering College Aurangabad, Bihar
 
Fundamentals of Python Programming
Fundamentals of Python ProgrammingFundamentals of Python Programming
Fundamentals of Python Programming
 
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.
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
 
bhaskars.pptx
bhaskars.pptxbhaskars.pptx
bhaskars.pptx
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdf
 

More from Ganesh Bhosale

More from Ganesh Bhosale (14)

KMSUnix and Linux.pptx
KMSUnix and Linux.pptxKMSUnix and Linux.pptx
KMSUnix and Linux.pptx
 
RDBMS_Concept.ppt
RDBMS_Concept.pptRDBMS_Concept.ppt
RDBMS_Concept.ppt
 
CLI.pptx
CLI.pptxCLI.pptx
CLI.pptx
 
Exam_Questions.docx
Exam_Questions.docxExam_Questions.docx
Exam_Questions.docx
 
AWS WAF.pptx
AWS WAF.pptxAWS WAF.pptx
AWS WAF.pptx
 
Python_Final_Test.docx
Python_Final_Test.docxPython_Final_Test.docx
Python_Final_Test.docx
 
KMS_Unix_Test_Questions.pdf
KMS_Unix_Test_Questions.pdfKMS_Unix_Test_Questions.pdf
KMS_Unix_Test_Questions.pdf
 
Machine learning
Machine learningMachine learning
Machine learning
 
Linux test paper2
Linux test paper2Linux test paper2
Linux test paper2
 
test questions
test questionstest questions
test questions
 
Module 1 introduction to aws demo 4
Module 1 introduction to aws demo 4Module 1 introduction to aws demo 4
Module 1 introduction to aws demo 4
 
Setup ip address manually using nmcli command
Setup ip address manually using nmcli commandSetup ip address manually using nmcli command
Setup ip address manually using nmcli command
 
Workshops
WorkshopsWorkshops
Workshops
 
Day4
Day4Day4
Day4
 

Recently uploaded

George Lever - eCommerce Day Chile 2024
George Lever -  eCommerce Day Chile 2024George Lever -  eCommerce Day Chile 2024
George Lever - eCommerce Day Chile 2024eCommerce Institute
 
Open Source Strategy in Logistics 2015_Henrik Hankedvz-d-nl-log-conference.pdf
Open Source Strategy in Logistics 2015_Henrik Hankedvz-d-nl-log-conference.pdfOpen Source Strategy in Logistics 2015_Henrik Hankedvz-d-nl-log-conference.pdf
Open Source Strategy in Logistics 2015_Henrik Hankedvz-d-nl-log-conference.pdfhenrik385807
 
Call Girls in Sarojini Nagar Market Delhi 💯 Call Us 🔝8264348440🔝
Call Girls in Sarojini Nagar Market Delhi 💯 Call Us 🔝8264348440🔝Call Girls in Sarojini Nagar Market Delhi 💯 Call Us 🔝8264348440🔝
Call Girls in Sarojini Nagar Market Delhi 💯 Call Us 🔝8264348440🔝soniya singh
 
Re-membering the Bard: Revisiting The Compleat Wrks of Wllm Shkspr (Abridged)...
Re-membering the Bard: Revisiting The Compleat Wrks of Wllm Shkspr (Abridged)...Re-membering the Bard: Revisiting The Compleat Wrks of Wllm Shkspr (Abridged)...
Re-membering the Bard: Revisiting The Compleat Wrks of Wllm Shkspr (Abridged)...Hasting Chen
 
BDSM⚡Call Girls in Sector 93 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 93 Noida Escorts >༒8448380779 Escort ServiceBDSM⚡Call Girls in Sector 93 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 93 Noida Escorts >༒8448380779 Escort ServiceDelhi Call girls
 
VVIP Call Girls Nalasopara : 9892124323, Call Girls in Nalasopara Services
VVIP Call Girls Nalasopara : 9892124323, Call Girls in Nalasopara ServicesVVIP Call Girls Nalasopara : 9892124323, Call Girls in Nalasopara Services
VVIP Call Girls Nalasopara : 9892124323, Call Girls in Nalasopara ServicesPooja Nehwal
 
Night 7k Call Girls Noida Sector 128 Call Me: 8448380779
Night 7k Call Girls Noida Sector 128 Call Me: 8448380779Night 7k Call Girls Noida Sector 128 Call Me: 8448380779
Night 7k Call Girls Noida Sector 128 Call Me: 8448380779Delhi Call girls
 
Introduction to Prompt Engineering (Focusing on ChatGPT)
Introduction to Prompt Engineering (Focusing on ChatGPT)Introduction to Prompt Engineering (Focusing on ChatGPT)
Introduction to Prompt Engineering (Focusing on ChatGPT)Chameera Dedduwage
 
Call Girl Number in Khar Mumbai📲 9892124323 💞 Full Night Enjoy
Call Girl Number in Khar Mumbai📲 9892124323 💞 Full Night EnjoyCall Girl Number in Khar Mumbai📲 9892124323 💞 Full Night Enjoy
Call Girl Number in Khar Mumbai📲 9892124323 💞 Full Night EnjoyPooja Nehwal
 
OSCamp Kubernetes 2024 | A Tester's Guide to CI_CD as an Automated Quality Co...
OSCamp Kubernetes 2024 | A Tester's Guide to CI_CD as an Automated Quality Co...OSCamp Kubernetes 2024 | A Tester's Guide to CI_CD as an Automated Quality Co...
OSCamp Kubernetes 2024 | A Tester's Guide to CI_CD as an Automated Quality Co...NETWAYS
 
CTAC 2024 Valencia - Henrik Hanke - Reduce to the max - slideshare.pdf
CTAC 2024 Valencia - Henrik Hanke - Reduce to the max - slideshare.pdfCTAC 2024 Valencia - Henrik Hanke - Reduce to the max - slideshare.pdf
CTAC 2024 Valencia - Henrik Hanke - Reduce to the max - slideshare.pdfhenrik385807
 
CTAC 2024 Valencia - Sven Zoelle - Most Crucial Invest to Digitalisation_slid...
CTAC 2024 Valencia - Sven Zoelle - Most Crucial Invest to Digitalisation_slid...CTAC 2024 Valencia - Sven Zoelle - Most Crucial Invest to Digitalisation_slid...
CTAC 2024 Valencia - Sven Zoelle - Most Crucial Invest to Digitalisation_slid...henrik385807
 
SaaStr Workshop Wednesday w: Jason Lemkin, SaaStr
SaaStr Workshop Wednesday w: Jason Lemkin, SaaStrSaaStr Workshop Wednesday w: Jason Lemkin, SaaStr
SaaStr Workshop Wednesday w: Jason Lemkin, SaaStrsaastr
 
Microsoft Copilot AI for Everyone - created by AI
Microsoft Copilot AI for Everyone - created by AIMicrosoft Copilot AI for Everyone - created by AI
Microsoft Copilot AI for Everyone - created by AITatiana Gurgel
 
Russian Call Girls in Kolkata Vaishnavi 🤌 8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Vaishnavi 🤌  8250192130 🚀 Vip Call Girls KolkataRussian Call Girls in Kolkata Vaishnavi 🤌  8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Vaishnavi 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 
Exploring protein-protein interactions by Weak Affinity Chromatography (WAC) ...
Exploring protein-protein interactions by Weak Affinity Chromatography (WAC) ...Exploring protein-protein interactions by Weak Affinity Chromatography (WAC) ...
Exploring protein-protein interactions by Weak Affinity Chromatography (WAC) ...Salam Al-Karadaghi
 
ANCHORING SCRIPT FOR A CULTURAL EVENT.docx
ANCHORING SCRIPT FOR A CULTURAL EVENT.docxANCHORING SCRIPT FOR A CULTURAL EVENT.docx
ANCHORING SCRIPT FOR A CULTURAL EVENT.docxNikitaBankoti2
 
Thirunelveli call girls Tamil escorts 7877702510
Thirunelveli call girls Tamil escorts 7877702510Thirunelveli call girls Tamil escorts 7877702510
Thirunelveli call girls Tamil escorts 7877702510Vipesco
 
Governance and Nation-Building in Nigeria: Some Reflections on Options for Po...
Governance and Nation-Building in Nigeria: Some Reflections on Options for Po...Governance and Nation-Building in Nigeria: Some Reflections on Options for Po...
Governance and Nation-Building in Nigeria: Some Reflections on Options for Po...Kayode Fayemi
 
Andrés Ramírez Gossler, Facundo Schinnea - eCommerce Day Chile 2024
Andrés Ramírez Gossler, Facundo Schinnea - eCommerce Day Chile 2024Andrés Ramírez Gossler, Facundo Schinnea - eCommerce Day Chile 2024
Andrés Ramírez Gossler, Facundo Schinnea - eCommerce Day Chile 2024eCommerce Institute
 

Recently uploaded (20)

George Lever - eCommerce Day Chile 2024
George Lever -  eCommerce Day Chile 2024George Lever -  eCommerce Day Chile 2024
George Lever - eCommerce Day Chile 2024
 
Open Source Strategy in Logistics 2015_Henrik Hankedvz-d-nl-log-conference.pdf
Open Source Strategy in Logistics 2015_Henrik Hankedvz-d-nl-log-conference.pdfOpen Source Strategy in Logistics 2015_Henrik Hankedvz-d-nl-log-conference.pdf
Open Source Strategy in Logistics 2015_Henrik Hankedvz-d-nl-log-conference.pdf
 
Call Girls in Sarojini Nagar Market Delhi 💯 Call Us 🔝8264348440🔝
Call Girls in Sarojini Nagar Market Delhi 💯 Call Us 🔝8264348440🔝Call Girls in Sarojini Nagar Market Delhi 💯 Call Us 🔝8264348440🔝
Call Girls in Sarojini Nagar Market Delhi 💯 Call Us 🔝8264348440🔝
 
Re-membering the Bard: Revisiting The Compleat Wrks of Wllm Shkspr (Abridged)...
Re-membering the Bard: Revisiting The Compleat Wrks of Wllm Shkspr (Abridged)...Re-membering the Bard: Revisiting The Compleat Wrks of Wllm Shkspr (Abridged)...
Re-membering the Bard: Revisiting The Compleat Wrks of Wllm Shkspr (Abridged)...
 
BDSM⚡Call Girls in Sector 93 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 93 Noida Escorts >༒8448380779 Escort ServiceBDSM⚡Call Girls in Sector 93 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 93 Noida Escorts >༒8448380779 Escort Service
 
VVIP Call Girls Nalasopara : 9892124323, Call Girls in Nalasopara Services
VVIP Call Girls Nalasopara : 9892124323, Call Girls in Nalasopara ServicesVVIP Call Girls Nalasopara : 9892124323, Call Girls in Nalasopara Services
VVIP Call Girls Nalasopara : 9892124323, Call Girls in Nalasopara Services
 
Night 7k Call Girls Noida Sector 128 Call Me: 8448380779
Night 7k Call Girls Noida Sector 128 Call Me: 8448380779Night 7k Call Girls Noida Sector 128 Call Me: 8448380779
Night 7k Call Girls Noida Sector 128 Call Me: 8448380779
 
Introduction to Prompt Engineering (Focusing on ChatGPT)
Introduction to Prompt Engineering (Focusing on ChatGPT)Introduction to Prompt Engineering (Focusing on ChatGPT)
Introduction to Prompt Engineering (Focusing on ChatGPT)
 
Call Girl Number in Khar Mumbai📲 9892124323 💞 Full Night Enjoy
Call Girl Number in Khar Mumbai📲 9892124323 💞 Full Night EnjoyCall Girl Number in Khar Mumbai📲 9892124323 💞 Full Night Enjoy
Call Girl Number in Khar Mumbai📲 9892124323 💞 Full Night Enjoy
 
OSCamp Kubernetes 2024 | A Tester's Guide to CI_CD as an Automated Quality Co...
OSCamp Kubernetes 2024 | A Tester's Guide to CI_CD as an Automated Quality Co...OSCamp Kubernetes 2024 | A Tester's Guide to CI_CD as an Automated Quality Co...
OSCamp Kubernetes 2024 | A Tester's Guide to CI_CD as an Automated Quality Co...
 
CTAC 2024 Valencia - Henrik Hanke - Reduce to the max - slideshare.pdf
CTAC 2024 Valencia - Henrik Hanke - Reduce to the max - slideshare.pdfCTAC 2024 Valencia - Henrik Hanke - Reduce to the max - slideshare.pdf
CTAC 2024 Valencia - Henrik Hanke - Reduce to the max - slideshare.pdf
 
CTAC 2024 Valencia - Sven Zoelle - Most Crucial Invest to Digitalisation_slid...
CTAC 2024 Valencia - Sven Zoelle - Most Crucial Invest to Digitalisation_slid...CTAC 2024 Valencia - Sven Zoelle - Most Crucial Invest to Digitalisation_slid...
CTAC 2024 Valencia - Sven Zoelle - Most Crucial Invest to Digitalisation_slid...
 
SaaStr Workshop Wednesday w: Jason Lemkin, SaaStr
SaaStr Workshop Wednesday w: Jason Lemkin, SaaStrSaaStr Workshop Wednesday w: Jason Lemkin, SaaStr
SaaStr Workshop Wednesday w: Jason Lemkin, SaaStr
 
Microsoft Copilot AI for Everyone - created by AI
Microsoft Copilot AI for Everyone - created by AIMicrosoft Copilot AI for Everyone - created by AI
Microsoft Copilot AI for Everyone - created by AI
 
Russian Call Girls in Kolkata Vaishnavi 🤌 8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Vaishnavi 🤌  8250192130 🚀 Vip Call Girls KolkataRussian Call Girls in Kolkata Vaishnavi 🤌  8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Vaishnavi 🤌 8250192130 🚀 Vip Call Girls Kolkata
 
Exploring protein-protein interactions by Weak Affinity Chromatography (WAC) ...
Exploring protein-protein interactions by Weak Affinity Chromatography (WAC) ...Exploring protein-protein interactions by Weak Affinity Chromatography (WAC) ...
Exploring protein-protein interactions by Weak Affinity Chromatography (WAC) ...
 
ANCHORING SCRIPT FOR A CULTURAL EVENT.docx
ANCHORING SCRIPT FOR A CULTURAL EVENT.docxANCHORING SCRIPT FOR A CULTURAL EVENT.docx
ANCHORING SCRIPT FOR A CULTURAL EVENT.docx
 
Thirunelveli call girls Tamil escorts 7877702510
Thirunelveli call girls Tamil escorts 7877702510Thirunelveli call girls Tamil escorts 7877702510
Thirunelveli call girls Tamil escorts 7877702510
 
Governance and Nation-Building in Nigeria: Some Reflections on Options for Po...
Governance and Nation-Building in Nigeria: Some Reflections on Options for Po...Governance and Nation-Building in Nigeria: Some Reflections on Options for Po...
Governance and Nation-Building in Nigeria: Some Reflections on Options for Po...
 
Andrés Ramírez Gossler, Facundo Schinnea - eCommerce Day Chile 2024
Andrés Ramírez Gossler, Facundo Schinnea - eCommerce Day Chile 2024Andrés Ramírez Gossler, Facundo Schinnea - eCommerce Day Chile 2024
Andrés Ramírez Gossler, Facundo Schinnea - eCommerce Day Chile 2024
 

Python programming

  • 2. Python • A readable • Dynamic • pleasant • Flexible • Fast and powerful language
  • 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
  • 13. Development Environments 1. PyDev with Eclipse 2. Komodo 3. Emacs 4. Vim 5. TextMate 6. Gedit 7. Idle 8. PIDA (Linux)(VIM Based) 9. NotePad++ (Windows) 10.BlueFish (Linux) 11. Geany 12. Python Interactive Shell
  • 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
  • 18. Python Tokens • Operators Categories : Arithmetic Operator Assignment Operator Comparison Operator Logical Operator Bitwise Operator Identity Operator Membership Operator
  • 19. Python Operators Arithmetic Operators + - * % / • Assignment Operators = += -= *=
  • 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))
  • 30. Some String Functions • find() name="Ganesh Bhosale" print (name.find("esh")) • replace() str=name.replace("Ganesh","Manish") print (str) • split() str="Ganesh,Balaji,Bhosale" print (str) str2=str.split(',') print (str2) - ['Ganesh', 'Balaji', 'Bhosale’]
  • 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]
  • 36. Built-in Functions on list • len(list) • max(list) • min(list • list(seq)
  • 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
  • 49. Declaration 1: mydata={1:”Ganesh”, 2:”Manish”, 3:”Nilesh”} print (mydata[2]) Declaration 2: mydata={name:”Johny”,1:[1,2,3]} print (mydata[1])
  • 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.
  • 51. • my_name_dict = {'name’:’Ganesh', 'age’: 48} • update value my_name_dict['age'] = 47 print(my_name_dict) • add item my_name_dict['address'] = ‘Pune’ print(my_dict)
  • 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)
  • 61. Python Set - Difference print (myset1 - myset2) print (myset2 – myset1)
  • 62. Flow Control in Python
  • 63. • If – else • Nested if-else • for • while • break • continue
  • 64. If-else flow control • Syntax if <condition> : statements else: statements
  • 65. Nested if-else • Syntax if (condition): statements1 elif (condition) : statements2 else statement3
  • 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")
  • 76. Ex2 : def add_numbers(n1,n2) : print(n1+n2) return add_numbers(10,20) Ex3 : d:file1.py d:file2.py d:disp_numbers.py d:add_numbers.py
  • 77. Ex3: def add_f(a,y=20): return(a+y) n1=add_f(10) print("return is ",n1) n2=add_f(100,200) print("return is ",n2) Ex4 : def disp_list(list2): for var in list2: return (list2); i+=1 list1=[1,2,3,5,4,33] list3=disp_list(list1) print("List3 is ",list3)
  • 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
  • 80. • def myfunc(a,b): • return (a+b) • • z=myfunc(10,20) • print(z) • def myfunc(str,b): • return str • x=myfunc("Ganesh",20) • print(x)
  • 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.
  • 92. Lambda Notation • f = lambda x,y : 2 * x + y • l=f(3,4) • print(l)
  • 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
  • 98. import the math module import math math.pi 3.1415926535897931 math.cos(0) 1.0 math.cos(math.pi) -1.0 dir(math) ['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'hypot', 'isinf', 'isnan', 'ldexp', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'] help(math) help(math.cos)
  • 99. Ex: • 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))
  • 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
  • 111. Recall String Methods len(str) upper, lower, capitalize find strip • name = " Ganesh B Bhosale " • print(name.upper()) • print(name.lower()) • print(name.capitalize()) • print(name.lower()) • x=name.find("Bhosale") • print(x) • print(len(name)) • str=name.strip() # trim spaces • print(len(str))
  • 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
  • 131. def temp_convert(var): try: return int(var) except ValueError: print "The argument does not contain numbersn", var • # Call above function here. temp_convert("xyz")
  • 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()
  • 141. • class Puppy(object): • def __init__(self): • self.name = [] • self.color = [] • def __setitem__(self, name, color): • self.name.append(name) • self.color.append(color) • def __getitem__(self, name): • if name in self.name: • return self.color[self.name.index(name)] • else: • return None • dog = Puppy() • dog['Max'] = 'brown' • dog['Ruby'] = 'yellow' • print ("Max is", dog['Max'])
  • 142. Exercise : • 1. Create a Employee Class. • 2. Create Multiple Employee Objects and Store their Details in a file
  • 144. • Why ? • What ? • Basic Operations • Examples
  • 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
  • 146. • Regular Expressions Compatible with • Java • Ruby • C# • Groovy • PHP • Swift • Scala • Perl • Unix • Javascript • etc
  • 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())
  • 153. Searching Pattern Import re result = re.search(‘Vedics', 'GB Bhosale Vedics GB Vedics ') print(result.group(0))
  • 154. Re.findall() Import re result = re.findall('GB', 'GB Bhosale Vedics GB') print(result)
  • 155. Re.split() Import re result=re.split(r’y','Analytics') print(result) # Multiple Splits result=re.split(r’y','Analytics VidhyaVihar') print(result)
  • 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))
  • 161. Example 1 def KelvinToFahrenheit(Temp): assert (Temp >= 0),"Colder than absolute zero!" return ((Temp-273)*1.8)+32 print (KelvinToFahrenheit(27)) #print (KelvinToFahrenheit(273)) #print (int(KelvinToFahrenheit(505.78))) #print (KelvinToFahrenheit(-5))
  • 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.
  • 164. Python sqlite3 module APIs • sqlite3.connect(database [,timeout ,other optional arguments]) • connection.cursor([cursorClass]) • cursor.execute(sql [, optional parameters]) Ex :cursor.execute("insert into people values (?, ?)", (who, age)) • connection.commit() • connection.rollback() • connection.close() • cursor.fetchone() • cursor.fetchall()
  • 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()
  • 168. SELECT Operation import sqlite3 conn = sqlite3.connect('test.db') print "Opened database successfully"; cursor = conn.execute("SELECT id, name, address, salary from COMPANY") for row in cursor: print "ID = ", row[0] print "NAME = ", row[1] print "ADDRESS = ", row[2] print "SALARY = ", row[3], "n" print "Operation done successfully"; conn.close()
  • 169. UPDATE Operation import sqlite3 conn = sqlite3.connect('test.db') print "Opened database successfully"; conn.execute("UPDATE COMPANY set SALARY = 25000.00 where ID = 1") conn.commit print "Total number of rows updated :", conn.total_changes cursor = conn.execute("SELECT id, name, address, salary from COMPANY") for row in cursor: print "ID = ", row[0] print "NAME = ", row[1] print "ADDRESS = ", row[2] print "SALARY = ", row[3], "n" print "Operation done successfully"; conn.close()
  • 170. DELETE Operation import sqlite3 conn = sqlite3.connect('test.db') print "Opened database successfully"; conn.execute("DELETE from COMPANY where ID = 2;") conn.commit() print "Total number of rows deleted :", conn.total_changes cursor = conn.execute("SELECT id, name, address, salary from COMPANY") for row in cursor: print "ID = ", row[0] print "NAME = ", row[1] print "ADDRESS = ", row[2] print "SALARY = ", row[3], "n" print "Operation done successfully"; conn.close()
  • 171. • import sqlite3 • conn = sqlite3.connect('test.db') • print("Opened database successfully") • #conn.execute('''create table emp1 • # (empno int primary key, • # ename text not null, • # salary real);''') • • #print ("Table Successfully Created") • #conn.execute('Insert into emp1 values(1010,"Ganesh",4000);') • #conn.execute('Insert into emp1 values(1020,"Manish",6000);') • #conn.execute('Insert into emp1 values(1030,"Nilesh",7000);') • #conn.execute('Insert into emp1 values(1040,"Joy",45000);')
  • 172. • conn.commit() • print("Records Inserted Successfully...") • cur=conn.execute('select empno,ename,salary from emp1;') • print("EmpnottEmpNamettSalary") • fp=open("datafile.txt","w") • for row in cur: • #print(row[0],"tt",row[1],"t",row[2]) • #fp.write(str(row)+"n") • fp.write("empnot"+str(row[0])) • fp.write("tempnamet"+row[1]) • fp.write("tSalaryt"+str(row[2])) • fp.write("n") • • fp.close() • # Display all tables created in sqlite • • con = sqlite3.connect(r'test.db') • mycur = con.cursor() • mycur.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;") • available_table=(mycur.fetchall()) • print(available_table) • conn.close()
  • 173. Questions / Doubts /Message / Warnings/Suggesstions ?
  • 174. Thanks for Your Co-operation and Support