SlideShare a Scribd company logo
PYTHON
INTRODUCTION
[Type the abstract of the document here. The abstract is typically a short
summary of the contents of the document. Type the abstract of the
document here. The abstract is typically a short summary of the contents of
the document.]
Reference:
sololearn.com
PYTHON
Table of Contents
Python Introduction............................................................................................................................6
Python versions..............................................................................................................................6
Python console...............................................................................................................................6
Python functions ................................................................................................................................6
Python errors.....................................................................................................................................6
Python floats......................................................................................................................................7
Python numerical operations ..............................................................................................................7
__main__...........................................................................................................................................8
Command line arguments...................................................................................................................8
sys module.....................................................................................................................................8
getopt module................................................................................................................................9
getopt.getopt method.................................................................................................................9
Exception getopt.GetoptError......................................................................................................9
Example.................................................................................................................................10
Strings..............................................................................................................................................11
String formatting..........................................................................................................................11
String operations ..........................................................................................................................12
Variables..........................................................................................................................................12
Variable names:............................................................................................................................12
del statement...............................................................................................................................13
Special operators..............................................................................................................................13
if statements....................................................................................................................................13
elif (short form of else if)...............................................................................................................13
Boolean logic................................................................................................................................14
While loops......................................................................................................................................14
infinite loop..................................................................................................................................14
break...........................................................................................................................................14
continue.......................................................................................................................................14
operator precedence........................................................................................................................14
More on else statements ..................................................................................................................15
Else with loops..............................................................................................................................15
Else with try/except......................................................................................................................15
Lists.................................................................................................................................................15
Empty list.....................................................................................................................................16
Nested lists...................................................................................................................................16
Errors...........................................................................................................................................16
List operations..............................................................................................................................16
Assignment...............................................................................................................................16
Addition and Multiplication........................................................................................................16
in operator................................................................................................................................16
not operator.............................................................................................................................17
Loops........................................................................................................................................17
List slices......................................................................................................................................17
Negative indexing......................................................................................................................17
List comprehensions .....................................................................................................................18
List functions................................................................................................................................18
Sets.................................................................................................................................................19
Mathematical operations - union/intersection................................................................................19
Functions and modules.....................................................................................................................20
Arguments ...................................................................................................................................20
Return values ...............................................................................................................................21
Docstrings ....................................................................................................................................21
Modules.......................................................................................................................................21
Import certain functions............................................................................................................21
Standard Library...............................................................................................................................21
Exception Handling...........................................................................................................................22
Raising exception..........................................................................................................................23
Assertions........................................................................................................................................23
Files handling...................................................................................................................................23
Opening files - open()....................................................................................................................23
Reading Files - read().....................................................................................................................24
Writing Files - write().....................................................................................................................24
with statement.............................................................................................................................24
None................................................................................................................................................25
Dictionaries......................................................................................................................................25
Dictionary Functions .....................................................................................................................26
Search......................................................................................................................................26
get() .........................................................................................................................................26
Tuples..............................................................................................................................................26
Tuple unpacking...........................................................................................................................26
Variable*......................................................................................................................................27
Ternary operator..............................................................................................................................27
Higher order functions......................................................................................................................27
Lambdas.......................................................................................................................................27
map and filter...............................................................................................................................28
Generators.......................................................................................................................................28
Decorators.......................................................................................................................................29
Object Oriented Programming...........................................................................................................30
Classes.........................................................................................................................................30
__init__........................................................................................................................................30
Methods ......................................................................................................................................30
Inheritance...................................................................................................................................30
Super function..............................................................................................................................31
Magic Methods.............................................................................................................................31
Operator overloading....................................................................................................................31
Object Lifecycle ............................................................................................................................31
Garbage collection........................................................................................................................32
Data Hiding..................................................................................................................................32
Class methods ..............................................................................................................................32
Static methods..........................................................................................................................32
Properties ....................................................................................................................................33
Regular Expressions..........................................................................................................................34
Matching pattern..........................................................................................................................34
re.search()....................................................................................................................................34
re.sub() - search & replace.............................................................................................................35
Metacharacters ............................................................................................................................35
. (dot) character........................................................................................................................35
^ and $ - start and end...............................................................................................................35
Character classes..........................................................................................................................35
^ character................................................................................................................................36
More Metacharacters ...................................................................................................................36
* character................................................................................................................................36
+ character................................................................................................................................36
? character................................................................................................................................36
Curly braces..............................................................................................................................36
Groups.........................................................................................................................................36
| character................................................................................................................................37
Named groups...........................................................................................................................37
Special Sequences ............................................................................................................................37
number - Backslash .....................................................................................................................37
d and D sequence.......................................................................................................................38
s and S sequence........................................................................................................................38
w and W sequence.....................................................................................................................38
A Sequence.................................................................................................................................38
b sequence .................................................................................................................................38
Email extraction ...............................................................................................................................38
Pythonicness & Packaging.................................................................................................................39
PEP- Python Enhancement Proposals.................................................................................................39
Packaging.........................................................................................................................................39
Setup.py.......................................................................................................................................40
Packaging for Users.......................................................................................................................40
Function arguments..........................................................................................................................40
*args............................................................................................................................................40
**kwargs – keyword arguments ....................................................................................................41
Major 3rd
party libraries ....................................................................................................................41
Django.........................................................................................................................................41
CherryPy and Flask........................................................................................................................41
BeautifulSoup...............................................................................................................................41
Matplotlib....................................................................................................................................41
NumPy.........................................................................................................................................41
SciPy............................................................................................................................................42
Panda3D ......................................................................................................................................42
List Vs Dictionary Vs TuplesVs Sets....................................................................................................42
itertools - standard library.................................................................................................................43
Python Vs C......................................................................................................................................43
Web scraping: webbrowser library ....................................................................................................44
Webbrowser.open()......................................................................................................................44
webbrowser.open_new(url)..........................................................................................................44
webbrowser.open_new_tab(url) ...................................................................................................44
webbrowser.get([name])...............................................................................................................44
Python !!!
PythonIntroduction
Pythonisa highlevel programminglanguagelikeC/C++/Javaetc.,itsapplicationsincludingweb
programming,scripting,scientificcomputingandartificial intelligence.
pythonisprocessedatruntime bythe interpreter.Noneedto compile pythonprogramsbefore
executingthemunlikeCprograms,where compilationstepismandatorybeforeexecutingit.
An Interpreterisaprogramthat runs scriptswritteninan interpretedlanguage suchasPython.
Pythonsource fileshave anextensionof .py
Python versions
There are three majorversionsof pythonwhichare 1.x,2.x and3.x. Both2.x and 3.x are currentlyused.
Python console
The pythonconsole isa program that allowsyouto enterone line of pythoncode,repeatedlyexecutes
that line,anddisplaysthe output.Thisisknownasa REPL - Read-Eval-Print-Loop.
To close a console,type inquit() orexit() andpressenter.
Pythonfunctions
Pythonfunction Usage
print("Hello") orprint('Hello') Printsthe message,producesthe output
quit() orexit() Close the console
input("Entersomethingplease:") Promptsthe use for input,andreturnswhatthey
enteras a stringwithcontentsautomatically
escaped.
Enter somethingplease:userentersncharacter!
o/p-> userentersncharacter!
int() Convertsgivennumberinstringformattointeger
int("2") + int("3") = 5
Similarlyfloat() andstr()
del variable_name del statementusedtoremove avariable from
program.
Pythonerrors
Type of error Example
ZeroDivisionError:divisionbyzero 11 / 0
TypeError:unsupportedoperandtype(s) 1 + "2"
For +:'int' and 'str'
TypeError:can't multiplysequence bynon-intof
type 'str' or 'float'
"s" * "s"
9.0 * "r"
SyntaxError:invalidsyntax >>>123abc = 7
1. When variable namesdon'tfollowrules.
2. When programuses++ or -- operators.
NameError:name 'var_name" is notdefined Whenprogram triestoaccess undefinedvariable
or a functionwhichisnotdefined
In Lists:
IndexError:
whentry toaccess out of boundvalues.
things="hai"
print(things[4])
In Lists:
TypeError:
whentry toaccess integerorfloat typesusing
index.
Num= 123
print(Num(2))
In Lists:
ValueError:
If the itemisnotin the listand tryingto getits
index.
ImportError Whentryingto access unavailablemodule
KeyError Tryingto index akeythat isn'tpart of the
dictionaryreturnsaKeyError.
Dictionary'sTypeError Whenmutable objectsare usedaskeys
RuntimeError:maximumrecursiondepth
exceeded
Oftenoccur whenforgottoimplementthe base
case of resusion.
AttributeError Tryingto access an attribute of an instance the
isn'tdefinedcausesthiserror.
Pythonfloats
A floatcan be addedto an integerbecause Pythonsilentlyconvertsthe integertoa float.However,this
implicitconversionisthe exceptionratherthanthe rule inPython.Youhave to convertvaluesmanually
if you wantto operate onthem.
Pythonnumerical operations
Operator Usage
+ , - , * , / Addition,subtraction,multiplication,division
1 + 2 = 3
1 + 2.2 = 3.2
2 * 3 = 6
2 * 3.2 = 6.4
4/2 = 2.0
5/2 = 2.5
** Exponentiation
2**5 = 32
9**(1/2) = 3.0
// Quotient(Floordivision)
20//6 = 3
% Remainder(modulooperator)
1.25%0.5 = 0.25
Inplace operators
+= , -=, *=, %= and /=
a += 3 -> a = a + 3
__main__
Whena pythoninterpreterreadsasource file,itexecutesall of the code itfindsinthe file. Before
executingthe code,itdefinesafewspecial variables.
For example,if the pythoninterpreterisrunningthatmodule (source file) asthe mainprogram, itsets
the special __name__ variable tohave avalue “__main__”. If the file beingimportedfromanother
module, __name__ will be settothe module’sname.
If __name__ == “__main__”:
print(“Thisisascript”)
else
print(“Imported”)
Commandline arguments
sys module
The Python sys module providesaccesstoany command-lineargumentsviathe sys.argv.Thisserves
twopurposes−
 sys.argvisthe listof command-linearguments.
 len(sys.argv) isthe numberof command-linearguments.
Here sys.argv[0] isthe program ie.scriptname.
Consider the following script test.py −
#!/usr/bin/python
import sys
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
Now run above script as follows −
$ python test.py arg1 arg2 arg3
This produce following result −
Number of arguments: 4 arguments.
Argument List: ['test.py', 'arg1', 'arg2', 'arg3']
getopt module
Pythonprovidesagetoptmodule thathelpsyouparse command-lineoptionsandarguments.
Pythonprovidedagetoptmodule thathelpsyouparse command-lineoptionsandarguments.This
module providestwofunctionsandan exceptiontoenablecommandline argumentparsing.
getopt.getoptmethod
Thismethodparsescommandline optionsandparameterlist.Followingissimple syntaxforthismethod
−
getopt.getopt(args,options,[long_options])
Here is the detail of the parameters−
 args: Thisisthe argumentlistto be parsed.
 options:This isthe stringof optionlettersthatthe scriptwantsto recognize,withoptionsthat
require anargumentshouldbe followedbyacolon(:).
 long_options:Thisis optional parameterandif specified,mustbe alistof stringswiththe
namesof the longoptions,whichshouldbe supported.Longoptions,whichrequire an
argumentshouldbe followedbyanequal sign('=').To accept onlylongoptions,optionsshould
be an emptystring.
 Thismethodreturnsvalue consistingof twoelements:the firstisalistof (option,value) pairs.
The secondis the listof program argumentsleftafterthe optionlistwasstripped.
 Each option-and-valuepairreturnedhasthe optionasitsfirstelement,prefixed withahyphen
for shortoptions(e.g.,'-x') ortwohyphensforlongoptions(e.g.,'--long-option').
Exceptiongetopt.GetoptError
Thisis raisedwhenanunrecognizedoptionisfoundinthe argumentlistorwhenanoptionrequiringan
argumentisgivennone.
The argumentto the exceptionisastringindicatingthe cause of the error. The attributesmsgandopt
give the errormessage andrelatedoption.
Example
Consider we want to pass two file names through command line and we
also want to give an option to check the usage of the script. Usage of the
script is as follows −
usage: test.py -i <inputfile> -o <outputfile>
Here is the following script to test.py −
#!/usr/bin/python
import sys, getopt
def main(argv):
inputfile = ''
outputfile = ''
try:
opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
except getopt.GetoptError:
print 'test.py -i <inputfile> -o <outputfile>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'test.py -i <inputfile> -o <outputfile>'
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
print 'Input file is "', inputfile
print 'Output file is "', outputfile
if __name__ == "__main__":
main(sys.argv[1:])
Now, run above script as follows −
$ test.py -h
usage: test.py -i <inputfile> -o <outputfile>
$ test.py -i BMP -o
usage: test.py -i <inputfile> -o <outputfile>
$ test.py -i inputfile
Input file is " inputfile
Output file is "
Strings
A stringiscreatedby enteringtextbetweentwosingle ordouble quotationmarks.
-> 'HelloWorld'or "HelloWorld"
Some characters can't be includedinstringdirectly,example of these charactersare single quoteand
double quotes,tabs, arbitraryunicode characters.
Put a backslashbefore these charactersif youaddthese special charactersinyourstring.
"Ram's brothername is "Raj""-->Ram's brothername is Raj
n - representsnew line.
String formatting
Providesamore powerful waytoembednon-stringswithinstrings.
Stringformattingusesastring's format methodtosubstitute anumberof argumentsinthe string.
nums= [4, 5, 6]
msg = "Numbers:{0} {1} {2}".format(nums[0],nums[2],nums[3])
print(msg) -> Numbers:4 5 6
Stringformattingcan alsobe done withnamedargumets.
a = "{x},{y}".format(x=5,y=12)
print(a) -> 5, 12
String operations
Concatenation "spam"+"eggs"= spameggs
"spam"+","+"eggs"= spam,eggs
"2"+"2" = 22
1 + "2" = TypeError(ReferPythonerrorstable)
Multiplication "spam"*3 = spamspamspam
4 * "3" = 3333
"s" * "r" = TypeError
"s" * 7.0 = TypeError
Replace "hellome".replace("me","world") ->helloworld
Startswith "Thisis car".startswith("This") ->True
Endswith
Upper() "I am a boy".upper() ->I AM A BOY
Lower()
Split() "spam, eggs,ham".split(",")
Variables
In python,variablesdon'thave specifictypes,soyoucan assigna stringto a variable,andlaterassignan
integertothe same variable.
>>> a = 100
>>>print(a)
100
>>>a = "Raj"
>>>print(a)
'Raj'
Variable names:
The onlycharacters that are allowedare letter,numbersandunderscores.Also,theycan'tstart with
numbers.
NotfollowingtheserulesresultsinSyntaxErrorerror.
Pythonisa case sensitiveprogramminglanguage.Thus,Lastname andlastname are twodifferent
variable namesinPython.
Tryingto reference avariable thathasnot assignedinthe programcausesan error (NameError).
>>>a = "raj"
>>>a
raj
>>>b
NameError:name 'b' isnot defined.
>>>del a
del statement
del statementusedtoremove avariable fromprogram.
Special operators
Pythondoesn'tsupportspecial operators++and --.But,it supportsinplace operators(referoperation
table above)
Interpreterthrowssyntax errorif programuses++ or -- operators.
Example: File "./prog.py", line 12
a++
^
SyntaxError: invalid syntax
if statements
use if statementstorun code whencertainconditionholds.
if expression:
statements
Pythonusesindentation(white spacesatthe beginningof aline) todelimitblocksof code.Other
languages,suchas,C, use curlybraces to accomplishthis.But,inPythonindentationismandatory;
program won'tworkwithoutit.Asyou can see,the statementsinthe if shouldbe indented.
elif (short form of else if)
the elif (shortforelse if) statementisashortcutto use whenchainingif andelse statements.
if expression:
statement
else:
if expression:
statement
can be modifiedasbelow
if expression:
statement
elif expression:
statement
Boolean logic
Booleanlogicisusedtomake more complicatedconditionsfor itstatementsthatrelyon more than one
condition.
Python'sBooleanoperatorsare and,or, andnot.
While loops
while condition:
statement1
statement2
infinite loop
while 1==1:
print("inthe loop")
break
To enda while loopprematurely,the breakstatementcanbe used.
i = 0
while 1==1:
print(i)
i = i +1
if i >= 5:
printf("breaking")
break
continue
Unlike break, continue jumpsbackto the top of the loop,ratherthan stoppingit.
operator precedence
== has higherprecedencethan or.
Python'sorderof operationsisthe same as that of normal mathematics.
the followingtable listsall of Python'soperators,fromhighestprecedence tolowest.
Operator Description
** Exponentiation
~ + - Complement,unaryplus/minus
* / %// Multiplication,division.moduloandfloordivision
+ - Addition/subtraction
>> << Rightand leftbitwise shift
& Bitwise AND
^ | Bitwise exclusive ORandregularOR
<= < > >= Comparisons
= %= /= //= -= += *= **= Assignmentoperators
isis not Identityoperators
innot in Membershipoperator
not or and Logical operators
More on else statements
Else with loops
Usingelse withforand while loops,the code withinit iscalledif the loopfinishednormally(whena
breakstatementdoesn’tcause anexitfromthe loop)
For I inrange(10):
if (i==999):
break
Else:
print(“Unbroken”)
Else with try/except
The else statementcanalsobe usedwithtry/exceptstatements.In thiscase,the code withinitisonly
executedif noerroroccurs inthe try statement.
Try:
print(1)
exceptZeroDivisionError:
print(2)
else:
print(3)
o/P:
1
3
Lists
Listsare one type of objectin Python.Theyare usedto store an indexedlistof items.
A listiscreatedusing square brackets withcommas separatingitems.Iteminthe listcanbe accessesby
usingitsindex insquare brackets. A comma can be placedafterlastitemalso,itsvalidonly.
words= ["Hello","world","!"]
print(words[0])
print(words[1])
print(words[2])
Empty list
An emptylistiscreatedwithanemptypairof square brackets.
empty_list=[]
print(empty_list) -->o/p:[]
Nested lists
Listscan alsoinclude differentitemtypesandalsobe nestedwithinotherlists.
num= 3
things= ["string",0, [1, 2, num],4.56]
print(things[1])
print(things[2])
print(things[2][2])
Errors
IndexError:whentryto accessout of boundvalues.print(things[4])
TypeError:whentry to accessintegerorfloat typesusingindex.
No errorwill be seenforstringtype.Example,str="Helloworld",print(str[0]),o/P:H
List operations
Assignment
The itemat certainindex ina listcan be reassigned.
AdditionandMultiplication
Listscan be addedandmultipliesinthe same wayas strings
nums= [1, 2, 3]
print(nums+[4, 5, 6]) -> [1,2,3,4,5,6]
print(nums*3) -> [1,2,3,1,2,3,1,2,3]
List andstringsare similarinmanyways - stringscan be thoughtof as listsof charactersthat can't be
changed.
in operator
To check if an itemisinlist,the in operatorcan be used.It returns True if the itemoccurs one or more
timesinthe list,and False if it doesn't.
words= ["spam","eggs","spam","sause"]
print("spam"inwords) ->True
print("tomo"inwords) ->False
The in operatoris alsousedto determinewhetherornota string issubstringof anotherstring.
not operator
To check if an itemisnot ina list.
print(not4 innums) -> True
print(4not innums) -> True
Loops
words= ["hello","world","spam"]
for wordinwords:
print(word)
o/p:
hello
world
spam
for i in range(3):
print("hi")
o/p:hi hi hi
List slices
Providesmore advancedwayof retrievingvaluesfromalist.
if the firstnumberina slice isomitted,itistakentobe the start of the list.If the 2nd numberisomitted,
it istakento be the end.
squares= [0, 1, 4, 9, 16, 25]
print(squares[1:4]) ->[1, 4, 9]
print(squares[0:1]) ->[0]
print(squares[:3]) ->[0, 1, 4]
print(squares[4:]) ->[16, 25]
List slicescanalsohave a 3rd number,representingthe step,toinclude onlyalternate valuesinthe slice.
print(squares[2:5:2]) ->[4, 16]
Negativeindexing
Negative valuescanbe usedinlistslicing(andnormal listindexing).
Whennegative valuesare usedforthe firstand2nd values ina slice (ora normal index),they count
fromthe endof the list.
print(squares[1:-1]) ->[1, 4, 9, 16]
If Negative value isusedforthe step,the slice isdone backwards.Using[ : : -1] as slice isa commonand
idiomaticwaytoreverse alist.
List comprehensions
List comprehensionsare auseful wayof quicklycreatinglistswhose contentsobeyasimple rule.
cubes= [i**3 fori in range(5)]
print(cubes) ->[0, 1, 8, 27, 64]
A listcomprehensioncanalsocontainan if statementtoenforce aconditiononvaluesinthe list.
evens= [i**2 for i in range(10) if i**2 %2 == 0]
print(evens) -->[0,4, 16, 36, 64]
Tryingto create a listina veryextensive range willresultina MemoryError.
even= [2*i fori in range(10**1000)] -> MemoryError.
Thisissue issolvedby generators.
List functions
Function Description
list.append(item):isamethodof listclass and
hence can be accessedusing dot before.
Addsan itemto the endof an existinglist.
Nums= [1, 2, 3]
Nums.append(4)
Print(nums) ->[1, 2, 3, 4]
len() Get the numberof itemsina list.
print(len(nums)) ->4
list.insert(index,item) Allowstoinsertanew itemat any positioninthe
list.
Nums.insert(1, 10)
print(nums) ->[1,10, 2, 3, 4]
list.index(item) Findsthe firstoccurrence of a listitemandreturns
thisindex.
If the itemisn'tinthe list,itraisesa ValueError.
print(nums.index(10)) ->1
print(nums.index(20)) ->ValueError:20is notin
the list
max(list) Returnsthe listitemwiththe maximumvalue
min(list) Returnsthe listitemwiththe minimumvalue
list.count(item) Returnsa count of how manytimesanitemoccurs
ina list.
list.remove(item) Removesanitemfroma list
list.reverse() Reversesitemsinlist
list(range(count)):Createsa sequential listof Nums= list(range(5))
numbers.range byitself createsarange object,
and thismustbe convertedtoa list.
print(nums) ->[0,1, 2, 3, 4]
list(range(first,end)):Producesalistfromthe first
to the end
Nums= list(range(2,7))
print(nums) ->[2,3, 4, 5, 6]
list(range(first,end,interval)) Nums= list(range(2,7,2))
print(nums) ->[2,4, 6]
all and any Take a listas argumentandreturnTrue if all or any
(respectively) of theirargumentsevaluatetoTrue.
Nums= [55, 44, 33]
If all([i>5fori innums]):
print("all are largerthan5")
If any([i%2== 0 for i in nums]):
Print("atleastone iseven")
Enumerate() Usedto iterate throughthe valuesandindicesof
listsimultaneously.
For v inenumerate(nums):
Print(v)
o/p:(0, 55)
(1, 44)
(2, 33)
Sets
Setsare data structures,similartolistsordictionaries.
Theyare createdusingcurlybraces,or the set function.
num_set= {1, 2, 3, 4}
word_set= set(["spam","eggs"])
print(3innum_set) -> True
print("spam"notinword_set) -> False
To create an emptyset,youmust use set(),as{} createsan emptydictionary.
Setsare unordered,whichmeansthattheycan'tbe indexed.
Theycannot containduplicate elements.Due tothe waytheyare stored,itsfasterto check whetheran
itemispart of a set,ratherthan part of a list.
Insteadof usingappend() toadd to a set,use add()
The methodremove() removesaspecificelementfromaset, pop() removesanarbitraryelement.
Mathematical operations - union/intersection
Setscan be combinedusingmathematical operations.
unionoperator|
intersectionoperator&
difference operator-
symmetricdifference operator^
first= {1, 2, 3, 4}
sec = {4, 5, 6}
print(first|sec) -> {1, 2, 3, 4, 5, 6}
print(first&sec) -> {4}
print(first-sec) -> {1, 2, 3}
print(first^sec) -> {1, 2, 3, 5, 6}
Functions and modules
create a functionbyusingthe def statementandmustbe definedbefore theyare called,elseyouwould
see NameError.
Functionscanbe assignedandreassignedtovariablesandlaterreferencedby those values
def my_func():
print("Iamin function")
my_func()
func2 = my_func()
func2()
Arguments
Functionscanalso be usedas argumentsof otherfunctions
def my_func(word):
print(word+ "!")
my_func("Hello")
def sum(x,y):
print(x+y)
sum(5, 8)
def add(x,y):
returnx+y
def do_twice(func,x,y):
returnfunc(func(x,y),func(x,y))
a = 5
b = 10
print(do_twice(add,a,b)
Return values
def max(x,y):
if x >= y:
returnx
else:
returny
z = max(8,5)
print(z)
Docstrings
Unlike conventional comments,docstringsare retainedthroughoutthe runtime of the program.This
allowsthe programmedtoinspectthese commentsatruntime.
Modules
Modulesare piecesof code that otherpeople have writtentofulfill commontasks,suchasgenerating
randomnumbersetc.
Tryingto importa module thatisn'tavailable causesanImportError.
Usage: addimport module_name at the top of yourcode.And,access functions/variable using
module_name.var
Example:
importrandom
for i in range(5):
val = random.randint(1, 6)
print(val)
Import certainfunctions
from module_name import var
for mathimportpi
print(pi)
for mathimportpi,sqrt
print(sqrt(25))
Importa module underadifferentname using askeyword
frommath importsqrt as square_root
print(square_root(100))
Standard Library
3 typesof modules
1. those you write yourself
2. those you install fromexternal sources
3. those are pre-installedwithpython -->Standardlibrary
Tasks that can be done by usingstandardlibraryinclude
stringparsing
data serialization
testing|debugging
manipulatingdates,emails
commandline argumentsandsoon.
Python'sextensive standardlibraryisone of itsmainstrengthsasa language.
ExceptionHandling
Exceptionsoccurwhensomethinggoeswrong,due toincorrectcode orinput.
Whenan exceptionoccurs,the programimmediatelystops.
Handle exceptions:use tryand exceptstatements. Useful whendealingwithuserinput.
The try blockcontainscode that mightthrow an exception.If thatexceptionoccurs,the code inthe try
blockstopsbeingexecuted,andthe code inthe exceptblockis run.If noerror occurs, the code in the
exceptblockdoesn'trun.
try:
num1 = 7
num2 = 0
print(num1/num2)
exceptZeroDivisionError:
print("Anerroroccurreddue to zerodivision")
except(ValueError,TypeError):
print("Erroroccurred")
An exceptstatementwithoutanyexceptionspecifiedwill catchall errors.
try:
print(7/0)
except:
print("erroroccurred")
finally:
print("Thiscode will runnomatterswhat")
The finallystatementalwaysrunsaftertry/exceptblocksevenincase of exception.
Raising exception
raise statementcanbe usedto raise exceptionandspecifythe type of exceptionraised. Youcanpass
argumentfordetails.
print(1)
raise ValueError
print(2)
raise NameError("Invalidname found")
Assertions
An Assertionisasanity-checkthatyoucan turnon or turn off whenyouhave finishedtestingthe
program.
An expression istested,andif the resultcomesupfalse,andexceptionisraised.
Programmers oftenplace assertionsatthe start of a functiontocheckfor validinput,andaftera
functioncall tocheck forvalidoutput.
print(1)
assert2 + 2 == 4
print(2)
assert1 + 1 == 3
print(3)
o/p:
1
2
AssertionError
The assert can take a secondsargument thatis passedtothe AssertionErrorraisedif the assertionfails.
temp= -10
assert(temp>= 0),"Colderthanabsolute Zero!"
o/p:AssertionError:Colderthanabsolute zero!
Files handling
Opening files - open()
myfle =open("filename.txt")
The argumentof the open() functionisthe pathto the file. Youcan specifythe mode usedtoopena file
by 2nd argument.
r : Openfile inreadmode,whichisthe default.
w : Write mode,forre-writingthe contentsof the file
a : Appendmode,foraddingnewcontent tothe endof the file
b : Openfile ina binarymode,usedfornon-textfiles(image/soundfiles)
myfile =open("filename.txt","a");
myfile.close()
Reading Files - read()
cont = myfile.read()
print(cont) ->will printall the contentsof the file.
Provide numberof bytesthatreadfromfile bypassingvalue tothe read()
print(myfile.read(10)) ->10 bytesread
Afterall contentsina file have beenread,anyattempttoreadfurtherfromthat file will returnan
emptystring,because youare tryingto read from the endof the file.
To retrieve eachline inafile,use readlines function.Itreturnalistin whicheachelementisaline inthe
file.
file =open("filename.txt","r")
print(file.readline())
file.close()
o/p:
['line1n','line2n','line3']
Writing Files - write()
write() - writesastringto the file. "w"mode will create afile if notexist. If exist,the contentsof the file
will be deleted.
write() returnsthe numberof byteswrittentothe file,if successful.
file =open("new.txt","w")
file.write("Writtingtothe file")
file.close()
file =open("new.txt","r")
print(file.read())
file.close()
with statement
It ismandatoryto close the file afterread/writingthe fileevenincase of exceptionoccur.
An alternative wayof doingthisisusingwithstatement.The fileisautomaticallyclosedatthe endof
the with statement,evenif exceptionoccurwithinit.
withopen("new.txt") asf:
print(f.read())
None
representsabsence of the value.
The None objectisreturnedbyany functionthatdoesn'texplicitlyreturnanythingelse.
def myfunc():
printf("Hi")
var = myfunc()
print(var)
o/p:
Hi
None
Dictionaries
Dictionariesare datastructuresusedtomap arbitrary keystovalues. {"Key":Value}.
Emptydictionaryis{}
Each elementinadictionaryisrepresentedby key:value pair
Dictionarykeyscanbe assignedtodifferentvalueslikelists.
Tryingto index akeythat isn'tpart of the dictionaryreturnsa KeyError.
primary= {
"red":[255, 0, 0],
"green":[0,255, 0],
"blue":[0,0, 255],
}
print(primary["red"]) -->[255, 0, 0]
primary["white"] =[200, 140, 100]
primary["blue"] =[0,0, 245]
print(primary["yellow"])-->KeyError:"yellow"
Dictionarycan store any type of data as Value.
Onlyimmutable objectscanbe usedas keystodictionaries.
List anddictionariesare mutable objectsandhence can'tbe usedas keysinthe dictionary.
bad_dict= {[1,2, 3]: "one twothree",}
TypeError: unhashable type:list
Dictionary Functions
Search
Use in andnot in
nums= {1: "one",2: "two",3: "three",}
print(1in nums) -> True
print(1not in nums) -> False
print(4not in nums) -> True
get()
Usedto get the valuesbyitsindex,butif the keyisnot found,itreturnsanotherspecificvalue(2nd
argument) instead(Nonebydefault).
pairs= {1: "apple","orange":[2,3], True:False,None:"True",}
print(pairs.get("orange"))->[2,3]
print(pairs.get(7)) ->None
print(pairs.get(1234,"Notfound")) ->Notfound
Tuples
Similartolists,exceptthattheyare immutable (theycan'tbe changed).Also,these are createdusing
parenthesis,ratherthansquare brackets.
words= () -> emptytuple
words= ("spam","eggs")
or
words= "spam","eggs"
Tuple unpacking
It allowsyoutoassigneach iteminan iterable toa variable.
Numbers= (1, 2 ,3)
a, b, c = numbers
print(a) ->1
print(b) ->2
Variable*
A variable thatisprefacedwithanasterisk(*) takesall valuesfromthe iterable thatare leftoverfrom
the othervariables
A,b, *c, d = [1, 2, 3, 4 ,5 ,6, 7]
print(a) -> 1
print(b) -> 2
print(c) ->[3, 4, 5, 6]
print(d) -> 7
Ternary operator
It takesthree arguments
Status= 1
msg = “Logout” if status ==1 else “Login”
print(msg) ->Logout
Higher order functions
Lambdas
Whenfunctionsare createdusing lambdasyntax thenthe functionsare notassignedtoany variable
unlike functionscreatednormallyusing def assignsittoa variable automatically.
Stringsand integerscanbe createdonthe fly,withoutassigningthemtoavariable. Similarly,functions
can be createdwithoutassigningthemtoanyvariable usinglambdakeyword.
def my_func(f,arg):
returnf(arg)
my_func(lambdax:2*x*x, 5)
Lambda functionsgettheirname fromlambdacalculus.
Lambda functionsare notpowerful asnamedfunctions.Theycanonlydothingsthatrequire asingle
expression - usuallyequivalenttoa single line of code.
#namedfunction
def polynomial(x):
returnx**2 + 5*x + 4
print(polynomial(-4))
#lambda
print(lambdax:x**2+ 5*x + 4, -4)
Lambda functionscanbe assignedtovariables, andusedlike anormal functions
double =lambdax: x * 2
print(double(4))
map and filter
map and filteroperate onlists(orsimilarobjectscalled itterables)
Maps Lambda
def add_five(x):
returnx+5
nums= [1, 2, 3, 4, 5]
result= list(map(add_five,nums))
print(result) -> [6, 7, 8, 9, 10]
Nums= [1, 2, 3, 4, 5]
result= list(map(lambdax:x+5,nums))
print(result) -> [6,7, 8, 9, 10]
The function filterfiltersaniterable byremovingitemsthatdon'tmatch a predicate
res= list(filter(lambdax:x%2==0, nums))
print(res) -> [2, 4]
Generators
Generatorsare a type of iterable,likelistsortuples.
Unlike lists,theydon'tallowindexingwitharbitraryindices,buttheycanstill be iteratedthroughwith
for loops.
Generatorscan be createdusingfunctionsandthe yieldstatement.
def countdown():
i=5
while i>0:
yieldi
i- = 1
for i in countdown():
print(i)
o/p: 5 4 3 2 1
Yieldstatementisusedtodefine agenerator,replacingthe returnof afunctionto provide aresulttoits
calledwithoutdestroyinglocal variables.
Due to the fact thatthey yieldone itemat a time,generatorsdon'thave the memoryrestrictionsof lists.
In fact,theycan be infinite.
In short, generatorsallowsyouto declare afunction that behaveslikeaniteratori.e.itcanbe usedina
for loop.
def infinite_sevens():
while True:
yield7
for i in infinite_sevens():
print(i)
Finite generatorscanbe convertedintolistsbypassingthemasargumentstothe listfunction.Using
generatorsresultsinimprovedperformance,whichisthe resultsof the lazygenerationof values,which
translatestolowermemoryusage.Furthermore,we donotneedtowaituntil all the elementshave
beengeneratedbefore we starttouse them.
def numbers(x):
for i in range(x):
if i%2 == 0:
yieldi
print(list(numbers(11))) -> o/P:[0, 2, 4, 6, 8, 10]
Decorators
Providesawayto modifyfunctionsusingotherfunctions.
Thisis ideal whenyouneedtoextendthe functionalityof functionsthatyoudon't wantto modify.
def decor(func):
def wrap():
print("=====")
func()
print("=====")
returnwrap
def print_text():
print("Hello")
decorated= decor(print_text)
decorated()
def print_text():
print("hello")
print_text= decor(print_text)
@decor
def print_text():
print("Hello")
Object Oriented Programming
Classes
3 paradigmsof programming
1. Imperative - usingstatements,loops,andfunctionsassubroutines
2. Functional - usingpure functions,higherorderfunctions,andrecursion
3. ObjectOrientedprogramming(OOP)
Objectsare createdusingclasses,whichare actuallythe focal pointof OOP.
A Classcan be describedasan object'sblueprint,description,ordefinition.Same classcanbe usedfor
creatingmultiple differentobjects.
class Cat:
def __init__(self,color,legs):
self.color=color
self.legs=legs
def bark(self):
print("woof")
felix =Cat("ginger",4)
rover= Cat("dog-colored",4)
stumpy= Cat("brown",3)
__init__
Calledwhenaninstance (object)of the classiscreated,usingthe classname as function.
All methodsmusthave self astheirfirstparameter,althoughitisn'texplicitlypassed,pythonaddsthe
self argumenttothe listforyou; youdo not needtoinclude itwhenyoucall the methods.
The __init__ methodis calledthe classconstructor.
Methods
Definedtoaddfunctionalitytothem.
Inheritance
Inheritance providesawayto share functionalityb/w calsses.
classAnimal:
def __init__(self,name,color):
self.name =name
self.color=color
classCat(Animal):
def purr(self):
print("Purr..")
classDog(Animal):
def bark(self):
print("woof")
super().purr()
classRed_dog(Dog):
def sec_method(self):
print("secondmethod")
A classthat inheritsfromanotherclassiscalledasubclass.
A classthat is inheritedfromiscalledasuperclass.
If a classinheritsfromanotherwiththe same attributesormethods,itoverridesthem.
Super function
The function superis a useful inheritance relatedfunctionthatreferstothe parentclass.
Magic Methods
These are special methodswhicha double underscores at the beginningandendof theirnames.They
are alsoknown as dunders.
One commonuse of themis operator overloading.
Operator overloading
__add__ for + __truediv__for / __floordiv__for// __mod__ for%
__sub__ for- __and__ for & __pow__ for ** __xor__ for^ __or__ for |
classVector2D:
def __init__(self,x,y):
self.x =x
self.y=y
def __add__(self,other):
returnVector2D(self.x +other.x,self.y+other.y)
first= Vector2D(5,7)
sec = Vector2D(12, 9)
result= first+ sec
__lt__ for< __le__ for <= __eq__ for== __ne__ for!= __gt__ for > __ge__ for>=
Object Lifecycle
Made up of creation,manipulationanddestruction.
Garbage collection
The processof deletingobjectswhentheyare nolongerneedediscalled garbage collection.
Whenan object'sreference countreachesZero,pythonautomaticallydeletesit.
Data Hiding
A keypart of OOP is encapsulation, whichinvolvespackagingof relatedvariablesandfunctionsinto
single easy-to-useobject- an instance of a class.
A relatedconceptis data hiding,whichstatesthat implementationdetailsof aclassshouldbe hidden,
and a cleanstandardinterface be presentedforthose whowantto use the class.
Thiswill be done usingprivate methodsattributesinotherprogramminglanguage.
In python,there are noways of enforcingamethodor attribute be strictlyprivate.
Weeklyprivate methodsandattributeshave a single underscore atthe beginning.
Stronglyprivate methodsandattributeshave a double underscore atthe beginning.
Class methods
Classmethodsare calledbya class,whichis passedtothe cls parameterof the method.
classRectangle:
def __init__(self,width,height):
self.width=width
self.height=height
def calculate_area(self):
returnself.width*self.height
@classmethod
def new_square(cls,side_length):
returncls(side_length,side_length)
square = Rectangle.new_square(5)
print(sqaure.calculate_area())
Note:Technically,the parameters self andclsare just conventions;theycouldbe changedtoanything
else.
Static methods
These are similartoclass methods,excepttheydon'treceive anyadditional arguments;theyare
identical tonormal functionsthatbelongstoaclass.
Theyare markedwiththe staticmethod
classPizza:
def __init__(self,toppings):
self.toppings=toppings
@staticmethod
def validate_topping(topping):
if topping== "pineapple":
raise ValueError("NoPineaaple")
else:
returnTrue
ingredients=["cheese","onions","spam"]
if all(Pizza.validate_topping(i) fori iningredients):
pizza= Pizza(ingredients)
Staticmethodsbehave like plainfunctions,exceptforthe factthat youcan call themfrom an instance of
the class.
Properties
Propertiesprovide awayof customizingaccesstoinstance attributes.
Theyare createdbyputtingthe property decoratorabove a method,whichmeanswhenthe instance
attribute withthe same name as the methodisaccessed,the methodwillbe calledinstead.
One commonuse of a propertyisto make an attribute read-only.
classPizza:
def __init__(self,toppings):
self.toppings=toppings
@property
def pineapple_allowed(self):
returnFalse
@pineapple_allowed.setter
def pineapple_allowed(sefl,value):
if value:
pwd= input("Enterpassword")
if pwd== "admin"
self._pineapple_allowed=value
else
raise ValueError("Alert..Intruder")
pizza= Pizza(["cheese","tomoto"])
print(pizza.pineapple_allowed)
pizza.pineapple_allowed=True
o/p:
False
AttributeError:can'tset attribute -->If setterisnot defined
Enter password:admin
True
Propertiescanalsobe setby defining setter/getterfunctions.
The setterfunctionsetsthe correspondingpropery'svalue.
The gettergetsthe value.
Regular Expressions
RegularExpressionsare powerful tool forvariouskindsof stringmanipulation.
Matching pattern
Standardlibraryisre.
Needtoimportit andcall the belowfunction.
Importre
re.match(“spam”,“eggsspam”) ->Not found
re.search(“spam”, “eggsspam”) ->Found
re.findall(“spam”,“eggsspam”) ->[‘spam’]
Search() Findsa match of a patternanywhere inthe string
Match() Looksat the beginningof the stringonly
Findall() Returnsa listof all substringsthatmatch a pattern
Finditer() Doesthe same thingas findall() exceptitreturns
an iterator,ratherthan a list
re.search()
The search returnsan objectwithseveral methodsthatgive detailsaboutit.These methodsinclude
group() whichreturnsstringmatched, start() andend() whichreturnthe start and endingpositionsof
the match, and span() whichreturnsthe start and endpositionsasa tuple.
Importre
pattern= r”pam”
match = re.search(pattern,“eggspamsausage”)
if match:
print(match.group())
print(match.start())
print(match.end())
print(match.span())
o/p:
pam
4
7
(4, 7)
re.sub() - search & replace
sub() methodreplacesall occurrencesof the patterninstringwithreplace string,substitutingall
occurrences,unlessmax provided.
re.sub(pattern,repl,string,max=0)
importre
str = “My name is David.Hi David”
pattern= r”David”
newstr= re.sub(pattern,“Raj”,str)
print(newstr) -> My name isRaj. Hi Raj.
Metacharacters
Allowsustocreate regularexpressiontorepresentconceptslike “one ormore” repetitionsofa vowel.
. (dot)character
Thismatchesany character, otherthan a new line.
Importre
pattern= r”gr.y”
if re.match(pattern,“grey”):
print(“Match1”)
^ and $ - start and end
Thismatchesthe start and endof a string.
Patter= r”^gr.y$”
re.match(pattern,“grey”) ->True
re.match(pattern,“spamgrey”) ->False
Character classes
Provide away to matchonlyone of a specificsetof characters.
A character classis createdbyputtingthe characters itmatchesinside square brackets.
Pattern= r”[aeiou]
re.search(pattern, “grey”) - > True
re.search(pattern,“myths”) - > False
Supportsrange of charactersalso.
[a-z]-> matchesanylowercase alphabeticcharacter
[G-P]-> matchesanyuppercase characterfrom G to P
[0-9]
[A-Za-z]
^ character
Place a ^ at the start of a character class toinvert it.
Pattern= r”[^A-Z]”
re.search(“Hi Raj”) ->True
re.search(“HIRAJ”) ->False
More Metacharacters
* character
Zeroor more repetitions
+ character
One or more repetitions
? character
Zeroor one repetitions
Curlybraces
Usedto representthe numberof repetitionsb/w twonumbers.
Pattern= r”9{1, 3}$”
Re.match(pattern,“9”) ->True
re.match(pattern,“999”) -> True
re.match(pattern,“9999”) -> False
Groups
A groupcan be createdbysurroundingpartof a regularexpressionwith parenthesis.
Thismeansthat a group can be givenas an argument to metacharacterssuchas * and?
Pattern= r”egg(spam)*”
re.match(pattern,egg) ->True
re.match(pattern,spam) ->False
The contentsof groupsina matchcan be accessedusingthe group function.
A call of group(0) or group() returnsthe whole match.
A call of group(n),where nisthe greaterthan 0, returnsthe nthgroup fromthe left.
Pattern= r”a(bc)(de)(f(g)h)I”
match = re.match(pattern,“abcdefghijklmnop”)
if match:
Print(match.group())->abcdefghi
print(match.group(0)) ->abcdefghi
print(match.group(1)) ->bc
print(match.group(2)) ->de
print(match.groups()) ->(‘bc’,‘de’,‘fgh’,‘g’)
| character
Means or.
Pattern= r”gr(a|e)y”
re.match(pattern,“grey”) ->True
Named groups
Namedgroupshave format (?P<name>…),where name isthe name of the group, … isthe content.
Theybehave exactlysame asthe normal groupsexcepttheycanbe accessedby group(name) in
additiontoitsnumber.
Pattern= r”(?P<first>abc)(?:def)(ghi)”
match = re.match(pattern,“abcdefghi”)
if match:
Print(match.group(“first”)) ->abc
print(match.groups()) ->(‘abc’,‘ghi’)
Non-capturinggroups have the format (?:…).Theyare not accessible bythe groupmethods,sotheycan
be addedto an existingregularexpressionwithoutbreakingthe numbering.See above.
Special Sequences
number - Backslash
Thismatchesthe expressionof the groupof that number. 1to 99 allowed.
Pattern= r”(.+) 1”
re.match(pattern,“wordword”) ->True
re.match(pattern,“abccde”) ->False
Note:“(.+) 1” isnot the same as “(.+) (.+)”.Because, 1refersto the firstgroup’ssubexpression,which
isthe matchedexpressionitself,andnotthe regularexpressionpattern.
d and D sequence
d – matchesthe digits.
D – matchesanythingthatisn’t a digit
Pattern= r”(D+d)”
re.match(pattern,“Hi 999”) -> True
s and S sequence
s – matchesthe white spaces.
S – matchesanythingthatisn’t a white space
Pattern= r”(S+s)”
re.match(pattern,“Hi ”) -> True
w and W sequence
d – matchesthe wordcharacters.
D – matchesanythingthatisn’t a word character
A Sequence
The sequences A andZ match the beginningandendof astring,respectively.
b sequence
It matchesthe emptystringb/w wand W characters, or w characters and the beginningorendof the
string.
Informally,itrepresentsthe boundaryb/w words.
Pattern= r”b(cat)b”
re.search(pattern,“The catsat!” -> True
re.search(pattern,“we scattered”) ->False
“b(cat)b”basicallymatchesthe word“cat”surroundedbywordboundaries.
Email extraction
To extractemail like info@sololearn.com fromtext,use below pattern
Pattern= r”([w.-]+)@([w.-])(.[w.]+)”
[w.-] ->matchesone or more wordcharacter, dot or dash
Str = “Please contactinfo@sololearn.com forassistance”
match = re.search(pattern,str)
if match:
print(match.group())
o/p:info@sololearn.com
Pythonicness & Packaging
Importthis module printsthe Zenof Pythonwhenimported.
There are 20 principlesinthe Zenof Python,butonly19 linesof test.The 20th
principle isamatterof
opinion,butourinterpretationisthatthe blankline means“Use white spaces”
PEP-PythonEnhancement Proposals
PEP are suggestionsforimprovementstothe language,made byexperiencedPythondevelopers.
PEP8 is a style guide onthe subjectof writingreadablecode.
- Modulesshouldhave short,all lowercase names
- Classnamesshould be inCapWordsstyle
- Most variablesandfunctionnamesshouldbe lowercase withunderscores
- Constantsshouldbe CAPSWITH UNDERSCORES
- Namesthatwouldclashwithpythinkeywordshouldhave atrailingunderscore.
- Linesshouldn’tbe longerthan80 characters
- “from module import*”shouldbe avoided
- There shouldbe onlybe one statementperline
Packaging
Referstoputtingmodulesyouhave writteninastandardformat,so that otherprogrammerscaninstall
and use themwithease.Thisinvolvesuse of the modules setuptoolsanddisutils.
Place all the filesyouwantto putin a libraryinthe same parentdirectory.Thisdirectoryshouldalso
containa file called __init__.py,whichcan be blankbut mustbe presentinthe directory.
Thisdirectorygoesintothe otherdirectorywhichwill have readme andlicense,aswell asan important
file called setup.py
Sololearn/
License.txt
Readme.txt
Setup.py
Sololearn/
__init__.py
sololearn.py
sololearn2.py
Setup.py
Thiscontainsinformationnecessarytoassemble the package soitcan be uploadedto PyPIand istalled
withpip
From disutils.core importsetup
Setup(
name=”Sololearn”,
version=’0.1dev’,
packages=[‘sololearn’,],
license=’MIT’,
long_description=open(‘README.txt’).read(),
)
To builda source distribution
python setup.pysdist
To builda binarydistribution
python setup.pybdist
To uploadpackage
python setup.pyregister
pythin setup.pysdistupload
Install apackage with pythonsetup.pyinstall
Packaging for Users
Py2exe tool can be usedtopackage a pythonscript,alongwithlibrariesitrequires,intoasingle
executable.
PyInstallerand cx_Freeze serve the same purpose.
Function arguments
Pythonallowstohave functionwithvaryingnumberof arguments.
*args
Using*args as a functionparameterenablesyoutopassan arbitrarynumberof argumentsto that
function.The argumentsare thenaccessible asthe tuple argsinthe bodyof the function.
Def function(named_arg,*arg):
print(named_arg)
print(args)
Function(1,2,3, 4, 5)
o/p:
1
(2, 3, 4, 5)
The parameter*args must come afterthe namesparameterstoa function.The name argsis justa
convention;youcanchoose to use another.
**kwargs – keyword arguments
Thisallowsyouto handle namedargumentsthatyouhave notdefinedinadvance.
The keywordargumentsreturnsadictionary,inwhichthe keysare the argumentnames, andthe values
are the argumentvalues.
Def my_func(x,y=7,*args, **kwargs):
print(kwargs)
My_func(2,3, 4, 5, 6, a=7, b=8)
o/P:
{‘a’:7, ‘b’:8}
The argumentsreturnedbythe **kwargs are notincludedin*args.
Major 3rd party libraries
Django
The most frequentlyusedwebframeworkwritteninPython,itpowerswebsitesthatincludeInstagram
and Dicqus.
CherryPy and Flask
Are alsopopularwebframeworks
BeautifulSoup
It isveryuseful,andleadstobetterresultsforscrappingdatafromwebsites.
Matplotlib
Allowsyoutocreate a graph basedon data inpython
NumPy
It allowsforthe use of multidimentional arraysthatare much fasterthan native pythonsolutionof
nestedlists.
SciPy
Containsnumerousextensionstothe functionalityof NumPy
Panda3D
For 3D games
Pygame for2D games
List Vs Dictionary Vs Tuples Vs Sets
Lists Sets Dictionaries Tuples
List = [10, 12, 15] Set= {1, 23, 34}
Print(set) ->{1,
23,24}
Set= {1, 1}
print(set) ->{1}
Dict = {"Ram": 26, "mary":
24}
Words = ("spam",
"egss")
Or
Words = "spam",
"eggs"
Access:print(list[0]) Print(set).
Setelementscan't
be indexed.
print(dict["ram"]) Print(words[0])
List[0] = 100 Setelementscan't
be indexed.So,use
add()
Set.add(7)
Dict["Ram"] = 27 Words[0] = "care" ->
TypeError
Mutable Mutable Mutable Immutable - Values
can't be changedonce
assigned
List = [] Set= set() Dict = {} Words = ()
Fasterthan listsbut
theycan't be changed.
Slicingcanbe done
print(list[1:2]) ->[12]
Notdone. Slicingcanalsobe
done on tuples
Can't contain
duplicate elements.
Use listsif youhave a
collectionof datathat
doesn'tneedrandom
access.
Use listswhenyouneed
a simple,iterable
collectionthatis
modifiedfrequently.
- Membership
testingandthe
eliminationof
duplicate entries.
- whenyouneed
uniquenessforthe
elements.
- Whenyouneeda logical
associationb/w key:value
pair.
- whenyouneedfast
lookupforyourdata, based
on a customkey.
- whenyourdata isbeing
constantlymodified.
Use tupleswhenyour
data cannot change.
A tuple isusedin
comibnationwitha
dictionary,for
example,atuple might
representakey,
because its
immutable.
itertools -standard library
The module itertoolsisastandardlibrary.Itproducesinfiniteiterators.
count():counts upinfinitelyfromavalue
cycle():infinitelyiteratesthroughaniterable (alistora string)
repeat():repeatsanobjects,eitherinfinitelyoraspecifiednumberof times.
fromitertoolsimportcount
for i in count(3):
print(i)
if i >= 11:
break
PythonVs C
C language Pythonlanguage
Special operators(++and --) works
I.e.a++; --a;
It doesn'tsupport++ and --.Throws Syntax error.
Each statementinC endswithsemicolon; No use of ; here.
Curlybracesare usedto delimitblocksof code
If (condition)
{
Statement1;
Statement2;
}
It useswhite spacesforthispurpose
If condition:
Statement1
Statement2
Example:
If 10 > 5:
print("10 isgreaterthan 5")
if 10 > 9:
print("10isgreaterthan 9")
else:
print("5is greaterthan10")
Compilingthe programbefore executionis
mandatory
Pythonprogramdirectlyexecuted byusing
interpreter. Nocompilerhere.
Booleanoperatorsare && and || and! Booleanoperatorsare and, or and not
Uses // for one line comment
Uses /* */ for multiple line comment
Uses # for one line comment
Uses """ """ for multi line comments (Docstrings).
Uses #include toimportstandardlibraryfunctions
#include<stdio.h>
Uses importkeywordtoinclude standardlibrary
functions
Importmath
Voidassert(intexpression)
Expression -Thiscanbe a variable orany C
expression.If expressionevaluatestoTRUE,
assert() doesnothing.If expressionevaluatesto
FALSE,assert() displaysanerrormessage
on stderr(standarderrorstreamto displayerror
assertexpression
Example
assert1 + 1 == 3
messagesanddiagnostics) andabortsprogram
execution.
NULL None - representsabsence of value
Don't have automaticmemorymanagement. AutomaticGarbage collection.
Web scraping: webbrowser library
https://automatetheboringstuff.com/chapter11/
Webscrapingis the term forusinga program to downloadandprocesscontentfromthe Web.For
example,Googlerunsmanywebscrapingprogramsto index webpagesforitssearchengine.
webbrowser. Comes with Python and opens a browser to a specific page.
Webbrowser.open()
webbrowser.open(url,new=0,autoraise=True)
Displayurl usingthe defaultbrowser.If new is0,the url is openedinthe same browserwindow if
possible.If newis1,a newbrowserwindow isopenedif possible.If new is2, a new browserpage
(“tab”) is openedif possible.If autoraise isTrue,the window israisedif possible (notethatundermany
windowmanagersthiswill occurregardlessof the settingof thisvariable).
Note that onsome platforms,tryingtoopena filename usingthisfunction,mayworkandstart the
operatingsystem’sassociatedprogram.However,thisisneithersupportednorportable.
webbrowser.open_new(url)
Openurl in a newwindowof the defaultbrowser,if possible,otherwise,openurl inthe onlybrowser
window.
webbrowser.open_new_tab(url)
Openurl in a newpage (“tab”) of the defaultbrowser,if possible,otherwise equivalenttoopen_new().
webbrowser.get([name])
Returna controllerobjectforthe browsertype name.If name isempty,returna controllerfora default
browserappropriate tothe caller’senvironment.
import webbrowser
url = 'http://idiotinside.com'
# Open URL in new browser window
webbrowser.open_new(url) # opens in default browser
# Opens in safari browser
webbrowser.get('safari').open_new(url)
# Open URL in a new tab
webbrowser.open_new_tab(url) # opens in default browser
# Opens in safari browser
webbrowser.get('safari').open_new_tab(url)
Type Name Class Name Notes
'mozilla' Mozilla('mozilla')
'firefox' Mozilla('mozilla')
'netscape' Mozilla('netscape')
'galeon' Galeon('galeon')
'epiphany' Galeon('epiphany')
'skipstone' BackgroundBrowser('skipstone')
'kfmclient' Konqueror() (1)
'konqueror' Konqueror() (1)
'kfm' Konqueror() (1)
'mosaic' BackgroundBrowser('mosaic')
'opera' Opera()
'grail' Grail()
'links' GenericBrowser('links')
'elinks' Elinks('elinks')
'lynx' GenericBrowser('lynx')
'w3m' GenericBrowser('w3m')
'windows-default' WindowsDefault (2)
'macosx' MacOSX('default') (3)
Type Name Class Name Notes
'safari' MacOSX('safari') (3)
'google-chrome' Chrome('google-chrome') (4)
'chrome' Chrome('chrome') (4)
'chromium' Chromium('chromium') (4)
'chromium-browser' Chromium('chromium-browser') (4)

More Related Content

What's hot (15)

Learn Python Programming | Python Programming - Step by Step | Python for Beg...
Learn Python Programming | Python Programming - Step by Step | Python for Beg...Learn Python Programming | Python Programming - Step by Step | Python for Beg...
Learn Python Programming | Python Programming - Step by Step | Python for Beg...
Edureka!
 
Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming
KrishnaMildain
 
Python pandas tutorial
Python pandas tutorialPython pandas tutorial
Python pandas tutorial
HarikaReddy115
 
Chapter 8 getting started with python
Chapter 8 getting started with pythonChapter 8 getting started with python
Chapter 8 getting started with python
Praveen M Jigajinni
 
Report om 3
Report om 3Report om 3
Report om 3
HarryRoy9
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
DrMohammed Qassim
 
Benefits & features of python |Advantages & disadvantages of python
Benefits & features of python |Advantages & disadvantages of pythonBenefits & features of python |Advantages & disadvantages of python
Benefits & features of python |Advantages & disadvantages of python
paradisetechsoftsolutions
 
11 Unit1 Chapter 1 Getting Started With Python
11   Unit1 Chapter 1 Getting Started With Python11   Unit1 Chapter 1 Getting Started With Python
11 Unit1 Chapter 1 Getting Started With Python
Praveen M Jigajinni
 
Python quick guide1
Python quick guide1Python quick guide1
Python quick guide1
Kanchilug
 
Statistics Using Python | Statistics Python Tutorial | Python Certification T...
Statistics Using Python | Statistics Python Tutorial | Python Certification T...Statistics Using Python | Statistics Python Tutorial | Python Certification T...
Statistics Using Python | Statistics Python Tutorial | Python Certification T...
Edureka!
 
Python course syllabus
Python course syllabusPython course syllabus
Python course syllabus
Sugantha T
 
Obj report
Obj reportObj report
Obj report
Manish Raghav
 
PYTHON CURRENT TREND APPLICATIONS- AN OVERVIEW
PYTHON CURRENT TREND APPLICATIONS- AN OVERVIEWPYTHON CURRENT TREND APPLICATIONS- AN OVERVIEW
PYTHON CURRENT TREND APPLICATIONS- AN OVERVIEW
EditorIJAERD
 
Python, the Language of Science and Engineering for Engineers
Python, the Language of Science and Engineering for EngineersPython, the Language of Science and Engineering for Engineers
Python, the Language of Science and Engineering for Engineers
Boey Pak Cheong
 
5 Simple Steps To Install Python On Windows | Install Python 3.7 | Python Tra...
5 Simple Steps To Install Python On Windows | Install Python 3.7 | Python Tra...5 Simple Steps To Install Python On Windows | Install Python 3.7 | Python Tra...
5 Simple Steps To Install Python On Windows | Install Python 3.7 | Python Tra...
Edureka!
 
Learn Python Programming | Python Programming - Step by Step | Python for Beg...
Learn Python Programming | Python Programming - Step by Step | Python for Beg...Learn Python Programming | Python Programming - Step by Step | Python for Beg...
Learn Python Programming | Python Programming - Step by Step | Python for Beg...
Edureka!
 
Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming
KrishnaMildain
 
Python pandas tutorial
Python pandas tutorialPython pandas tutorial
Python pandas tutorial
HarikaReddy115
 
Chapter 8 getting started with python
Chapter 8 getting started with pythonChapter 8 getting started with python
Chapter 8 getting started with python
Praveen M Jigajinni
 
Benefits & features of python |Advantages & disadvantages of python
Benefits & features of python |Advantages & disadvantages of pythonBenefits & features of python |Advantages & disadvantages of python
Benefits & features of python |Advantages & disadvantages of python
paradisetechsoftsolutions
 
11 Unit1 Chapter 1 Getting Started With Python
11   Unit1 Chapter 1 Getting Started With Python11   Unit1 Chapter 1 Getting Started With Python
11 Unit1 Chapter 1 Getting Started With Python
Praveen M Jigajinni
 
Python quick guide1
Python quick guide1Python quick guide1
Python quick guide1
Kanchilug
 
Statistics Using Python | Statistics Python Tutorial | Python Certification T...
Statistics Using Python | Statistics Python Tutorial | Python Certification T...Statistics Using Python | Statistics Python Tutorial | Python Certification T...
Statistics Using Python | Statistics Python Tutorial | Python Certification T...
Edureka!
 
Python course syllabus
Python course syllabusPython course syllabus
Python course syllabus
Sugantha T
 
PYTHON CURRENT TREND APPLICATIONS- AN OVERVIEW
PYTHON CURRENT TREND APPLICATIONS- AN OVERVIEWPYTHON CURRENT TREND APPLICATIONS- AN OVERVIEW
PYTHON CURRENT TREND APPLICATIONS- AN OVERVIEW
EditorIJAERD
 
Python, the Language of Science and Engineering for Engineers
Python, the Language of Science and Engineering for EngineersPython, the Language of Science and Engineering for Engineers
Python, the Language of Science and Engineering for Engineers
Boey Pak Cheong
 
5 Simple Steps To Install Python On Windows | Install Python 3.7 | Python Tra...
5 Simple Steps To Install Python On Windows | Install Python 3.7 | Python Tra...5 Simple Steps To Install Python On Windows | Install Python 3.7 | Python Tra...
5 Simple Steps To Install Python On Windows | Install Python 3.7 | Python Tra...
Edureka!
 

Viewers also liked (20)

An Introduction to Python Programming
An Introduction to Python ProgrammingAn Introduction to Python Programming
An Introduction to Python Programming
Morteza Zakeri
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
Aravind Ganesh
 
Learn python - for beginners - part-2
Learn python - for beginners - part-2Learn python - for beginners - part-2
Learn python - for beginners - part-2
RajKumar Rampelli
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
amiable_indian
 
Introduction to Python - Part Two
Introduction to Python - Part TwoIntroduction to Python - Part Two
Introduction to Python - Part Two
amiable_indian
 
Introduction to Advanced Javascript
Introduction to Advanced JavascriptIntroduction to Advanced Javascript
Introduction to Advanced Javascript
Collaboration Technologies
 
Java OOP Programming language (Part 1) - Introduction to Java
Java OOP Programming language (Part 1) - Introduction to JavaJava OOP Programming language (Part 1) - Introduction to Java
Java OOP Programming language (Part 1) - Introduction to Java
OUM SAOKOSAL
 
Python - Lecture 1
Python - Lecture 1Python - Lecture 1
Python - Lecture 1
Ravi Kiran Khareedi
 
Meetup Python Nantes - les tests en python
Meetup Python Nantes - les tests en pythonMeetup Python Nantes - les tests en python
Meetup Python Nantes - les tests en python
Arthur Lutz
 
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Matt Harrison
 
Learning notes of r for python programmer (Temp1)
Learning notes of r for python programmer (Temp1)Learning notes of r for python programmer (Temp1)
Learning notes of r for python programmer (Temp1)
Chia-Chi Chang
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and More
Matt Harrison
 
Operator Overloading
Operator Overloading  Operator Overloading
Operator Overloading
Sardar Alam
 
Python for All
Python for All Python for All
Python for All
Pragya Goyal
 
Installing Python on Mac
Installing Python on MacInstalling Python on Mac
Installing Python on Mac
Wei-Wen Hsu
 
Lesson1 python an introduction
Lesson1 python an introductionLesson1 python an introduction
Lesson1 python an introduction
Arulalan T
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Yi-Fan Chu
 
Python master class part 1
Python master class part 1Python master class part 1
Python master class part 1
Chathuranga Bandara
 
Introduction to facebook java script sdk
Introduction to facebook java script sdk Introduction to facebook java script sdk
Introduction to facebook java script sdk
Yi-Fan Chu
 
Lec02 structures (2)
Lec02 structures (2)Lec02 structures (2)
Lec02 structures (2)
Khuder Altangerel
 
An Introduction to Python Programming
An Introduction to Python ProgrammingAn Introduction to Python Programming
An Introduction to Python Programming
Morteza Zakeri
 
Learn python - for beginners - part-2
Learn python - for beginners - part-2Learn python - for beginners - part-2
Learn python - for beginners - part-2
RajKumar Rampelli
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
amiable_indian
 
Introduction to Python - Part Two
Introduction to Python - Part TwoIntroduction to Python - Part Two
Introduction to Python - Part Two
amiable_indian
 
Java OOP Programming language (Part 1) - Introduction to Java
Java OOP Programming language (Part 1) - Introduction to JavaJava OOP Programming language (Part 1) - Introduction to Java
Java OOP Programming language (Part 1) - Introduction to Java
OUM SAOKOSAL
 
Meetup Python Nantes - les tests en python
Meetup Python Nantes - les tests en pythonMeetup Python Nantes - les tests en python
Meetup Python Nantes - les tests en python
Arthur Lutz
 
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Matt Harrison
 
Learning notes of r for python programmer (Temp1)
Learning notes of r for python programmer (Temp1)Learning notes of r for python programmer (Temp1)
Learning notes of r for python programmer (Temp1)
Chia-Chi Chang
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and More
Matt Harrison
 
Operator Overloading
Operator Overloading  Operator Overloading
Operator Overloading
Sardar Alam
 
Installing Python on Mac
Installing Python on MacInstalling Python on Mac
Installing Python on Mac
Wei-Wen Hsu
 
Lesson1 python an introduction
Lesson1 python an introductionLesson1 python an introduction
Lesson1 python an introduction
Arulalan T
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Yi-Fan Chu
 
Introduction to facebook java script sdk
Introduction to facebook java script sdk Introduction to facebook java script sdk
Introduction to facebook java script sdk
Yi-Fan Chu
 
Ad

Similar to Introduction to Python - Running Notes (20)

Swaroop c h a byte of python
Swaroop c h a byte of pythonSwaroop c h a byte of python
Swaroop c h a byte of python
Lagal Tchixa
 
python_tutorial.pdf
python_tutorial.pdfpython_tutorial.pdf
python_tutorial.pdf
poojaofficial
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
Albertz Ace-Red
 
Python basics
Python basicsPython basics
Python basics
kaviyaanu17
 
Python basics
Python basicsPython basics
Python basics
Emerson Candido
 
python_tutorial.pdf
python_tutorial.pdfpython_tutorial.pdf
python_tutorial.pdf
amgadmonir1
 
Python 3 - Tutorialspoint Full Cource Book.pdf
Python 3 - Tutorialspoint Full Cource Book.pdfPython 3 - Tutorialspoint Full Cource Book.pdf
Python 3 - Tutorialspoint Full Cource Book.pdf
AbdikadirAbdirahman4
 
Hewlp
HewlpHewlp
Hewlp
Rajesh Kumar
 
Python Programming Hans-petter Halvorsen.pdf
Python Programming Hans-petter Halvorsen.pdfPython Programming Hans-petter Halvorsen.pdf
Python Programming Hans-petter Halvorsen.pdf
sasidhar3641
 
Raspberry Pi: Python todo en uno para dummies por John Shovic parte 1.pdf
Raspberry Pi: Python todo en uno para dummies por John Shovic parte 1.pdfRaspberry Pi: Python todo en uno para dummies por John Shovic parte 1.pdf
Raspberry Pi: Python todo en uno para dummies por John Shovic parte 1.pdf
SANTIAGO PABLO ALBERTO
 
Learn Python Fast-Deep-Simple.pdf
Learn Python Fast-Deep-Simple.pdfLearn Python Fast-Deep-Simple.pdf
Learn Python Fast-Deep-Simple.pdf
BehnamKhani6
 
python_tutorial.pdf
python_tutorial.pdfpython_tutorial.pdf
python_tutorial.pdf
Shenthilkumar Subburam
 
python tutorial for all python tutorial for all
python tutorial for all python tutorial for allpython tutorial for all python tutorial for all
python tutorial for all python tutorial for all
Khaled250375
 
XRumer user manual guide
XRumer user manual guideXRumer user manual guide
XRumer user manual guide
Regis Wa
 
Installation_Guide_SC80-A4
Installation_Guide_SC80-A4Installation_Guide_SC80-A4
Installation_Guide_SC80-A4
Eugene Lymar
 
کلا اوپن استک با اوبونتو - روزبه شفیعی - جشواره متن‌باز ایران
کلا اوپن استک با اوبونتو - روزبه شفیعی - جشواره متن‌باز ایرانکلا اوپن استک با اوبونتو - روزبه شفیعی - جشواره متن‌باز ایران
کلا اوپن استک با اوبونتو - روزبه شفیعی - جشواره متن‌باز ایران
ofest
 
Thru rest api_1_0_ref_1_7
Thru rest api_1_0_ref_1_7Thru rest api_1_0_ref_1_7
Thru rest api_1_0_ref_1_7
urooj230
 
Dat 210 academic adviser ....tutorialrank.com
Dat 210 academic adviser ....tutorialrank.comDat 210 academic adviser ....tutorialrank.com
Dat 210 academic adviser ....tutorialrank.com
ladworkspaces
 
DAT 210 Education Specialist |tutorialrank.com
DAT 210 Education Specialist |tutorialrank.comDAT 210 Education Specialist |tutorialrank.com
DAT 210 Education Specialist |tutorialrank.com
ladworkspaces
 
02.12.2012 ubuntu 12.1 server guide
02.12.2012 ubuntu 12.1 server guide02.12.2012 ubuntu 12.1 server guide
02.12.2012 ubuntu 12.1 server guide
El Alex Andrade
 
Swaroop c h a byte of python
Swaroop c h a byte of pythonSwaroop c h a byte of python
Swaroop c h a byte of python
Lagal Tchixa
 
python_tutorial.pdf
python_tutorial.pdfpython_tutorial.pdf
python_tutorial.pdf
amgadmonir1
 
Python 3 - Tutorialspoint Full Cource Book.pdf
Python 3 - Tutorialspoint Full Cource Book.pdfPython 3 - Tutorialspoint Full Cource Book.pdf
Python 3 - Tutorialspoint Full Cource Book.pdf
AbdikadirAbdirahman4
 
Python Programming Hans-petter Halvorsen.pdf
Python Programming Hans-petter Halvorsen.pdfPython Programming Hans-petter Halvorsen.pdf
Python Programming Hans-petter Halvorsen.pdf
sasidhar3641
 
Raspberry Pi: Python todo en uno para dummies por John Shovic parte 1.pdf
Raspberry Pi: Python todo en uno para dummies por John Shovic parte 1.pdfRaspberry Pi: Python todo en uno para dummies por John Shovic parte 1.pdf
Raspberry Pi: Python todo en uno para dummies por John Shovic parte 1.pdf
SANTIAGO PABLO ALBERTO
 
Learn Python Fast-Deep-Simple.pdf
Learn Python Fast-Deep-Simple.pdfLearn Python Fast-Deep-Simple.pdf
Learn Python Fast-Deep-Simple.pdf
BehnamKhani6
 
python tutorial for all python tutorial for all
python tutorial for all python tutorial for allpython tutorial for all python tutorial for all
python tutorial for all python tutorial for all
Khaled250375
 
XRumer user manual guide
XRumer user manual guideXRumer user manual guide
XRumer user manual guide
Regis Wa
 
Installation_Guide_SC80-A4
Installation_Guide_SC80-A4Installation_Guide_SC80-A4
Installation_Guide_SC80-A4
Eugene Lymar
 
کلا اوپن استک با اوبونتو - روزبه شفیعی - جشواره متن‌باز ایران
کلا اوپن استک با اوبونتو - روزبه شفیعی - جشواره متن‌باز ایرانکلا اوپن استک با اوبونتو - روزبه شفیعی - جشواره متن‌باز ایران
کلا اوپن استک با اوبونتو - روزبه شفیعی - جشواره متن‌باز ایران
ofest
 
Thru rest api_1_0_ref_1_7
Thru rest api_1_0_ref_1_7Thru rest api_1_0_ref_1_7
Thru rest api_1_0_ref_1_7
urooj230
 
Dat 210 academic adviser ....tutorialrank.com
Dat 210 academic adviser ....tutorialrank.comDat 210 academic adviser ....tutorialrank.com
Dat 210 academic adviser ....tutorialrank.com
ladworkspaces
 
DAT 210 Education Specialist |tutorialrank.com
DAT 210 Education Specialist |tutorialrank.comDAT 210 Education Specialist |tutorialrank.com
DAT 210 Education Specialist |tutorialrank.com
ladworkspaces
 
02.12.2012 ubuntu 12.1 server guide
02.12.2012 ubuntu 12.1 server guide02.12.2012 ubuntu 12.1 server guide
02.12.2012 ubuntu 12.1 server guide
El Alex Andrade
 
Ad

More from RajKumar Rampelli (14)

Writing Character driver (loadable module) in linux
Writing Character driver (loadable module) in linuxWriting Character driver (loadable module) in linux
Writing Character driver (loadable module) in linux
RajKumar Rampelli
 
Linux Kernel MMC Storage driver Overview
Linux Kernel MMC Storage driver OverviewLinux Kernel MMC Storage driver Overview
Linux Kernel MMC Storage driver Overview
RajKumar Rampelli
 
Learn python – for beginners
Learn python – for beginnersLearn python – for beginners
Learn python – for beginners
RajKumar Rampelli
 
Linux watchdog timer
Linux watchdog timerLinux watchdog timer
Linux watchdog timer
RajKumar Rampelli
 
Linux Kernel I/O Schedulers
Linux Kernel I/O SchedulersLinux Kernel I/O Schedulers
Linux Kernel I/O Schedulers
RajKumar Rampelli
 
Linux GIT commands
Linux GIT commandsLinux GIT commands
Linux GIT commands
RajKumar Rampelli
 
Introduction to Kernel and Device Drivers
Introduction to Kernel and Device DriversIntroduction to Kernel and Device Drivers
Introduction to Kernel and Device Drivers
RajKumar Rampelli
 
System Booting Process overview
System Booting Process overviewSystem Booting Process overview
System Booting Process overview
RajKumar Rampelli
 
Network security and cryptography
Network security and cryptographyNetwork security and cryptography
Network security and cryptography
RajKumar Rampelli
 
Tasklet vs work queues (Deferrable functions in linux)
Tasklet vs work queues (Deferrable functions in linux)Tasklet vs work queues (Deferrable functions in linux)
Tasklet vs work queues (Deferrable functions in linux)
RajKumar Rampelli
 
Sql injection attack
Sql injection attackSql injection attack
Sql injection attack
RajKumar Rampelli
 
Turing awards seminar
Turing awards seminarTuring awards seminar
Turing awards seminar
RajKumar Rampelli
 
Higher education importance
Higher education importanceHigher education importance
Higher education importance
RajKumar Rampelli
 
C compilation process
C compilation processC compilation process
C compilation process
RajKumar Rampelli
 
Writing Character driver (loadable module) in linux
Writing Character driver (loadable module) in linuxWriting Character driver (loadable module) in linux
Writing Character driver (loadable module) in linux
RajKumar Rampelli
 
Linux Kernel MMC Storage driver Overview
Linux Kernel MMC Storage driver OverviewLinux Kernel MMC Storage driver Overview
Linux Kernel MMC Storage driver Overview
RajKumar Rampelli
 
Learn python – for beginners
Learn python – for beginnersLearn python – for beginners
Learn python – for beginners
RajKumar Rampelli
 
Introduction to Kernel and Device Drivers
Introduction to Kernel and Device DriversIntroduction to Kernel and Device Drivers
Introduction to Kernel and Device Drivers
RajKumar Rampelli
 
System Booting Process overview
System Booting Process overviewSystem Booting Process overview
System Booting Process overview
RajKumar Rampelli
 
Network security and cryptography
Network security and cryptographyNetwork security and cryptography
Network security and cryptography
RajKumar Rampelli
 
Tasklet vs work queues (Deferrable functions in linux)
Tasklet vs work queues (Deferrable functions in linux)Tasklet vs work queues (Deferrable functions in linux)
Tasklet vs work queues (Deferrable functions in linux)
RajKumar Rampelli
 

Recently uploaded (20)

How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
EduSkills OECD
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdfUnit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Celine George
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
Quiz Club of PSG College of Arts & Science
 
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
Quiz Club of PSG College of Arts & Science
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
Hemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptxHemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptx
Arshad Shaikh
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
Strengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptxStrengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptx
SteffMusniQuiballo
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptxPests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Arshad Shaikh
 
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
EduSkills OECD
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdfUnit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Celine George
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
Hemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptxHemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptx
Arshad Shaikh
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
Strengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptxStrengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptx
SteffMusniQuiballo
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptxPests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Arshad Shaikh
 
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 

Introduction to Python - Running Notes

  • 1. PYTHON INTRODUCTION [Type the abstract of the document here. The abstract is typically a short summary of the contents of the document. Type the abstract of the document here. The abstract is typically a short summary of the contents of the document.] Reference: sololearn.com
  • 2. PYTHON Table of Contents Python Introduction............................................................................................................................6 Python versions..............................................................................................................................6 Python console...............................................................................................................................6 Python functions ................................................................................................................................6 Python errors.....................................................................................................................................6 Python floats......................................................................................................................................7 Python numerical operations ..............................................................................................................7 __main__...........................................................................................................................................8 Command line arguments...................................................................................................................8 sys module.....................................................................................................................................8 getopt module................................................................................................................................9 getopt.getopt method.................................................................................................................9 Exception getopt.GetoptError......................................................................................................9 Example.................................................................................................................................10 Strings..............................................................................................................................................11 String formatting..........................................................................................................................11 String operations ..........................................................................................................................12 Variables..........................................................................................................................................12 Variable names:............................................................................................................................12 del statement...............................................................................................................................13 Special operators..............................................................................................................................13 if statements....................................................................................................................................13 elif (short form of else if)...............................................................................................................13 Boolean logic................................................................................................................................14 While loops......................................................................................................................................14 infinite loop..................................................................................................................................14 break...........................................................................................................................................14 continue.......................................................................................................................................14
  • 3. operator precedence........................................................................................................................14 More on else statements ..................................................................................................................15 Else with loops..............................................................................................................................15 Else with try/except......................................................................................................................15 Lists.................................................................................................................................................15 Empty list.....................................................................................................................................16 Nested lists...................................................................................................................................16 Errors...........................................................................................................................................16 List operations..............................................................................................................................16 Assignment...............................................................................................................................16 Addition and Multiplication........................................................................................................16 in operator................................................................................................................................16 not operator.............................................................................................................................17 Loops........................................................................................................................................17 List slices......................................................................................................................................17 Negative indexing......................................................................................................................17 List comprehensions .....................................................................................................................18 List functions................................................................................................................................18 Sets.................................................................................................................................................19 Mathematical operations - union/intersection................................................................................19 Functions and modules.....................................................................................................................20 Arguments ...................................................................................................................................20 Return values ...............................................................................................................................21 Docstrings ....................................................................................................................................21 Modules.......................................................................................................................................21 Import certain functions............................................................................................................21 Standard Library...............................................................................................................................21 Exception Handling...........................................................................................................................22 Raising exception..........................................................................................................................23 Assertions........................................................................................................................................23 Files handling...................................................................................................................................23 Opening files - open()....................................................................................................................23
  • 4. Reading Files - read().....................................................................................................................24 Writing Files - write().....................................................................................................................24 with statement.............................................................................................................................24 None................................................................................................................................................25 Dictionaries......................................................................................................................................25 Dictionary Functions .....................................................................................................................26 Search......................................................................................................................................26 get() .........................................................................................................................................26 Tuples..............................................................................................................................................26 Tuple unpacking...........................................................................................................................26 Variable*......................................................................................................................................27 Ternary operator..............................................................................................................................27 Higher order functions......................................................................................................................27 Lambdas.......................................................................................................................................27 map and filter...............................................................................................................................28 Generators.......................................................................................................................................28 Decorators.......................................................................................................................................29 Object Oriented Programming...........................................................................................................30 Classes.........................................................................................................................................30 __init__........................................................................................................................................30 Methods ......................................................................................................................................30 Inheritance...................................................................................................................................30 Super function..............................................................................................................................31 Magic Methods.............................................................................................................................31 Operator overloading....................................................................................................................31 Object Lifecycle ............................................................................................................................31 Garbage collection........................................................................................................................32 Data Hiding..................................................................................................................................32 Class methods ..............................................................................................................................32 Static methods..........................................................................................................................32 Properties ....................................................................................................................................33 Regular Expressions..........................................................................................................................34
  • 5. Matching pattern..........................................................................................................................34 re.search()....................................................................................................................................34 re.sub() - search & replace.............................................................................................................35 Metacharacters ............................................................................................................................35 . (dot) character........................................................................................................................35 ^ and $ - start and end...............................................................................................................35 Character classes..........................................................................................................................35 ^ character................................................................................................................................36 More Metacharacters ...................................................................................................................36 * character................................................................................................................................36 + character................................................................................................................................36 ? character................................................................................................................................36 Curly braces..............................................................................................................................36 Groups.........................................................................................................................................36 | character................................................................................................................................37 Named groups...........................................................................................................................37 Special Sequences ............................................................................................................................37 number - Backslash .....................................................................................................................37 d and D sequence.......................................................................................................................38 s and S sequence........................................................................................................................38 w and W sequence.....................................................................................................................38 A Sequence.................................................................................................................................38 b sequence .................................................................................................................................38 Email extraction ...............................................................................................................................38 Pythonicness & Packaging.................................................................................................................39 PEP- Python Enhancement Proposals.................................................................................................39 Packaging.........................................................................................................................................39 Setup.py.......................................................................................................................................40 Packaging for Users.......................................................................................................................40 Function arguments..........................................................................................................................40 *args............................................................................................................................................40 **kwargs – keyword arguments ....................................................................................................41
  • 6. Major 3rd party libraries ....................................................................................................................41 Django.........................................................................................................................................41 CherryPy and Flask........................................................................................................................41 BeautifulSoup...............................................................................................................................41 Matplotlib....................................................................................................................................41 NumPy.........................................................................................................................................41 SciPy............................................................................................................................................42 Panda3D ......................................................................................................................................42 List Vs Dictionary Vs TuplesVs Sets....................................................................................................42 itertools - standard library.................................................................................................................43 Python Vs C......................................................................................................................................43 Web scraping: webbrowser library ....................................................................................................44 Webbrowser.open()......................................................................................................................44 webbrowser.open_new(url)..........................................................................................................44 webbrowser.open_new_tab(url) ...................................................................................................44 webbrowser.get([name])...............................................................................................................44
  • 7. Python !!! PythonIntroduction Pythonisa highlevel programminglanguagelikeC/C++/Javaetc.,itsapplicationsincludingweb programming,scripting,scientificcomputingandartificial intelligence. pythonisprocessedatruntime bythe interpreter.Noneedto compile pythonprogramsbefore executingthemunlikeCprograms,where compilationstepismandatorybeforeexecutingit. An Interpreterisaprogramthat runs scriptswritteninan interpretedlanguage suchasPython. Pythonsource fileshave anextensionof .py Python versions There are three majorversionsof pythonwhichare 1.x,2.x and3.x. Both2.x and 3.x are currentlyused. Python console The pythonconsole isa program that allowsyouto enterone line of pythoncode,repeatedlyexecutes that line,anddisplaysthe output.Thisisknownasa REPL - Read-Eval-Print-Loop. To close a console,type inquit() orexit() andpressenter. Pythonfunctions Pythonfunction Usage print("Hello") orprint('Hello') Printsthe message,producesthe output quit() orexit() Close the console input("Entersomethingplease:") Promptsthe use for input,andreturnswhatthey enteras a stringwithcontentsautomatically escaped. Enter somethingplease:userentersncharacter! o/p-> userentersncharacter! int() Convertsgivennumberinstringformattointeger int("2") + int("3") = 5 Similarlyfloat() andstr() del variable_name del statementusedtoremove avariable from program. Pythonerrors Type of error Example ZeroDivisionError:divisionbyzero 11 / 0 TypeError:unsupportedoperandtype(s) 1 + "2"
  • 8. For +:'int' and 'str' TypeError:can't multiplysequence bynon-intof type 'str' or 'float' "s" * "s" 9.0 * "r" SyntaxError:invalidsyntax >>>123abc = 7 1. When variable namesdon'tfollowrules. 2. When programuses++ or -- operators. NameError:name 'var_name" is notdefined Whenprogram triestoaccess undefinedvariable or a functionwhichisnotdefined In Lists: IndexError: whentry toaccess out of boundvalues. things="hai" print(things[4]) In Lists: TypeError: whentry toaccess integerorfloat typesusing index. Num= 123 print(Num(2)) In Lists: ValueError: If the itemisnotin the listand tryingto getits index. ImportError Whentryingto access unavailablemodule KeyError Tryingto index akeythat isn'tpart of the dictionaryreturnsaKeyError. Dictionary'sTypeError Whenmutable objectsare usedaskeys RuntimeError:maximumrecursiondepth exceeded Oftenoccur whenforgottoimplementthe base case of resusion. AttributeError Tryingto access an attribute of an instance the isn'tdefinedcausesthiserror. Pythonfloats A floatcan be addedto an integerbecause Pythonsilentlyconvertsthe integertoa float.However,this implicitconversionisthe exceptionratherthanthe rule inPython.Youhave to convertvaluesmanually if you wantto operate onthem. Pythonnumerical operations Operator Usage + , - , * , / Addition,subtraction,multiplication,division 1 + 2 = 3 1 + 2.2 = 3.2 2 * 3 = 6 2 * 3.2 = 6.4 4/2 = 2.0 5/2 = 2.5 ** Exponentiation 2**5 = 32 9**(1/2) = 3.0 // Quotient(Floordivision)
  • 9. 20//6 = 3 % Remainder(modulooperator) 1.25%0.5 = 0.25 Inplace operators += , -=, *=, %= and /= a += 3 -> a = a + 3 __main__ Whena pythoninterpreterreadsasource file,itexecutesall of the code itfindsinthe file. Before executingthe code,itdefinesafewspecial variables. For example,if the pythoninterpreterisrunningthatmodule (source file) asthe mainprogram, itsets the special __name__ variable tohave avalue “__main__”. If the file beingimportedfromanother module, __name__ will be settothe module’sname. If __name__ == “__main__”: print(“Thisisascript”) else print(“Imported”) Commandline arguments sys module The Python sys module providesaccesstoany command-lineargumentsviathe sys.argv.Thisserves twopurposes−  sys.argvisthe listof command-linearguments.  len(sys.argv) isthe numberof command-linearguments. Here sys.argv[0] isthe program ie.scriptname. Consider the following script test.py − #!/usr/bin/python import sys print 'Number of arguments:', len(sys.argv), 'arguments.' print 'Argument List:', str(sys.argv) Now run above script as follows −
  • 10. $ python test.py arg1 arg2 arg3 This produce following result − Number of arguments: 4 arguments. Argument List: ['test.py', 'arg1', 'arg2', 'arg3'] getopt module Pythonprovidesagetoptmodule thathelpsyouparse command-lineoptionsandarguments. Pythonprovidedagetoptmodule thathelpsyouparse command-lineoptionsandarguments.This module providestwofunctionsandan exceptiontoenablecommandline argumentparsing. getopt.getoptmethod Thismethodparsescommandline optionsandparameterlist.Followingissimple syntaxforthismethod − getopt.getopt(args,options,[long_options]) Here is the detail of the parameters−  args: Thisisthe argumentlistto be parsed.  options:This isthe stringof optionlettersthatthe scriptwantsto recognize,withoptionsthat require anargumentshouldbe followedbyacolon(:).  long_options:Thisis optional parameterandif specified,mustbe alistof stringswiththe namesof the longoptions,whichshouldbe supported.Longoptions,whichrequire an argumentshouldbe followedbyanequal sign('=').To accept onlylongoptions,optionsshould be an emptystring.  Thismethodreturnsvalue consistingof twoelements:the firstisalistof (option,value) pairs. The secondis the listof program argumentsleftafterthe optionlistwasstripped.  Each option-and-valuepairreturnedhasthe optionasitsfirstelement,prefixed withahyphen for shortoptions(e.g.,'-x') ortwohyphensforlongoptions(e.g.,'--long-option'). Exceptiongetopt.GetoptError Thisis raisedwhenanunrecognizedoptionisfoundinthe argumentlistorwhenanoptionrequiringan argumentisgivennone. The argumentto the exceptionisastringindicatingthe cause of the error. The attributesmsgandopt give the errormessage andrelatedoption.
  • 11. Example Consider we want to pass two file names through command line and we also want to give an option to check the usage of the script. Usage of the script is as follows − usage: test.py -i <inputfile> -o <outputfile> Here is the following script to test.py − #!/usr/bin/python import sys, getopt def main(argv): inputfile = '' outputfile = '' try: opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="]) except getopt.GetoptError: print 'test.py -i <inputfile> -o <outputfile>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'test.py -i <inputfile> -o <outputfile>' sys.exit() elif opt in ("-i", "--ifile"): inputfile = arg elif opt in ("-o", "--ofile"): outputfile = arg print 'Input file is "', inputfile print 'Output file is "', outputfile if __name__ == "__main__": main(sys.argv[1:])
  • 12. Now, run above script as follows − $ test.py -h usage: test.py -i <inputfile> -o <outputfile> $ test.py -i BMP -o usage: test.py -i <inputfile> -o <outputfile> $ test.py -i inputfile Input file is " inputfile Output file is " Strings A stringiscreatedby enteringtextbetweentwosingle ordouble quotationmarks. -> 'HelloWorld'or "HelloWorld" Some characters can't be includedinstringdirectly,example of these charactersare single quoteand double quotes,tabs, arbitraryunicode characters. Put a backslashbefore these charactersif youaddthese special charactersinyourstring. "Ram's brothername is "Raj""-->Ram's brothername is Raj n - representsnew line. String formatting Providesamore powerful waytoembednon-stringswithinstrings. Stringformattingusesastring's format methodtosubstitute anumberof argumentsinthe string. nums= [4, 5, 6] msg = "Numbers:{0} {1} {2}".format(nums[0],nums[2],nums[3]) print(msg) -> Numbers:4 5 6 Stringformattingcan alsobe done withnamedargumets. a = "{x},{y}".format(x=5,y=12) print(a) -> 5, 12
  • 13. String operations Concatenation "spam"+"eggs"= spameggs "spam"+","+"eggs"= spam,eggs "2"+"2" = 22 1 + "2" = TypeError(ReferPythonerrorstable) Multiplication "spam"*3 = spamspamspam 4 * "3" = 3333 "s" * "r" = TypeError "s" * 7.0 = TypeError Replace "hellome".replace("me","world") ->helloworld Startswith "Thisis car".startswith("This") ->True Endswith Upper() "I am a boy".upper() ->I AM A BOY Lower() Split() "spam, eggs,ham".split(",") Variables In python,variablesdon'thave specifictypes,soyoucan assigna stringto a variable,andlaterassignan integertothe same variable. >>> a = 100 >>>print(a) 100 >>>a = "Raj" >>>print(a) 'Raj' Variable names: The onlycharacters that are allowedare letter,numbersandunderscores.Also,theycan'tstart with numbers. NotfollowingtheserulesresultsinSyntaxErrorerror. Pythonisa case sensitiveprogramminglanguage.Thus,Lastname andlastname are twodifferent variable namesinPython. Tryingto reference avariable thathasnot assignedinthe programcausesan error (NameError). >>>a = "raj" >>>a raj >>>b NameError:name 'b' isnot defined. >>>del a
  • 14. del statement del statementusedtoremove avariable fromprogram. Special operators Pythondoesn'tsupportspecial operators++and --.But,it supportsinplace operators(referoperation table above) Interpreterthrowssyntax errorif programuses++ or -- operators. Example: File "./prog.py", line 12 a++ ^ SyntaxError: invalid syntax if statements use if statementstorun code whencertainconditionholds. if expression: statements Pythonusesindentation(white spacesatthe beginningof aline) todelimitblocksof code.Other languages,suchas,C, use curlybraces to accomplishthis.But,inPythonindentationismandatory; program won'tworkwithoutit.Asyou can see,the statementsinthe if shouldbe indented. elif (short form of else if) the elif (shortforelse if) statementisashortcutto use whenchainingif andelse statements. if expression: statement else: if expression: statement can be modifiedasbelow if expression: statement elif expression: statement
  • 15. Boolean logic Booleanlogicisusedtomake more complicatedconditionsfor itstatementsthatrelyon more than one condition. Python'sBooleanoperatorsare and,or, andnot. While loops while condition: statement1 statement2 infinite loop while 1==1: print("inthe loop") break To enda while loopprematurely,the breakstatementcanbe used. i = 0 while 1==1: print(i) i = i +1 if i >= 5: printf("breaking") break continue Unlike break, continue jumpsbackto the top of the loop,ratherthan stoppingit. operator precedence == has higherprecedencethan or. Python'sorderof operationsisthe same as that of normal mathematics. the followingtable listsall of Python'soperators,fromhighestprecedence tolowest. Operator Description ** Exponentiation ~ + - Complement,unaryplus/minus * / %// Multiplication,division.moduloandfloordivision + - Addition/subtraction >> << Rightand leftbitwise shift & Bitwise AND
  • 16. ^ | Bitwise exclusive ORandregularOR <= < > >= Comparisons = %= /= //= -= += *= **= Assignmentoperators isis not Identityoperators innot in Membershipoperator not or and Logical operators More on else statements Else with loops Usingelse withforand while loops,the code withinit iscalledif the loopfinishednormally(whena breakstatementdoesn’tcause anexitfromthe loop) For I inrange(10): if (i==999): break Else: print(“Unbroken”) Else with try/except The else statementcanalsobe usedwithtry/exceptstatements.In thiscase,the code withinitisonly executedif noerroroccurs inthe try statement. Try: print(1) exceptZeroDivisionError: print(2) else: print(3) o/P: 1 3 Lists Listsare one type of objectin Python.Theyare usedto store an indexedlistof items. A listiscreatedusing square brackets withcommas separatingitems.Iteminthe listcanbe accessesby usingitsindex insquare brackets. A comma can be placedafterlastitemalso,itsvalidonly. words= ["Hello","world","!"] print(words[0])
  • 17. print(words[1]) print(words[2]) Empty list An emptylistiscreatedwithanemptypairof square brackets. empty_list=[] print(empty_list) -->o/p:[] Nested lists Listscan alsoinclude differentitemtypesandalsobe nestedwithinotherlists. num= 3 things= ["string",0, [1, 2, num],4.56] print(things[1]) print(things[2]) print(things[2][2]) Errors IndexError:whentryto accessout of boundvalues.print(things[4]) TypeError:whentry to accessintegerorfloat typesusingindex. No errorwill be seenforstringtype.Example,str="Helloworld",print(str[0]),o/P:H List operations Assignment The itemat certainindex ina listcan be reassigned. AdditionandMultiplication Listscan be addedandmultipliesinthe same wayas strings nums= [1, 2, 3] print(nums+[4, 5, 6]) -> [1,2,3,4,5,6] print(nums*3) -> [1,2,3,1,2,3,1,2,3] List andstringsare similarinmanyways - stringscan be thoughtof as listsof charactersthat can't be changed. in operator To check if an itemisinlist,the in operatorcan be used.It returns True if the itemoccurs one or more timesinthe list,and False if it doesn't.
  • 18. words= ["spam","eggs","spam","sause"] print("spam"inwords) ->True print("tomo"inwords) ->False The in operatoris alsousedto determinewhetherornota string issubstringof anotherstring. not operator To check if an itemisnot ina list. print(not4 innums) -> True print(4not innums) -> True Loops words= ["hello","world","spam"] for wordinwords: print(word) o/p: hello world spam for i in range(3): print("hi") o/p:hi hi hi List slices Providesmore advancedwayof retrievingvaluesfromalist. if the firstnumberina slice isomitted,itistakentobe the start of the list.If the 2nd numberisomitted, it istakento be the end. squares= [0, 1, 4, 9, 16, 25] print(squares[1:4]) ->[1, 4, 9] print(squares[0:1]) ->[0] print(squares[:3]) ->[0, 1, 4] print(squares[4:]) ->[16, 25] List slicescanalsohave a 3rd number,representingthe step,toinclude onlyalternate valuesinthe slice. print(squares[2:5:2]) ->[4, 16] Negativeindexing Negative valuescanbe usedinlistslicing(andnormal listindexing). Whennegative valuesare usedforthe firstand2nd values ina slice (ora normal index),they count fromthe endof the list.
  • 19. print(squares[1:-1]) ->[1, 4, 9, 16] If Negative value isusedforthe step,the slice isdone backwards.Using[ : : -1] as slice isa commonand idiomaticwaytoreverse alist. List comprehensions List comprehensionsare auseful wayof quicklycreatinglistswhose contentsobeyasimple rule. cubes= [i**3 fori in range(5)] print(cubes) ->[0, 1, 8, 27, 64] A listcomprehensioncanalsocontainan if statementtoenforce aconditiononvaluesinthe list. evens= [i**2 for i in range(10) if i**2 %2 == 0] print(evens) -->[0,4, 16, 36, 64] Tryingto create a listina veryextensive range willresultina MemoryError. even= [2*i fori in range(10**1000)] -> MemoryError. Thisissue issolvedby generators. List functions Function Description list.append(item):isamethodof listclass and hence can be accessedusing dot before. Addsan itemto the endof an existinglist. Nums= [1, 2, 3] Nums.append(4) Print(nums) ->[1, 2, 3, 4] len() Get the numberof itemsina list. print(len(nums)) ->4 list.insert(index,item) Allowstoinsertanew itemat any positioninthe list. Nums.insert(1, 10) print(nums) ->[1,10, 2, 3, 4] list.index(item) Findsthe firstoccurrence of a listitemandreturns thisindex. If the itemisn'tinthe list,itraisesa ValueError. print(nums.index(10)) ->1 print(nums.index(20)) ->ValueError:20is notin the list max(list) Returnsthe listitemwiththe maximumvalue min(list) Returnsthe listitemwiththe minimumvalue list.count(item) Returnsa count of how manytimesanitemoccurs ina list. list.remove(item) Removesanitemfroma list list.reverse() Reversesitemsinlist list(range(count)):Createsa sequential listof Nums= list(range(5))
  • 20. numbers.range byitself createsarange object, and thismustbe convertedtoa list. print(nums) ->[0,1, 2, 3, 4] list(range(first,end)):Producesalistfromthe first to the end Nums= list(range(2,7)) print(nums) ->[2,3, 4, 5, 6] list(range(first,end,interval)) Nums= list(range(2,7,2)) print(nums) ->[2,4, 6] all and any Take a listas argumentandreturnTrue if all or any (respectively) of theirargumentsevaluatetoTrue. Nums= [55, 44, 33] If all([i>5fori innums]): print("all are largerthan5") If any([i%2== 0 for i in nums]): Print("atleastone iseven") Enumerate() Usedto iterate throughthe valuesandindicesof listsimultaneously. For v inenumerate(nums): Print(v) o/p:(0, 55) (1, 44) (2, 33) Sets Setsare data structures,similartolistsordictionaries. Theyare createdusingcurlybraces,or the set function. num_set= {1, 2, 3, 4} word_set= set(["spam","eggs"]) print(3innum_set) -> True print("spam"notinword_set) -> False To create an emptyset,youmust use set(),as{} createsan emptydictionary. Setsare unordered,whichmeansthattheycan'tbe indexed. Theycannot containduplicate elements.Due tothe waytheyare stored,itsfasterto check whetheran itemispart of a set,ratherthan part of a list. Insteadof usingappend() toadd to a set,use add() The methodremove() removesaspecificelementfromaset, pop() removesanarbitraryelement. Mathematical operations - union/intersection Setscan be combinedusingmathematical operations.
  • 21. unionoperator| intersectionoperator& difference operator- symmetricdifference operator^ first= {1, 2, 3, 4} sec = {4, 5, 6} print(first|sec) -> {1, 2, 3, 4, 5, 6} print(first&sec) -> {4} print(first-sec) -> {1, 2, 3} print(first^sec) -> {1, 2, 3, 5, 6} Functions and modules create a functionbyusingthe def statementandmustbe definedbefore theyare called,elseyouwould see NameError. Functionscanbe assignedandreassignedtovariablesandlaterreferencedby those values def my_func(): print("Iamin function") my_func() func2 = my_func() func2() Arguments Functionscanalso be usedas argumentsof otherfunctions def my_func(word): print(word+ "!") my_func("Hello") def sum(x,y): print(x+y) sum(5, 8) def add(x,y): returnx+y def do_twice(func,x,y): returnfunc(func(x,y),func(x,y)) a = 5 b = 10 print(do_twice(add,a,b)
  • 22. Return values def max(x,y): if x >= y: returnx else: returny z = max(8,5) print(z) Docstrings Unlike conventional comments,docstringsare retainedthroughoutthe runtime of the program.This allowsthe programmedtoinspectthese commentsatruntime. Modules Modulesare piecesof code that otherpeople have writtentofulfill commontasks,suchasgenerating randomnumbersetc. Tryingto importa module thatisn'tavailable causesanImportError. Usage: addimport module_name at the top of yourcode.And,access functions/variable using module_name.var Example: importrandom for i in range(5): val = random.randint(1, 6) print(val) Import certainfunctions from module_name import var for mathimportpi print(pi) for mathimportpi,sqrt print(sqrt(25)) Importa module underadifferentname using askeyword frommath importsqrt as square_root print(square_root(100)) Standard Library 3 typesof modules
  • 23. 1. those you write yourself 2. those you install fromexternal sources 3. those are pre-installedwithpython -->Standardlibrary Tasks that can be done by usingstandardlibraryinclude stringparsing data serialization testing|debugging manipulatingdates,emails commandline argumentsandsoon. Python'sextensive standardlibraryisone of itsmainstrengthsasa language. ExceptionHandling Exceptionsoccurwhensomethinggoeswrong,due toincorrectcode orinput. Whenan exceptionoccurs,the programimmediatelystops. Handle exceptions:use tryand exceptstatements. Useful whendealingwithuserinput. The try blockcontainscode that mightthrow an exception.If thatexceptionoccurs,the code inthe try blockstopsbeingexecuted,andthe code inthe exceptblockis run.If noerror occurs, the code in the exceptblockdoesn'trun. try: num1 = 7 num2 = 0 print(num1/num2) exceptZeroDivisionError: print("Anerroroccurreddue to zerodivision") except(ValueError,TypeError): print("Erroroccurred") An exceptstatementwithoutanyexceptionspecifiedwill catchall errors. try: print(7/0) except: print("erroroccurred") finally: print("Thiscode will runnomatterswhat") The finallystatementalwaysrunsaftertry/exceptblocksevenincase of exception.
  • 24. Raising exception raise statementcanbe usedto raise exceptionandspecifythe type of exceptionraised. Youcanpass argumentfordetails. print(1) raise ValueError print(2) raise NameError("Invalidname found") Assertions An Assertionisasanity-checkthatyoucan turnon or turn off whenyouhave finishedtestingthe program. An expression istested,andif the resultcomesupfalse,andexceptionisraised. Programmers oftenplace assertionsatthe start of a functiontocheckfor validinput,andaftera functioncall tocheck forvalidoutput. print(1) assert2 + 2 == 4 print(2) assert1 + 1 == 3 print(3) o/p: 1 2 AssertionError The assert can take a secondsargument thatis passedtothe AssertionErrorraisedif the assertionfails. temp= -10 assert(temp>= 0),"Colderthanabsolute Zero!" o/p:AssertionError:Colderthanabsolute zero! Files handling Opening files - open() myfle =open("filename.txt") The argumentof the open() functionisthe pathto the file. Youcan specifythe mode usedtoopena file by 2nd argument.
  • 25. r : Openfile inreadmode,whichisthe default. w : Write mode,forre-writingthe contentsof the file a : Appendmode,foraddingnewcontent tothe endof the file b : Openfile ina binarymode,usedfornon-textfiles(image/soundfiles) myfile =open("filename.txt","a"); myfile.close() Reading Files - read() cont = myfile.read() print(cont) ->will printall the contentsof the file. Provide numberof bytesthatreadfromfile bypassingvalue tothe read() print(myfile.read(10)) ->10 bytesread Afterall contentsina file have beenread,anyattempttoreadfurtherfromthat file will returnan emptystring,because youare tryingto read from the endof the file. To retrieve eachline inafile,use readlines function.Itreturnalistin whicheachelementisaline inthe file. file =open("filename.txt","r") print(file.readline()) file.close() o/p: ['line1n','line2n','line3'] Writing Files - write() write() - writesastringto the file. "w"mode will create afile if notexist. If exist,the contentsof the file will be deleted. write() returnsthe numberof byteswrittentothe file,if successful. file =open("new.txt","w") file.write("Writtingtothe file") file.close() file =open("new.txt","r") print(file.read()) file.close() with statement It ismandatoryto close the file afterread/writingthe fileevenincase of exceptionoccur.
  • 26. An alternative wayof doingthisisusingwithstatement.The fileisautomaticallyclosedatthe endof the with statement,evenif exceptionoccurwithinit. withopen("new.txt") asf: print(f.read()) None representsabsence of the value. The None objectisreturnedbyany functionthatdoesn'texplicitlyreturnanythingelse. def myfunc(): printf("Hi") var = myfunc() print(var) o/p: Hi None Dictionaries Dictionariesare datastructuresusedtomap arbitrary keystovalues. {"Key":Value}. Emptydictionaryis{} Each elementinadictionaryisrepresentedby key:value pair Dictionarykeyscanbe assignedtodifferentvalueslikelists. Tryingto index akeythat isn'tpart of the dictionaryreturnsa KeyError. primary= { "red":[255, 0, 0], "green":[0,255, 0], "blue":[0,0, 255], } print(primary["red"]) -->[255, 0, 0] primary["white"] =[200, 140, 100] primary["blue"] =[0,0, 245] print(primary["yellow"])-->KeyError:"yellow" Dictionarycan store any type of data as Value. Onlyimmutable objectscanbe usedas keystodictionaries.
  • 27. List anddictionariesare mutable objectsandhence can'tbe usedas keysinthe dictionary. bad_dict= {[1,2, 3]: "one twothree",} TypeError: unhashable type:list Dictionary Functions Search Use in andnot in nums= {1: "one",2: "two",3: "three",} print(1in nums) -> True print(1not in nums) -> False print(4not in nums) -> True get() Usedto get the valuesbyitsindex,butif the keyisnot found,itreturnsanotherspecificvalue(2nd argument) instead(Nonebydefault). pairs= {1: "apple","orange":[2,3], True:False,None:"True",} print(pairs.get("orange"))->[2,3] print(pairs.get(7)) ->None print(pairs.get(1234,"Notfound")) ->Notfound Tuples Similartolists,exceptthattheyare immutable (theycan'tbe changed).Also,these are createdusing parenthesis,ratherthansquare brackets. words= () -> emptytuple words= ("spam","eggs") or words= "spam","eggs" Tuple unpacking It allowsyoutoassigneach iteminan iterable toa variable. Numbers= (1, 2 ,3) a, b, c = numbers print(a) ->1 print(b) ->2
  • 28. Variable* A variable thatisprefacedwithanasterisk(*) takesall valuesfromthe iterable thatare leftoverfrom the othervariables A,b, *c, d = [1, 2, 3, 4 ,5 ,6, 7] print(a) -> 1 print(b) -> 2 print(c) ->[3, 4, 5, 6] print(d) -> 7 Ternary operator It takesthree arguments Status= 1 msg = “Logout” if status ==1 else “Login” print(msg) ->Logout Higher order functions Lambdas Whenfunctionsare createdusing lambdasyntax thenthe functionsare notassignedtoany variable unlike functionscreatednormallyusing def assignsittoa variable automatically. Stringsand integerscanbe createdonthe fly,withoutassigningthemtoavariable. Similarly,functions can be createdwithoutassigningthemtoanyvariable usinglambdakeyword. def my_func(f,arg): returnf(arg) my_func(lambdax:2*x*x, 5) Lambda functionsgettheirname fromlambdacalculus. Lambda functionsare notpowerful asnamedfunctions.Theycanonlydothingsthatrequire asingle expression - usuallyequivalenttoa single line of code. #namedfunction def polynomial(x): returnx**2 + 5*x + 4 print(polynomial(-4))
  • 29. #lambda print(lambdax:x**2+ 5*x + 4, -4) Lambda functionscanbe assignedtovariables, andusedlike anormal functions double =lambdax: x * 2 print(double(4)) map and filter map and filteroperate onlists(orsimilarobjectscalled itterables) Maps Lambda def add_five(x): returnx+5 nums= [1, 2, 3, 4, 5] result= list(map(add_five,nums)) print(result) -> [6, 7, 8, 9, 10] Nums= [1, 2, 3, 4, 5] result= list(map(lambdax:x+5,nums)) print(result) -> [6,7, 8, 9, 10] The function filterfiltersaniterable byremovingitemsthatdon'tmatch a predicate res= list(filter(lambdax:x%2==0, nums)) print(res) -> [2, 4] Generators Generatorsare a type of iterable,likelistsortuples. Unlike lists,theydon'tallowindexingwitharbitraryindices,buttheycanstill be iteratedthroughwith for loops. Generatorscan be createdusingfunctionsandthe yieldstatement. def countdown(): i=5 while i>0: yieldi i- = 1 for i in countdown(): print(i) o/p: 5 4 3 2 1 Yieldstatementisusedtodefine agenerator,replacingthe returnof afunctionto provide aresulttoits calledwithoutdestroyinglocal variables.
  • 30. Due to the fact thatthey yieldone itemat a time,generatorsdon'thave the memoryrestrictionsof lists. In fact,theycan be infinite. In short, generatorsallowsyouto declare afunction that behaveslikeaniteratori.e.itcanbe usedina for loop. def infinite_sevens(): while True: yield7 for i in infinite_sevens(): print(i) Finite generatorscanbe convertedintolistsbypassingthemasargumentstothe listfunction.Using generatorsresultsinimprovedperformance,whichisthe resultsof the lazygenerationof values,which translatestolowermemoryusage.Furthermore,we donotneedtowaituntil all the elementshave beengeneratedbefore we starttouse them. def numbers(x): for i in range(x): if i%2 == 0: yieldi print(list(numbers(11))) -> o/P:[0, 2, 4, 6, 8, 10] Decorators Providesawayto modifyfunctionsusingotherfunctions. Thisis ideal whenyouneedtoextendthe functionalityof functionsthatyoudon't wantto modify. def decor(func): def wrap(): print("=====") func() print("=====") returnwrap def print_text(): print("Hello") decorated= decor(print_text) decorated() def print_text(): print("hello") print_text= decor(print_text) @decor def print_text(): print("Hello")
  • 31. Object Oriented Programming Classes 3 paradigmsof programming 1. Imperative - usingstatements,loops,andfunctionsassubroutines 2. Functional - usingpure functions,higherorderfunctions,andrecursion 3. ObjectOrientedprogramming(OOP) Objectsare createdusingclasses,whichare actuallythe focal pointof OOP. A Classcan be describedasan object'sblueprint,description,ordefinition.Same classcanbe usedfor creatingmultiple differentobjects. class Cat: def __init__(self,color,legs): self.color=color self.legs=legs def bark(self): print("woof") felix =Cat("ginger",4) rover= Cat("dog-colored",4) stumpy= Cat("brown",3) __init__ Calledwhenaninstance (object)of the classiscreated,usingthe classname as function. All methodsmusthave self astheirfirstparameter,althoughitisn'texplicitlypassed,pythonaddsthe self argumenttothe listforyou; youdo not needtoinclude itwhenyoucall the methods. The __init__ methodis calledthe classconstructor. Methods Definedtoaddfunctionalitytothem. Inheritance Inheritance providesawayto share functionalityb/w calsses. classAnimal: def __init__(self,name,color): self.name =name self.color=color classCat(Animal): def purr(self): print("Purr..")
  • 32. classDog(Animal): def bark(self): print("woof") super().purr() classRed_dog(Dog): def sec_method(self): print("secondmethod") A classthat inheritsfromanotherclassiscalledasubclass. A classthat is inheritedfromiscalledasuperclass. If a classinheritsfromanotherwiththe same attributesormethods,itoverridesthem. Super function The function superis a useful inheritance relatedfunctionthatreferstothe parentclass. Magic Methods These are special methodswhicha double underscores at the beginningandendof theirnames.They are alsoknown as dunders. One commonuse of themis operator overloading. Operator overloading __add__ for + __truediv__for / __floordiv__for// __mod__ for% __sub__ for- __and__ for & __pow__ for ** __xor__ for^ __or__ for | classVector2D: def __init__(self,x,y): self.x =x self.y=y def __add__(self,other): returnVector2D(self.x +other.x,self.y+other.y) first= Vector2D(5,7) sec = Vector2D(12, 9) result= first+ sec __lt__ for< __le__ for <= __eq__ for== __ne__ for!= __gt__ for > __ge__ for>= Object Lifecycle Made up of creation,manipulationanddestruction.
  • 33. Garbage collection The processof deletingobjectswhentheyare nolongerneedediscalled garbage collection. Whenan object'sreference countreachesZero,pythonautomaticallydeletesit. Data Hiding A keypart of OOP is encapsulation, whichinvolvespackagingof relatedvariablesandfunctionsinto single easy-to-useobject- an instance of a class. A relatedconceptis data hiding,whichstatesthat implementationdetailsof aclassshouldbe hidden, and a cleanstandardinterface be presentedforthose whowantto use the class. Thiswill be done usingprivate methodsattributesinotherprogramminglanguage. In python,there are noways of enforcingamethodor attribute be strictlyprivate. Weeklyprivate methodsandattributeshave a single underscore atthe beginning. Stronglyprivate methodsandattributeshave a double underscore atthe beginning. Class methods Classmethodsare calledbya class,whichis passedtothe cls parameterof the method. classRectangle: def __init__(self,width,height): self.width=width self.height=height def calculate_area(self): returnself.width*self.height @classmethod def new_square(cls,side_length): returncls(side_length,side_length) square = Rectangle.new_square(5) print(sqaure.calculate_area()) Note:Technically,the parameters self andclsare just conventions;theycouldbe changedtoanything else. Static methods These are similartoclass methods,excepttheydon'treceive anyadditional arguments;theyare identical tonormal functionsthatbelongstoaclass. Theyare markedwiththe staticmethod classPizza: def __init__(self,toppings):
  • 34. self.toppings=toppings @staticmethod def validate_topping(topping): if topping== "pineapple": raise ValueError("NoPineaaple") else: returnTrue ingredients=["cheese","onions","spam"] if all(Pizza.validate_topping(i) fori iningredients): pizza= Pizza(ingredients) Staticmethodsbehave like plainfunctions,exceptforthe factthat youcan call themfrom an instance of the class. Properties Propertiesprovide awayof customizingaccesstoinstance attributes. Theyare createdbyputtingthe property decoratorabove a method,whichmeanswhenthe instance attribute withthe same name as the methodisaccessed,the methodwillbe calledinstead. One commonuse of a propertyisto make an attribute read-only. classPizza: def __init__(self,toppings): self.toppings=toppings @property def pineapple_allowed(self): returnFalse @pineapple_allowed.setter def pineapple_allowed(sefl,value): if value: pwd= input("Enterpassword") if pwd== "admin" self._pineapple_allowed=value else raise ValueError("Alert..Intruder") pizza= Pizza(["cheese","tomoto"]) print(pizza.pineapple_allowed) pizza.pineapple_allowed=True o/p: False AttributeError:can'tset attribute -->If setterisnot defined
  • 35. Enter password:admin True Propertiescanalsobe setby defining setter/getterfunctions. The setterfunctionsetsthe correspondingpropery'svalue. The gettergetsthe value. Regular Expressions RegularExpressionsare powerful tool forvariouskindsof stringmanipulation. Matching pattern Standardlibraryisre. Needtoimportit andcall the belowfunction. Importre re.match(“spam”,“eggsspam”) ->Not found re.search(“spam”, “eggsspam”) ->Found re.findall(“spam”,“eggsspam”) ->[‘spam’] Search() Findsa match of a patternanywhere inthe string Match() Looksat the beginningof the stringonly Findall() Returnsa listof all substringsthatmatch a pattern Finditer() Doesthe same thingas findall() exceptitreturns an iterator,ratherthan a list re.search() The search returnsan objectwithseveral methodsthatgive detailsaboutit.These methodsinclude group() whichreturnsstringmatched, start() andend() whichreturnthe start and endingpositionsof the match, and span() whichreturnsthe start and endpositionsasa tuple. Importre pattern= r”pam” match = re.search(pattern,“eggspamsausage”) if match: print(match.group()) print(match.start()) print(match.end()) print(match.span())
  • 36. o/p: pam 4 7 (4, 7) re.sub() - search & replace sub() methodreplacesall occurrencesof the patterninstringwithreplace string,substitutingall occurrences,unlessmax provided. re.sub(pattern,repl,string,max=0) importre str = “My name is David.Hi David” pattern= r”David” newstr= re.sub(pattern,“Raj”,str) print(newstr) -> My name isRaj. Hi Raj. Metacharacters Allowsustocreate regularexpressiontorepresentconceptslike “one ormore” repetitionsofa vowel. . (dot)character Thismatchesany character, otherthan a new line. Importre pattern= r”gr.y” if re.match(pattern,“grey”): print(“Match1”) ^ and $ - start and end Thismatchesthe start and endof a string. Patter= r”^gr.y$” re.match(pattern,“grey”) ->True re.match(pattern,“spamgrey”) ->False Character classes Provide away to matchonlyone of a specificsetof characters. A character classis createdbyputtingthe characters itmatchesinside square brackets. Pattern= r”[aeiou] re.search(pattern, “grey”) - > True re.search(pattern,“myths”) - > False
  • 37. Supportsrange of charactersalso. [a-z]-> matchesanylowercase alphabeticcharacter [G-P]-> matchesanyuppercase characterfrom G to P [0-9] [A-Za-z] ^ character Place a ^ at the start of a character class toinvert it. Pattern= r”[^A-Z]” re.search(“Hi Raj”) ->True re.search(“HIRAJ”) ->False More Metacharacters * character Zeroor more repetitions + character One or more repetitions ? character Zeroor one repetitions Curlybraces Usedto representthe numberof repetitionsb/w twonumbers. Pattern= r”9{1, 3}$” Re.match(pattern,“9”) ->True re.match(pattern,“999”) -> True re.match(pattern,“9999”) -> False Groups A groupcan be createdbysurroundingpartof a regularexpressionwith parenthesis. Thismeansthat a group can be givenas an argument to metacharacterssuchas * and? Pattern= r”egg(spam)*” re.match(pattern,egg) ->True re.match(pattern,spam) ->False The contentsof groupsina matchcan be accessedusingthe group function. A call of group(0) or group() returnsthe whole match. A call of group(n),where nisthe greaterthan 0, returnsthe nthgroup fromthe left.
  • 38. Pattern= r”a(bc)(de)(f(g)h)I” match = re.match(pattern,“abcdefghijklmnop”) if match: Print(match.group())->abcdefghi print(match.group(0)) ->abcdefghi print(match.group(1)) ->bc print(match.group(2)) ->de print(match.groups()) ->(‘bc’,‘de’,‘fgh’,‘g’) | character Means or. Pattern= r”gr(a|e)y” re.match(pattern,“grey”) ->True Named groups Namedgroupshave format (?P<name>…),where name isthe name of the group, … isthe content. Theybehave exactlysame asthe normal groupsexcepttheycanbe accessedby group(name) in additiontoitsnumber. Pattern= r”(?P<first>abc)(?:def)(ghi)” match = re.match(pattern,“abcdefghi”) if match: Print(match.group(“first”)) ->abc print(match.groups()) ->(‘abc’,‘ghi’) Non-capturinggroups have the format (?:…).Theyare not accessible bythe groupmethods,sotheycan be addedto an existingregularexpressionwithoutbreakingthe numbering.See above. Special Sequences number - Backslash Thismatchesthe expressionof the groupof that number. 1to 99 allowed. Pattern= r”(.+) 1” re.match(pattern,“wordword”) ->True re.match(pattern,“abccde”) ->False Note:“(.+) 1” isnot the same as “(.+) (.+)”.Because, 1refersto the firstgroup’ssubexpression,which isthe matchedexpressionitself,andnotthe regularexpressionpattern.
  • 39. d and D sequence d – matchesthe digits. D – matchesanythingthatisn’t a digit Pattern= r”(D+d)” re.match(pattern,“Hi 999”) -> True s and S sequence s – matchesthe white spaces. S – matchesanythingthatisn’t a white space Pattern= r”(S+s)” re.match(pattern,“Hi ”) -> True w and W sequence d – matchesthe wordcharacters. D – matchesanythingthatisn’t a word character A Sequence The sequences A andZ match the beginningandendof astring,respectively. b sequence It matchesthe emptystringb/w wand W characters, or w characters and the beginningorendof the string. Informally,itrepresentsthe boundaryb/w words. Pattern= r”b(cat)b” re.search(pattern,“The catsat!” -> True re.search(pattern,“we scattered”) ->False “b(cat)b”basicallymatchesthe word“cat”surroundedbywordboundaries. Email extraction To extractemail like [email protected] fromtext,use below pattern Pattern= r”([w.-]+)@([w.-])(.[w.]+)” [w.-] ->matchesone or more wordcharacter, dot or dash Str = “Please [email protected] forassistance” match = re.search(pattern,str) if match:
  • 40. print(match.group()) o/p:[email protected] Pythonicness & Packaging Importthis module printsthe Zenof Pythonwhenimported. There are 20 principlesinthe Zenof Python,butonly19 linesof test.The 20th principle isamatterof opinion,butourinterpretationisthatthe blankline means“Use white spaces” PEP-PythonEnhancement Proposals PEP are suggestionsforimprovementstothe language,made byexperiencedPythondevelopers. PEP8 is a style guide onthe subjectof writingreadablecode. - Modulesshouldhave short,all lowercase names - Classnamesshould be inCapWordsstyle - Most variablesandfunctionnamesshouldbe lowercase withunderscores - Constantsshouldbe CAPSWITH UNDERSCORES - Namesthatwouldclashwithpythinkeywordshouldhave atrailingunderscore. - Linesshouldn’tbe longerthan80 characters - “from module import*”shouldbe avoided - There shouldbe onlybe one statementperline Packaging Referstoputtingmodulesyouhave writteninastandardformat,so that otherprogrammerscaninstall and use themwithease.Thisinvolvesuse of the modules setuptoolsanddisutils. Place all the filesyouwantto putin a libraryinthe same parentdirectory.Thisdirectoryshouldalso containa file called __init__.py,whichcan be blankbut mustbe presentinthe directory. Thisdirectorygoesintothe otherdirectorywhichwill have readme andlicense,aswell asan important file called setup.py Sololearn/ License.txt Readme.txt Setup.py Sololearn/ __init__.py sololearn.py sololearn2.py
  • 41. Setup.py Thiscontainsinformationnecessarytoassemble the package soitcan be uploadedto PyPIand istalled withpip From disutils.core importsetup Setup( name=”Sololearn”, version=’0.1dev’, packages=[‘sololearn’,], license=’MIT’, long_description=open(‘README.txt’).read(), ) To builda source distribution python setup.pysdist To builda binarydistribution python setup.pybdist To uploadpackage python setup.pyregister pythin setup.pysdistupload Install apackage with pythonsetup.pyinstall Packaging for Users Py2exe tool can be usedtopackage a pythonscript,alongwithlibrariesitrequires,intoasingle executable. PyInstallerand cx_Freeze serve the same purpose. Function arguments Pythonallowstohave functionwithvaryingnumberof arguments. *args Using*args as a functionparameterenablesyoutopassan arbitrarynumberof argumentsto that function.The argumentsare thenaccessible asthe tuple argsinthe bodyof the function. Def function(named_arg,*arg): print(named_arg) print(args) Function(1,2,3, 4, 5)
  • 42. o/p: 1 (2, 3, 4, 5) The parameter*args must come afterthe namesparameterstoa function.The name argsis justa convention;youcanchoose to use another. **kwargs – keyword arguments Thisallowsyouto handle namedargumentsthatyouhave notdefinedinadvance. The keywordargumentsreturnsadictionary,inwhichthe keysare the argumentnames, andthe values are the argumentvalues. Def my_func(x,y=7,*args, **kwargs): print(kwargs) My_func(2,3, 4, 5, 6, a=7, b=8) o/P: {‘a’:7, ‘b’:8} The argumentsreturnedbythe **kwargs are notincludedin*args. Major 3rd party libraries Django The most frequentlyusedwebframeworkwritteninPython,itpowerswebsitesthatincludeInstagram and Dicqus. CherryPy and Flask Are alsopopularwebframeworks BeautifulSoup It isveryuseful,andleadstobetterresultsforscrappingdatafromwebsites. Matplotlib Allowsyoutocreate a graph basedon data inpython NumPy It allowsforthe use of multidimentional arraysthatare much fasterthan native pythonsolutionof nestedlists.
  • 43. SciPy Containsnumerousextensionstothe functionalityof NumPy Panda3D For 3D games Pygame for2D games List Vs Dictionary Vs Tuples Vs Sets Lists Sets Dictionaries Tuples List = [10, 12, 15] Set= {1, 23, 34} Print(set) ->{1, 23,24} Set= {1, 1} print(set) ->{1} Dict = {"Ram": 26, "mary": 24} Words = ("spam", "egss") Or Words = "spam", "eggs" Access:print(list[0]) Print(set). Setelementscan't be indexed. print(dict["ram"]) Print(words[0]) List[0] = 100 Setelementscan't be indexed.So,use add() Set.add(7) Dict["Ram"] = 27 Words[0] = "care" -> TypeError Mutable Mutable Mutable Immutable - Values can't be changedonce assigned List = [] Set= set() Dict = {} Words = () Fasterthan listsbut theycan't be changed. Slicingcanbe done print(list[1:2]) ->[12] Notdone. Slicingcanalsobe done on tuples Can't contain duplicate elements. Use listsif youhave a collectionof datathat doesn'tneedrandom access. Use listswhenyouneed a simple,iterable collectionthatis modifiedfrequently. - Membership testingandthe eliminationof duplicate entries. - whenyouneed uniquenessforthe elements. - Whenyouneeda logical associationb/w key:value pair. - whenyouneedfast lookupforyourdata, based on a customkey. - whenyourdata isbeing constantlymodified. Use tupleswhenyour data cannot change. A tuple isusedin comibnationwitha dictionary,for example,atuple might representakey, because its immutable.
  • 44. itertools -standard library The module itertoolsisastandardlibrary.Itproducesinfiniteiterators. count():counts upinfinitelyfromavalue cycle():infinitelyiteratesthroughaniterable (alistora string) repeat():repeatsanobjects,eitherinfinitelyoraspecifiednumberof times. fromitertoolsimportcount for i in count(3): print(i) if i >= 11: break PythonVs C C language Pythonlanguage Special operators(++and --) works I.e.a++; --a; It doesn'tsupport++ and --.Throws Syntax error. Each statementinC endswithsemicolon; No use of ; here. Curlybracesare usedto delimitblocksof code If (condition) { Statement1; Statement2; } It useswhite spacesforthispurpose If condition: Statement1 Statement2 Example: If 10 > 5: print("10 isgreaterthan 5") if 10 > 9: print("10isgreaterthan 9") else: print("5is greaterthan10") Compilingthe programbefore executionis mandatory Pythonprogramdirectlyexecuted byusing interpreter. Nocompilerhere. Booleanoperatorsare && and || and! Booleanoperatorsare and, or and not Uses // for one line comment Uses /* */ for multiple line comment Uses # for one line comment Uses """ """ for multi line comments (Docstrings). Uses #include toimportstandardlibraryfunctions #include<stdio.h> Uses importkeywordtoinclude standardlibrary functions Importmath Voidassert(intexpression) Expression -Thiscanbe a variable orany C expression.If expressionevaluatestoTRUE, assert() doesnothing.If expressionevaluatesto FALSE,assert() displaysanerrormessage on stderr(standarderrorstreamto displayerror assertexpression Example assert1 + 1 == 3
  • 45. messagesanddiagnostics) andabortsprogram execution. NULL None - representsabsence of value Don't have automaticmemorymanagement. AutomaticGarbage collection. Web scraping: webbrowser library https://automatetheboringstuff.com/chapter11/ Webscrapingis the term forusinga program to downloadandprocesscontentfromthe Web.For example,Googlerunsmanywebscrapingprogramsto index webpagesforitssearchengine. webbrowser. Comes with Python and opens a browser to a specific page. Webbrowser.open() webbrowser.open(url,new=0,autoraise=True) Displayurl usingthe defaultbrowser.If new is0,the url is openedinthe same browserwindow if possible.If newis1,a newbrowserwindow isopenedif possible.If new is2, a new browserpage (“tab”) is openedif possible.If autoraise isTrue,the window israisedif possible (notethatundermany windowmanagersthiswill occurregardlessof the settingof thisvariable). Note that onsome platforms,tryingtoopena filename usingthisfunction,mayworkandstart the operatingsystem’sassociatedprogram.However,thisisneithersupportednorportable. webbrowser.open_new(url) Openurl in a newwindowof the defaultbrowser,if possible,otherwise,openurl inthe onlybrowser window. webbrowser.open_new_tab(url) Openurl in a newpage (“tab”) of the defaultbrowser,if possible,otherwise equivalenttoopen_new(). webbrowser.get([name]) Returna controllerobjectforthe browsertype name.If name isempty,returna controllerfora default browserappropriate tothe caller’senvironment. import webbrowser url = 'http://idiotinside.com' # Open URL in new browser window webbrowser.open_new(url) # opens in default browser # Opens in safari browser webbrowser.get('safari').open_new(url) # Open URL in a new tab
  • 46. webbrowser.open_new_tab(url) # opens in default browser # Opens in safari browser webbrowser.get('safari').open_new_tab(url) Type Name Class Name Notes 'mozilla' Mozilla('mozilla') 'firefox' Mozilla('mozilla') 'netscape' Mozilla('netscape') 'galeon' Galeon('galeon') 'epiphany' Galeon('epiphany') 'skipstone' BackgroundBrowser('skipstone') 'kfmclient' Konqueror() (1) 'konqueror' Konqueror() (1) 'kfm' Konqueror() (1) 'mosaic' BackgroundBrowser('mosaic') 'opera' Opera() 'grail' Grail() 'links' GenericBrowser('links') 'elinks' Elinks('elinks') 'lynx' GenericBrowser('lynx') 'w3m' GenericBrowser('w3m') 'windows-default' WindowsDefault (2) 'macosx' MacOSX('default') (3)
  • 47. Type Name Class Name Notes 'safari' MacOSX('safari') (3) 'google-chrome' Chrome('google-chrome') (4) 'chrome' Chrome('chrome') (4) 'chromium' Chromium('chromium') (4) 'chromium-browser' Chromium('chromium-browser') (4)