python introduction all the students.ppt

ArunkumarM192050 32 views 75 slides Jul 23, 2024
Slide 1
Slide 1 of 75
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75

About This Presentation

python introduction


Slide Content

UNIT-I: BASICS
Pythoninterpreterandinteractive
mode–Tokens-Datatypes–
Numbersandmatfunctions–Input
andoutputoperations-Comments
–Reservedwords–Indentation–
OperatorsandExpressions–
Precedenceandassociativity–Type
Conversion–Debugging–Common
errorsinPython.
1-1

1. INTRODUCTION
•Pythonisahigh-level,interpreted,interactiveandobject
oriented-scriptinglanguage.
•Pythonwasdesignedtobehighlyreadablewhichuses
Englishkeywordsfrequentlywhereasotherlanguagesuse
punctuationandithasfewersyntacticalconstructionsthan
otherlanguages.
1-2

INTRODUCTION(Cont…)
•Python is Interpreted:This means that it is processed at
runtime by the interpreter and you do not need to compile
your program before executing it. This is similar to PERL and
PHP.
•Python is Interactive:This means that you can actually sit at a
Python prompt and interact with the interpreter directly to
write your programs.
•Python is Object-Oriented:This means that Python supports
Object-Oriented style or technique of programming that
encapsulates code within objects.
•Python is Beginner's Language:Python is a great language for
the beginner programmers and supports the development of
a wide range of applications, from simple text processing to
WWW browsers to games.
1-3

Compiling and interpreting
•Many languages require you to compile (translate) your
program into a form that the machine understands.
•Python is instead directly interpreted into machine
instructions.
compile execute
outputsource code
Hello.java
byte code
Hello.class
interpret
outputsource code
Hello.py
1-4

History of Python
•PythonwasdevelopedbyGuidovanRossuminthelate
eightiesandearlyninetiesattheNationalResearchInstitute
forMathematicsandComputerScienceintheNetherlands.
•Pythonisderivedfrommanyotherlanguages,includingABC,
Modula-3,C,C++,Algol-68,SmallTalk,andUnixshelland
otherscriptinglanguages.
•Pythoniscopyrighted,LikePerl,Pythonsourcecodeisnow
availableundertheGNUGeneralPublicLicense(GPL).
•Pythonisnowmaintainedbyacoredevelopmentteamatthe
institute,althoughGuidovanRossumstillholdsavitalrolein
directingit'sprogress.
1-5

Python Features
•Easy-to-learn:Python has relatively few keywords, simple
structure, and a clearly defined syntax.
•Easy-to-read:Python code is much more clearly defined and
visible to the eyes.
•Easy-to-maintain:Python's success is that its source code is
fairly easy-to-maintain.
•A broad standard library:One of Python's greatest strengths
is the bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
•Interactive Mode:Support for an interactive mode in which
you can enter results from a terminal right to the language,
allowing interactive testing and debugging of snippets of
code.
1-6

Python Features (cont’d)
•Portable:Python can run on a wide variety of hardware
platforms and has the same interface on all platforms.
•Extendable:You can add low-level modules to the Python
interpreter. These modules enable programmers to add to or
customize their tools to be more efficient.
•Databases:Python provides interfaces to all major
commercial databases.
•GUI Programming:Python supports GUI applications that can
be created and ported to many system calls, libraries, and
windows systems, such as Windows MFC, Macintosh, and the
X Window system of Unix.
•Scalable:Python provides a better structure and support for
large programs than shell scripting.
1-7

Python Environment
•Unix (Solaris, Linux, FreeBSD, AIX, HP/UX, SunOS, IRIX etc.)
•Win 9x/NT/2000
•Macintosh (PPC, 68K)
•OS/2
•DOS (multiple versions)
•PalmOS
•Nokia mobile phones
•Windows CE
•Acorn/RISC OS
•BeOS
•Amiga
•VMS/OpenVMS
•QNX
•VxWorks
•Psion
•Python has also been ported to the Java and .NET virtual machines.
1-8

2. Python interpreter and interactive
mode
1-9

Python -Basic Syntax
•Interactive Mode Programming:
>>> print "Hello, Python!";
Hello, Python!
>>> 3+4*5;
23
1-10

•Script Mode Programming :
Invoking the interpreter with a script parameter begins
execution of the script and continues until the script is
finished. When the script is finished, the interpreter is no
longer active.
For example, put the following in one test.py, and run,
print "Hello, Python!";
print "I love COMP3050!";
The output will be:
Hello, Python!
I love COMP3050!
1-11

3. Tokens
•The smallest unit/element in the python
program/script is known as a Token or a
Lexical unit. Python has following Tokens:
–Keywords
–Identifiers
–Literals
–Operators
–Punctuators
1-12

Reserved Words:
and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield
Keywords contain lowercase letters only.
1-13

Python Identifiers:
•APythonidentifierisanameusedtoidentifyavariable,
function,class,module,orotherobject.
•AnidentifierstartswithaletterAtoZoratozoran
underscore(_)followedbyzeroormoreletters,underscores,
anddigits(0to9).
•Pythondoesnotallowpunctuationcharacterssuchas@,$,
and%withinidentifiers.
•Pythonisacasesensitiveprogramminglanguage.
•ThusManpowerandmanpoweraretwodifferentidentifiers
inPython.
1-14

Python Identifiers (cont’d)
•HerearefollowingidentifiernamingconventionforPython:
–Classnamesstartwithanuppercaseletterandallother
identifierswithalowercaseletter.
–Startinganidentifierwithasingleleadingunderscore
indicatesbyconventionthattheidentifierismeanttobe
private.
–Startinganidentifierwithtwoleadingunderscores
indicatesastronglyprivateidentifier.
–Iftheidentifieralsoendswithtwotrailingunderscores,
theidentifierisalanguage-definedspecialname.
1-15

Literals
•Literalsarethedataitemsthathaveafixed
orconstantvalue.
•Literalsareessentialbuildingelementsof
Pythonprogramming, expressingfixed
valuesdirectlyinsertedwithincode.
•Theyincludemanydatakinds,eachserving
aspecificroleinrelayinginformationtothe
interpreter
1-16

Literals: Types
•StringLiterals:Thetextwritteninsingle,double,ortriple
quotesrepresentsthestringliteralsinPython.Forexample:
“ComputerScience”,‘sam’,etc.Wecanalsousetriplequotesto
writemulti-linestrings.Astringliteralisasequenceof
characterssurroundedbyQuotes.
•Example:
•string = 'Hello'
•s = "World"
•A = "'Python is a
• high-level and
• general purpose language'"

1-17

Literals: Types
•CharacterLiterals:Characterliteralisalsoa
stringliteraltypeinwhichthecharacteris
enclosedinsingleordouble-quotes.
•Example:
•a='G'
•b="W"
1-18

Literals: Types
•NumericLiterals:Thesearetheliteralswritten
informofnumbers.Pythonsupportsthe
followingnumericalliterals:
–IntegerLiteral:Itincludesbothpositiveand
negativenumbersalongwith0.Itdoesn’tinclude
fractionalparts.Itcanalsoincludebinary,decimal,
octal,hexadecimalliteral.
–FloatLiteral:Itincludesbothpositiveandnegative
realnumbers.Italsoincludesfractionalparts.
–ComplexLiteral:Itincludesa+binumeral,herea
representstherealpartandbrepresentsthe
complexpart.
1-19

Literals: Types
•Boolean Literals: Boolean literals have only
two values in Python. These are True and
False.
•Special Literals: Python has a special literal
‘None’. It is used to denote nothing, no
values, or the absence of value.
•Example:
•var = None
•print(var)
1-20

Literals: Types
•LiteralsCollections
–List,dictionary,tuple,andsetsareexamplesofPythonliteral
collections.
–List:Itisacomma-separatedlistofcomponentsenclosedinsquare
brackets.Theseelementscanbeofanydatatypeandcanbe
changed.
–Tuple:Inroundbrackets,thisissimilartoalisthavingcomma-
separateditemsorvalues.Thevaluesarefixedandcanhaveany
Pythondatatype.
–Dictionary:Thisdatastructureisanunorderedsetofkey-value
combinations.
–Set:Itisthegroupofcomponentsenclosedincurlybraces,"{}"
• Example:
• #Alistliteralcollection
•my_list=[23,"Python",1.2,'Character']
1-21

4. Data Types
•Datatypesaretheclassificationorcategorizationofdata
items.Datatypesareusedtoidentifythetypeofdataandset
ofvalidoperationswhichcanbeperformedonit.
1-22

Data Types (cont..)
Python has five standard data types:
•Numbers
•String
•List
•Tuple
•Dictionary
1-23

Python Numbers:
•Number data types store numeric values. They are immutable
data types, which means that changing the value of a number
data type results in a newly allocated object.
•Number objects are created when you assign a value to them.
For example:
var1 = 1
var2 = 10
Python supports four different numerical types:
•int (signed integers)
•long (long integers [can also be represented in octal and
hexadecimal])
•float (floating point real values)
•complex (complex numbers)
1-24

Number Examples:
int long float complex
10 51924361L 0 3.14j
100 -0x19323L 15.2 45.j
-786 0122L -21.9 9.322e-36j
80 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j
-490 535633629843L -90 -.6545+0J
-0x260 -052318172735L -3.25E+101 3e+26J
0x69 -4721885298529L 70.2-E12 4.53e-7j
1-25

Python Strings
•StringsinPythonareidentifiedasacontiguoussetof
charactersinbetweenquotationmarks.
•Pythonallowsforeitherpairsofsingleordoublequotes.
Subsetsofstringscanbetakenusingthesliceoperator([]
and[:])withindexesstartingat0inthebeginningofthe
stringandworkingtheirwayfrom-1attheend.
•Theplus(+)signisthestringconcatenationoperator,and
theasterisk(*)istherepetitionoperator.
1-26

Example:
str = 'Hello World!'
print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to
6th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string
Output:
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
1-27

Python Lists:
•Lists are the most versatile of Python's compound data types.
A list contains items separated by commas and enclosed
within square brackets ([]).
•To some extent, lists are similar to arrays in C. One
difference between them is that all the items belonging to a
list can be of different data type.
•The values stored in a list can be accessed using the slice
operator ( [ ] and [ : ] ) with indexes starting at 0 in the
beginning of the list and working their way to end-1.
•The plus ( + ) sign is the list concatenation operator, and the
asterisk ( * ) is the repetition operator.
1-28

Python Lists (cont..)
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print list # Prints complete list
print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists
Output:
['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
1-29

Python Tuples:
•A tuple is another sequence data type that is similar to the
list. A tuple consists of a number of values separated by
commas. Unlike lists, however, tuples are enclosed within
parentheses.
•The main differences between lists and tuples are: Lists are
enclosed in brackets ( [ ] ), and their elements and size can
be changed, while tuples are enclosed in parentheses ( ( ) )
and cannot be updated. Tuples can be thought of as read-
onlylists.
1-30

Python Tuples(Cont..)
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print tuple # Prints complete list
print tuple[0] # Prints first element of the list
print tuple[1:3] # Prints elements starting from 2nd till 3rd
print tuple[2:] # Prints elements starting from 3rd element
print tinytuple * 2 # Prints list two times
print tuple + tinytuple # Prints concatenated lists
OUTPUT:
('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
1-31

Python Dictionary:
•Python 's dictionaries are hash table type. They work like
associative arrays or hashes found in Perl and consist of key-
value pairs.
•Keys can be almost any Python type, but are usually numbers
or strings. Values, on the other hand, can be any arbitrary
Python object.
•Dictionaries are enclosed by curly braces ( { } ) and values can
be assigned and accessed using square braces ( [] ).
1-32

Python Dictionary(cont..)
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two“
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one'] # Prints value for 'one' key
print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values
OUTPUT:
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
1-33

Boolean Data Type
•Datatypewithoneofthetwobuilt-invalues,True
orFalse.
•BooleanobjectsthatareequaltoTruearetruthy
(true),andthoseequaltoFalsearefalsy(false).
•Howevernon-Booleanobjectscanbeevaluatedina
Booleancontextaswellanddeterminedtobetrue
orfalse.Itisdenotedbytheclassbool.
•Note–TrueandFalsewithcapital‘T’and‘F’are
validbooleansotherwisepythonwillthrowanerror.
1-34

Set Data Type
•InPython,aSetisanunorderedcollectionofdatatypesthatis
iterable,mutable,andhasnoduplicateelements.
•Theorderofelementsinasetisundefinedthoughitmayconsistof
variouselements.
•Setscanbecreatedbyusingthebuilt-inset()functionwithan
iterableobjectorasequencebyplacingthesequenceinsidecurly
braces,separatedbya‘comma’.T
•hetypeofelementsinasetneednotbethesame,variousmixed-
updatatypevaluescanalsobepassedtotheset.
•Setitemscannotbeaccessedbyreferringtoanindex,sincesetsare
unorderedtheitemshavenoindex.
•Butwecanloopthroughthesetitemsusingaforloop,oraskifa
specifiedvalueispresentinaset,byusingtheinthekeyword.
1-35

5. NUMBERS AND MATH FUNCTIONS
•Pythonhasasetofbuilt-inmathfunctions,including
anextensivemathmodule.Itallowstoperform
mathematicaltasksonnumbers.
1-36

Python -Numbers
•Numberdatatypesstorenumericvalues.Theyareimmutable
datatypes,whichmeansthatchangingthevalueofanumber
datatyperesultsinanewlyallocatedobject.
•Numberobjectsarecreatedwhenyouassignavaluetothem.
Forexample:
var1=1
var2=10
•Youcanalsodeletethereferencetoanumberobjectby
usingthedelstatement.Thesyntaxofthedelstatementis:
delvar1[,var2[,var3[....,varN]]]]
Youcandeleteasingleobjectormultipleobjectsbyusing
thedelstatement.Forexample:
delvardelvar_a,var_b

Python -Numbers
Pythonsupportsfourdifferentnumericaltypes:
•int(signedintegers):oftencalledjustintegersorints,arepositive
ornegativewholenumberswithnodecimalpoint.
•long(longintegers):orlongs,areintegersofunlimitedsize,
writtenlikeintegersandfollowedbyanuppercaseorlowercaseL.
•float(floatingpointrealvalues):orfloats,representrealnumbers
andarewrittenwithadecimalpointdividingtheintegerand
fractionalparts.Floatsmayalsobeinscientificnotation,withEore
indicatingthepowerof10(2.5e2=2.5x10
2
=250).
•complex(complexnumbers):areoftheforma+bJ,whereaandb
arefloatsandJ(orj)representsthesquarerootof-1(whichisan
imaginarynumber).aistherealpartofthenumber,andbisthe
imaginarypart.ComplexnumbersarenotusedmuchinPython
programming.

Mathematical Functions(Math functions
Function Returns ( description )
abs(x) The absolute value of x: the (positive) distance between x and zero.
ceil(x) The ceiling of x: the smallest integer not less than x
cmp(x, y) -1 if x < y, 0 if x == y, or 1 if x > y
exp(x) The exponential of x: e
x
fabs(x) The absolute value of x.
floor(x) The floor of x: the largest integer not greater than x
log(x) The natural logarithm of x, for x> 0
log10(x) The base-10 logarithm of x for x> 0 .
max(x1, x2,...) The largest of its arguments: the value closest to positive infinity
min(x1, x2,...) The smallest of its arguments: the value closest to negative infinity
modf(x) The fractional and integer parts of x in a two-item tuple. Both parts
have the same sign as x. The integer part is returned as a float.
pow(x, y) The value of x**y.
round(x [,n]) xrounded to n digits from the decimal point. Python rounds away from
zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.
sqrt(x) The square root of x for x > 0

Random Number Functions:
Function Returns ( description )
choice(seq) A random item from a list, tuple, or string.
randrange ([start,]
stop [,step])
A randomly selected element from range(start, stop,
step)
random() A random float r, such that 0 is less than or equal to
r and r is less than 1
seed([x]) Sets the integer starting value used in generating
random numbers. Call this function before calling
any other random module function. Returns None.
shuffle(lst) Randomizes the items of a list in place. Returns
None.
uniform(x, y) A random float r, such that x is less than or equal to
r and r is less than y

Trigonometric Functions:
Function Description
acos(x) Return the arc cosine of x, in radians.
asin(x) Return the arc sine of x, in radians.
atan(x) Return the arc tangent of x, in radians.
atan2(y, x)Return atan(y / x), in radians.
cos(x) Return the cosine of x radians.
hypot(x, y)Return the Euclidean norm, sqrt(x*x + y*y).
sin(x) Return the sine of x radians.
tan(x) Return the tangent of x radians.
degrees(x)Converts angle x from radians to degrees.
radians(x)Converts angle x from degrees to radians.

6. INPUT AND OUTPUT OPERATIONS
•InPython,programoutputisdisplayedusing
theprint()function,whileuserinputisobtained
withtheinput()function.Pythontreatsallinput
asstringsbydefault,requiringexplicit
conversionforotherdatatypes.
1-42

Python Input
•Sometimes,usersordeveloperswanttoruntheprogramswiththeir
owndatainthevariablesfortheirownease.Toexecutethis,wewill
learntotakeinputfromtheusers,inwhichtheusersthemselveswill
definethevaluesofthevariables.Theinput()statementallowsustodo
suchthingsinPython.
•Thesyntaxforthisfunctionisasfollows:
•input('prompt')
•Here,promptisthestringwewanttodisplaywhiletakinginputfrom
theuser.Thisisoptional.
•Pythongetuserinputwithamessage
• #Takinginputfromtheuser
• name=input("Enteryourname:")

•#Output
•print("Hello,"+name)
•print(type(name))
1-43

Python Output
•Pythonprovidestheprint()functiontodisplayoutputtothe
standardoutputdevices.
•Syntax:
–print(value(s),sep=‘‘,end=‘\n’,file=file,flush=flush)
•Parameters:
–value(s):Anyvalue,andasmanyas.Willbeconvertedtostring
beforeprinted
–sep=’separator’(Optional):Specifyhowtoseparatetheobjects,if
thereismorethanone.Default:’‘
–end=’end’(Optional):Specifywhattoprintattheend.Default:‘\n’
–file(Optional):Anobjectwithawritemethod.Default:sys.stdout
–flush(Optional):ABoolean,specifyingiftheoutputisflushed
(True)orbuffered(False).Default:False
–Returns:Itreturnsoutputtothescreen.
1-44

7. Comments
•Commentsarenonexecutablestatementsina
program.
–Singlelinecommentalwaysstartswith#
–Multilinecommentwillbeintriplequotes.For
example“’writeaprogramtofindthesimple
interest“’.
–Note:Tripleapostropheiscalleddocstrings.
1-45

Single-line comments
•A single-line comment starts and ends in the same line. We use the # symbol to
write a single-line comment.
•Example:
•# create a variable
•name = 'Eric Cartman'

•# print the value
•print(name)
•Output
•Eric Cartman
•Here, we have created two single-line comments:
•# create a variable
•# print the value
•We can also use the single-line comment along with the code.
•name = 'Eric Cartman' # name is a string
•Here, code before # are executed and code after # are ignored by the interpreter.
1-46

Multi-line comments
•Pythondoesn'tofferaseparatewaytowritemultilinecomments.
However,thereisotherwaystogetaroundthisissue.
•Wecanuse#atthebeginningofeachlineofcommentonmultiple
lines.
•Forexample,
•#Thisisalongcomment
•#anditextends
•#tomultiplelines
•Here,eachlineistreatedasasinglecomment,andallofthemare
ignored.
•Anotherwayofdoingthisistousetriplequotes,either'''or""".
•Thesetriplequotesaregenerallyusedformulti-linestrings.Butif
wedonotassignittoanyvariableorfunction,wecanuseitasa
comment.Theinterpreterignoresthestringthatisnotassignedto
anyvariableorfunction.
1-47

8. RESERVED WORDS
Keyword Description
and A logical operator
as To create an alias
assert For debugging
break To break out of a loop
class To define a class
continue To continue to the next iteration of a loop
def To define a function
del To delete an object
elif Used in conditional statements, same as else if
else Used in conditional statements
except Used with exceptions, what to do when an exception occurs
False Boolean value, result of comparison operations
finally Used with exceptions, a block of code that will be executed no
matter if there is an exception or not
for To create a for loop
from To import specific parts of a module
global To declare a global variable
if To make a conditional statement
1-48

RESERVED WORDS(Cont..)
1-49
Keyword Description
import To import a module
in To check if a value is present in a list, tuple, etc.
is To test if two variables are equal
lambda To create an anonymous function
None Represents a null value
nonlocal To declare a non-local variable
not A logical operator
or A logical operator
pass A null statement, a statement that will do nothing
raise To raise an exception
return To exit a function and return a value
True Boolean value, result of comparison operations
try To make a try...except statement
while To create a while loop
with Used to simplify exception handling
yield To end a function, returns a generator

9. Indentation
•IndentationinPythonreferstothewhitespaces
atthestartofthelinetoindicateablockof
code.
•Wecancreateanindentationusingspaceor
tabs.
•WhenwritingPythoncode,wehavetodefinea
groupofstatementsforfunctionsandloops.
•Thisisdonebyproperlyindentingthe
statementsforthatblock.
1-50

Indentation(Cont..)
•Theleadingwhitespaces(spaceandtabs)at
thestartofalineareusedtodeterminethe
indentationleveloftheline.
•Wehavetoincreasetheindentleveltogroup
thestatementsforthatcodeblock.
•Similarly,reducetheindentationtoclosethe
grouping.
•Thefourwhitespacesorasingletabcharacter
atthebeginningofacodelineareusedto
createorincreasetheindentationlevel.
1-51

Indentation(Cont..)
1-52

Indentation(Cont..)
1-53
•PythonIndentationRules
•Belowaretherulesthatoneshouldfollow
whileusingindentation:
–ThefirstlineofPythoncodecan’thaveanindentation,itwill
throwIndentationError.
–Weshouldavoidmixingtabsandwhitespacestocreatean
indentation.It’sbecausetexteditorsinNon-Unixsystems
behavedifferentlyandmixingthemcancausethewrong
indentation.
–Itispreferredtousewhitespacethanthetabcharacter.
–Thebestpracticeistouse4whitespacesforthefirst
indentationandthenkeepaddingadditional4whitespacesto
increasetheindentation.

10. OPERATORS AND EXPRESSIONS
Python language supports following type of operators.
•Arithmetic Operators
•Comparison Operators
•Assignment Operators
•Unary Operators
•Logical Operators
•Bitwise Operators
•Membership Operators
•Identity Operators

Python Arithmetic Operators:
Operator Description Example
+ Addition -Adds values on either side of the
operator
a + b will give 30
- Subtraction -Subtracts right hand operand
from left hand operand
a -b will give -10
* Multiplication -Multiplies values on either
side of the operator
a * b will give 200
/ Division -Divides left hand operand by
right hand operand
b / a will give 2
% Modulus -Divides left hand operand by
right hand operand and returns remainder
b % a will give 0
** Exponent -Performs exponential (power)
calculation on operators
a**b will give 10 to
the power 20
// Floor Division -The division of operands
where the result is the quotient in which
the digits after the decimal point are
removed.
9//2 is equal to 4 and
9.0//2.0 is equal to 4.0

Python Comparison Operators:
Operato
r
Description Example
== Checks if the value of two operands are equal or not, if
yes then condition becomes true.
(a == b) is not true.
!= Checks if the value of two operands are equal or not, if
values are not equal then condition becomes true.
(a != b) is true.
<> Checks if the value of two operands are equal or not, if
values are not equal then condition becomes true.
(a <> b) is true. This is
similar to != operator.
> Checks if the value of left operand is greater than the
value of right operand, if yes then condition becomes
true.
(a > b) is not true.
< Checks if the value of left operand is less than the
value of right operand, if yes then condition becomes
true.
(a < b) is true.
>= Checks if the value of left operand is greater than or
equal to the value of right operand, if yes then
condition becomes true.
(a >= b) is not true.
<= Checks if the value of left operand is less than or equal
to the value of right operand, if yes then condition
becomes true.
(a <= b) is true.

Python Assignment Operators:
Operator Description Example
= Simple assignment operator, Assigns values from right
side operands to left side operand
c = a + b will
assigne value of a +
b into c
+= Add AND assignment operator, It adds right operand to
the left operand and assign the result to left operand
c += a is equivalent
to c = c + a
-= Subtract AND assignment operator, It subtracts right
operand from the left operand and assign the result to left
operand
c -= a is equivalent
to c = c -a
*= Multiply AND assignment operator, It multiplies right
operand with the left operand and assign the result to left
operand
c *= a is equivalent
to c = c * a
/= Divide AND assignment operator, It divides left operand
with the right operand and assign the result to left
operand
c /= a is equivalent
to c = c / a
%= Modulus AND assignment operator, It takes modulus
using two operands and assign the result to left operand
c %= a is equivalent
to c = c % a
**= Exponent AND assignment operator, Performs exponential
(power) calculation on operators and assign value to the
left operand
c **= a is
equivalent to c = c
** a
//= Floor Division and assigns a value, Performs floor division
on operators and assign value to the left operand
c //= a is equivalent
to c = c // a

Python Bitwise Operators:
Operat
or
Description Example
& Binary AND Operator copies a bit to the
result if it exists in both operands.
(a & b) will give 12
which is 0000 1100
| Binary OR Operator copies a bit if it exists
in either operand.
(a | b) will give 61
which is 0011 1101
^ Binary XOR Operator copies the bit if it is
set in one operand but not both.
(a ^ b) will give 49
which is 0011 0001
~ Binary Ones Complement Operator is unary
and has the effect of 'flipping' bits.
(~a ) will give -60
which is 1100 0011
<< Binary Left Shift Operator. The left
operands value is moved left by the
number of bits specified by the right
operand.
a << 2 will give 240
which is 1111 0000
>> Binary Right Shift Operator. The left
operands value is moved right by the
number of bits specified by the right
operand.
a >> 2 will give 15
which is 0000 1111

Python Logical Operators:
Operat
or
Description Example
and Called Logical AND operator. If both the
operands are true then then condition
becomes true.
(a and b) is true.
or Called Logical OR Operator. If any of the two
operands are non zero then then condition
becomes true.
(a or b) is true.
not Called Logical NOT Operator. Use to
reverses the logical state of its operand. If a
condition is true then Logical NOT operator
will make false.
not(a and b) is false.

Python Membership Operators:
In addition to the operators discussed previously, Python has
membership operators, which test for membership in a
sequence, such as strings, lists, or tuples.
Operator Description Example
in Evaluates to true if it finds a variable in the
specified sequence and false otherwise.
x in y, here inresults in a 1
if x is a member of
sequence y.
not in Evaluates to true if it does not finds a variable
in the specified sequence and false otherwise.
x not in y, here not in
results in a 1 if x is a
member of sequence y.

Python Identity Operators:
Operator Sample
Expression
Result
is xisy Trueifxandyholda
referencetothesamein-
memoryobject
Falseotherwise
isnot xisnoty Trueifxpointstoanobject
differentfromtheobject
thatypointsto
Falseotherwise
1-61

Unary operator
•Unaryoperatorsarethoseoperatorsthatrequirea
singleoperandforcomputations.Pythonsupports
unaryminusoperator.Theoperator‘-’iscalledthe
Unaryminusoperator.Itisusedtonegatethenumber.
Theminusoperatorisusedtorepresentanegative
value.
•Example:
•b=10
•a=-(b)
•Theresultofthisexpressionisa=-10,because
variablebhasapositivevalue.Afterapplyingunary
minusoperator(-)ontheoperandb,thevalue
becomes-10,whichindicatesitasanegativevalue
1-62

11. Python Operators Precedence
Operator Description
** Exponentiation (raise to the power)
~ + - Ccomplement, unary plus and minus (method names for
the last two are +@ and -@)
* / % // Multiply, divide, modulo and floor division
+ - Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^ | Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= +=
*= **=
Assignment operators
is is not Identity operators
in not in Membership operators
not or and Logical operators

12. TYPE CONVERSION
•Typeconversionistheprocessofconverting
dataofonetypetoanother.Therearemainly
twotypesoftypeconversionmethodsin
Python:
–Implicittypeconversion-Doneautomaticallyby
thePythoninterpreter
–Explicittypeconversion-Needstobedone
manuallybytheprogrammer.
1-64

Implicit type conversion
•Incertainsituations,Pythonautomaticallyconverts
onedatatypetoanother.Thisisknownasimplicit
typeconversion.Thistypeofdatatypeconversion
takesplaceduringcompilationorduringtheruntime.
•Example:
–a=5
–b=5.5
–sum=a+b
–print(sum)
–print(type(sum))#type()isusedtodisplaythedatatypeofavariable
•Output:
–10.5
–<class‘float’>
1-65

Explicit type conversion
•Explicittypeconversionisalsoknownas
typecasting.
•InExplicitTypeConversion,thedatatypeis
manuallychangedbytheuseraspertheir
requirement.
•Withexplicittypeconversion,thereisariskof
datalosssinceweareforcinganexpressionto
bechangedinsomespecificdatatype
1-66

Data Type Conversion:
Function Description
int(x[,base]) Convertsxtoaninteger.basespecifiesthebaseifxisastring.
long(x[,base]) Convertsxtoalonginteger.basespecifiesthebaseifxisastring.
float(x) Convertsxtoafloating-pointnumber.
complex(real
[,imag])
Createsacomplexnumber.
str(x) Convertsobjectxtoastringrepresentation.
repr(x) Convertsobjectxtoanexpressionstring.
eval(str) Evaluatesastringandreturnsanobject.
tuple(s) Convertsstoatuple.
list(s) Convertsstoalist.
set(s) Convertsstoaset.
dict(d) Createsadictionary.dmustbeasequenceof(key,value)tuples.
frozenset(s) Convertsstoafrozenset.
chr(x) Convertsanintegertoacharacter.
unichr(x) ConvertsanintegertoaUnicodecharacter.
ord(x) Convertsasinglecharactertoitsintegervalue.
hex(x) Convertsanintegertoahexadecimalstring.
oct(x) Convertsanintegertoanoctalstring. 1-67

13. DEBUGGING
•Debuggingisamethodthatinvolvestesting
ofacodeduringitsexecutionandcode
correction.
•Duringdebugging,aprogramisexecuted
severaltimeswithdifferentinputstoensure
thatitperformsitsintendedtaskcorrectly.
•Whileotherformsoftestingaimsto
demonstratecorrectnessoftheprograms,
testingduringdebugging,ontheotherhand
isprimarilyaimedatlocatingerrors.

1-68

Preconditions for Effective debugging
•Understand the design and algorithm
•Check correctness
•Code tracing
•Peer reviews
1-69

Principles of Debugging
•Reporterrorconditionsimmediately
•Maximizeusefulinformationandeaseof
interpretation
•Minimize useless and distracting
information
•Avoidcomplexone-usetestingcode
1-70

Debugging Aids
•Assert statements
•Tracebacks
•General purpose debuggers
•Print Statements
1-71

14. COMMON ERRORS IN PYTHON
•Thereareseveraltypesoferrorsthatcan
occurinPython.
•Eachtypeindicatesadifferentkindofproblem
inthecode,andcomprehendingtheseerror
typesiscrucialincreatingeffectivePython
applications.
•Themostcommontypesoferrorsencounter
inPythonaresyntaxerrors,runtimeerrors,
logicalerrors,nameerrors,typeerrors,index
errors,andattributeerrors.
1-72

Syntax Errors
•AsyntaxerroroccursinPythonwhenthe
interpreterisunabletoparsethecodedueto
thecodeviolatingPythonlanguagerules,such
asinappropriateindentation,erroneous
keywordusage,orincorrectoperatoruse.
•Syntaxerrorsprohibitthecodefromrunning,
andtheinterpreterdisplaysanerrormessage
thatspecifiestheproblemandwhereit
occurredinthecode.
1-73

Runtime Errors
•InPython,aruntimeerroroccurswhenthe
programisexecutingandencountersan
unexpectedconditionthatpreventsitfrom
continuing.
•Runtimeerrorsarealsoknownasexceptions
andcanoccurforvariousreasonssuchas
divisionbyzero,attemptingtoaccessan
indexthatisoutofrange,orcallinga
functionthatdoesnotexist.
1-74

Logical Errors
•AlogicalerroroccursinPythonwhenthe
coderunswithoutanysyntaxorruntime
errorsbutproducesincorrectresultsdueto
flawedlogicinthecode.
•Thesetypesoferrorsareoftencausedby
incorrectassumptions, anincomplete
understandingoftheproblem,orthe
incorrectuseofalgorithmsorformulas.
•Unlikesyntaxorruntimeerrors,logicalerrors
canbechallengingtodetectandfixbecause
thecoderunswithoutproducinganyerror
messages.
1-75
Tags