Python Programming Language
Python Programming Language
Best match
0 Variablel
0 First
Command
CUD idle
Store (2)
>
3.Logical Operators
Operator Description
and (Logical AND) Both operands are true it
is True. Otherwise False.
4.Bitwise Operators
Operator Name
& Bitwise and
Bitwise or
A Bitwise exclusive or
Bitwise Complement
<< Bitwise Left-Shift
>> Bitwise Right-shift
5.Membership Operators
Operator Description
in It returns True if it
finds a variable in the
specified sequence.
Otherwise False
not in It returns True if it
does not find a variable
in the specified
sequence. Other False.
6.Identity Operators
Operator Description
is It returns True if the
two variables points to
the same memory location.
Otherwise False.
is not It returns False if the
two-variable point to the
same memory location.
Otherwise True.
7.Assignment Operators
Operator Description
= (Assignment Operator) Right side value will be
stored into left side
variable/object.
+= (Addition Assignment Adds right operand to
Operator) the left operand and
stores the result into
left operand.
-= (Subtraction Subtract right operand
Assignment Operator) to the left operand and
stores the result into
left operand.
*= (Multiplication Multiplies right operand
Assignment Operator) to the left operand and
stores the result into
left operand.
statement-1
statement-2
else:
statement-1
statement-2
Ex
1. n = input(’Is the Window is Open:’)
2.
3.if n == ’yes’:
4. print(’The Room is Cool.’)
5.
5. elif n == ’no’:
6. print(’The Room is Warm.’)
8.
7. else:
8. print(’The Romm is Cool and Warm.’)
Output:
D:\notes\Python\materi al>python Exanple.py Is
the Window is Open:no The Room is Warm.
D:\notes\Python\materi al>python Exanple.py Is
the Window is Open:yes The Room i s Cool.
D:\notes\Python\materi al>python Exanple.py Is
the Window is Open:middle The Romm is Cool and
Warm.
D:\notes\Python\materi al>
Note:
[Seise block is always optional.
[! Switch statement is not there in python.
Looping or Iterative Statement
& Loops are used to execute a group of statement for
multiple times.
& Until the condition becomes false the loop stops
and control jumps out of the loop.
While
& While loops are known as indefinite or conditional
loops.
& It iterates until certain condition is met.
& There is no guarantee that how many times the loop
will be iterates.
Syntax:
Initialization While condition:
Statement-1
Statement-2
Increment / Decrement
Note:
& Initialization and Increment / Decrement statement
are optional.
Ex:
1.i = 1
2. while i<10:
3. print(’i=’,i)
4.1 = i + 1
output:
D:\notes\Python\material>python Exanple.py i= 1 i=
2 i = 3 i = 4 i= 5 i= 6 i= 7 i = 8 i= 9
Ex
1.# Write a Python program sum of ’n’ natural
number
2. n = int(input(’Enter a number:’))
3. sum = 0
4. i = 1
5. while i<=n:
6. sum +=i
7.1 = i + 1
8.
9. print(’Sum of Natural Number is
:’,sum)
output:
D:\notes\Python\material>python Exanple.py
Enter a number:10
Sum of Natural Number is : 55
D:\notes\Python\material>python Exanple.py
Enter a number:5
Sum of Natural Number is : 15
For
Ofor loop repeats a group of statements a specified
number of times.
Syntax:
for <variable_name> in sequence: statement-1
statement-2
Note
il where sequence can be string/list/tuple .. etc.
Ex:
1. for x in "PYTHON":
2. print(x)
output:
D:\notes\Python\materi al>python Exanpl e.py P
Ex:
1.list1 = [1,2,3,4]
2. for x in list1:
3. print(x)
output:
D:\notes\Python\mate ri al>python Exanple.py 1
4
range () function
& range () function is used to generate sequence of
numbers.
& It is a built-in function available in python.
Syntax:
range (Start, Stop, Step) start:
& It represents the starting point of the list.
& It is optional argument and the default value for
this argument is 0.
Stop:
& It is the end point of the sequence generated.
& It is the only required argument in the function.
& It does not have any default value.
Step:
& This is the 3rd and the last argument in the
function.
& Just like start it is also the optional argument
and its default value is 1.
& Though the user can change this value according to
its requirements.
Note:
IS Since python is 0 indexed.
[I So, by default every list generated by range
function will start from 0 and will end at stop-
1. i.e. 1 less than the value for stop argument.
Hi Though it will include the starting point in the
list.
Ex
1. for x in range(10):
2. print(x)
output:
D:\notes\Python\materi al>python Exanple.py 0
9 Ex
1. # Write a Python Program to print 20 even
2. numbers using range() function
3.
3. for x in range(2,22,2):
4. print(x)
output:
C:\Users\vasu\Desktop>python Demo.py 2
10 12 14 16 18 20
Note:
Hi The 3rd argument (step argument) in range()
function can never be 0.
Hi If it is 0, then it will raise a ValueError
exception.
Nested Loops
for <variable> in <range>: #outer loop [do something]
# Optional for <variable> in <range>:# Nested loop
[do something]
Ex
1. for x in range(1,3):
2. for y in range(1,3):
i. print('x:',x,,and y:’,y)
3. print( ----- ’ ’)
output:
C:\Users\vasu\Desktop>python Demo.py x: 1
and y: 1 x: 1 and y: 2
x: 2 and y: 1 x: 2 and y: 2
Ex:
1. for x in range(1,4):
2. for y in range(1,4):
i. print(’ * ’,end=’’)
3. print()
output:
C:\Users\vasu\Desktop>python Demo.py
A A A
output:
NameError: name 'a' is no defined.
Keybordlnterrupt
& Raised when the user hits the interrupt key
(normally Control-C or Delete).
& During execution, a check for interrupts is made
regularly.
SyntaxError:
& Raised when the parser encounters a syntax
error.
Exception hierarchy
BaseException
+-- SystemExit +-- Keyboardlnterrupt +-- GeneratorExit
+-- Exception
+-- Stoplteration +-- ArithmeticError | +--
FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError +-- AttributeError +-- BufferError
+-- EOFError
+-- ImportError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- MemoryError
+-- NameError
| +-- UnboundLocalError
+-- OSError
| +-- BlockinglOError
| +-- ChildProcessError
| +-- ConnectionError
| | +-- BrokenPipeError
| | +-- ConnectionAbortedError
| | +-- ConnectionRefusedError
| | +-- ConnectionResetError
| +-- FileExistsError
| +-- FileNotFoundError
| +-- InterruptedError
| +-- IsADirectoryError
| +-- NotADirectoryError
| +-- PermissionError
| +-- ProcessLookupError
| +-- TimeoutError
68 | P a g e SS TECHNOLOGIES Pvt Ltd
Software Training & Development. www.sstechnologis.com
+-- ReferenceError
+-- RuntimeError
| +-- NotImplementedError
+-- SyntaxError
| +-- IndentationError
| +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
+-- ResourceWarning
69 | P a g e SS TECHNOLOGIES Pvt Ltd
Software Training & Development. www.sstechnologis.com
Object Oriented Programming
& Python is an Object-Oriented programming language.
& Python doesn't force to use the object-oriented
paradigm exclusively.
& Python also supports procedural programming with
modules and functions, so you can select the most
suitable programming paradigm for each part of your
program.
Note:
H Generally, the object-oriented paradigm is
suitable when you want to group state (data) and
behaviour (code) together in handy packets of
functionality.
Class
& Binds the member variables and into a single unit.
OR
Class is a Blue Print or Template for an object.
Syntax:
class <name>([<name>, <name>, . . .]):
& Statement's
Where,
class is a keyword. name is an identifier.
[] optional
Ex:
1. # Creating a Class
2. class Vasu():
3. print(’Hello’)
Object:
& Object is an instance of a class.
OObject has state and behaviour.
Syntax:
<referenc_name> = <class_name>([parameter list])
Ex:
1. # Creating a Class
2. class Vasu():
3. print(’Hello’)
4.
4. # Creating an object 6.obj1 = Vasu()
Note:
0 For one class you can createone or more object,
il For every object PVMmaintainsdifferent
address.
Method
& A method is a function defined in class.
Types of method
instance method Class method Ecstatic method
Instance method
& Method define inside a class and has a keyword
fselfJ parameter.
class A:
def m1(self):
print(’m1() in A.’)
class B:
def m1(self):
print(’m1() in B.’)
9.
10.
class C(A,B): pass
11.
10. obj1 = C()
11. obj1.m1()
output
ml() in A.
& In above program both parent classes having same
method name.
& In this case python uses Method Resolution Order.
Method Resolution Order in Python
T Every class in Python is derived from the class
object.
T In the multiple inheritance scenario, any
specified attribute or method is searched first in
the current class. If not found, the search continues
into parent classes in depth-first, left-right
fashion without searching same class twice.
Hybrid Inheritance
1. class A:
2. def m1(self):
4.
5.
4. 7.
3. print(’m1() in A.’)
class B:
def m1(self):
print(’m1() in B.’) class C(A,B): def m1(self):
8.
9.
9. 11. 12.
13.
14.
print(’m1() in C.’)
class D(C): pass
15.
15. obj1 = D()
16. obj1.m1()
Polymorphism
T Polymorphism is a Latin word which made up of
‘‘poly’ means many and ‘‘morphs-’ means forms. From
the Greek, Polymorphism means many(poly)
shapes(morph).
T This is something similar to a word having several
different meanings depending on the context.
T Generally speaking, polymorphism means that a
method or function is able to cope with different
types of input.
Method Overloading
T There is NO direct support for method overloading
in Python.
T Can be emulated (spoofed) by using default
parameters.
Ex:
1.
2.
3.
class A:
def m1(self):
print(’m1() in A.’)
def m1(self,a):
4.
5.
4. 7.
print(’m1(a) in A.’)
7. a = A()
8. #a.m1() # TypeError: m1() missing 1 require
9. #positional argument: ’a’
11.
10. a.m1(10)
Note:
Hi In above program when you are calling m1() method
it occurs an TypeError.
(S When you are calling ml(a) but no error.
il In python latest method will be call.
Method Overloading using Default Parameter
T A default parameter to a function is where a
default value is specified in the function
definition, when the function is called without the
parameter.
Ex:
1.
2.
3.
class A:
def m1(self,a=None,b=None,c=None):
if a != None and b != None and c !=
None:
4.
print(’Three Argument are
passed.’)
5.
6.
else:
print(’Zero Arrgument are
passed.’)
7.
8. a = A()
9. a.m1()
10. a.m1(10,20,30)
Operator Overloading Ex
1. class Example:
2. def init (self,a,b):
3. self.a= a
4. self.b= b
5.
5. def add
(self,other):
6. returnself.a+ other.a, self.b +
other.b
8.
7. obj1 = Example(1,2)
8. obj2 = Example(3,4)
9. obj3 = Example(1.2,2.2)
10. print(obj1 + obj2)
11. print(obj1 + obj3)
Python Magic Methods OR Special Functions
List of Assignment operators and associated magic
methods.
Assignment Magic Method or Special
Operators Function
- = object. _ isub _ (self, other)
+= object. _ iadd _ (self, other)
*= object. _ imul _ (self, other)
/= object. _ idiv _ (self, other)
Function
< object. _ lt _ (self, other)
a| b (ne)
(?imx)
(?-imx)
(?: re)
\D Matches nondigits.
Repetition Cases
Example Description
Nongreedv repetition
Example Description
Example Description
\D\d+ No group: + repeats \d
(\D\d)+ Grouped: + repeats \D\d
pair
([Pp]ython(, )?)+ Match "Python", "Python,
python, python", etc.
Backreferences
Example Description
Alternatives
Example Description
python|perl Match "python" or "perl"
Example Description
APython Match "Python" at the start of a string
or internal line
Python$ Match "Python" at the end of a string or
line
Example Description