000 - Python Document
000 - Python Document
INTRODUCTION
Software :-
Types Of Software :-
Examples
Microsoft Word
Microsoft Excel
Custom software :-
Packaged Software :-
System Software :-
Examples
Operating Systems
Utility Programs
Device Drivers
Operating System (OS) :-
Utility program :-
Device Driver :-
Like printers
What is a language?
There are basically three types of computer programming languages, they are
The programming languages that have features of low level and high
level programming languages
C programming languages is the best example of Low Level
Programming languages as it has features of low level and high level
programming languages both.
Why Python ?
They are used to define the syntax and structure of the Python language.
There are 33 keywords in Python 3.3. This number can vary slightly in
course of time.
as elif If or yield
asser
else Import pass
t
Python Identifiers
Identifier is the name given to entities like class, functions, variables etc. in
Python.
>>>global = 1
File"<interactive input>", line 1
global = 1
^
SyntaxError: invalid syntax
>>>a@ = 0
File"<interactive input>", line 1
a@ = 0
^
SyntaxError: invalid syntax
Python Statement
Instructions that a Python interpreter can execute are called statements.
Multi-line statement
But we can make a statement extend over multiple lines with the line
continuation character (\).This is explicit line continuation.
a =1+2+3+ \
4+5+6+ \
7+8+9
a =(1+2+3+
4+5+6+
7+8+9)
a =1; b =2; c =3
Python Indentation
Most of the programming languages like C, C++, Java use braces { } to
define a block of code. Python uses indentation.
for i in range(1,11):
print(i)
if i == 5:
break
Python Comments
#This is a comment
#print out Hello
Multi-line comments
If we have comments that extend multiple lines, one way of doing it is to use
hash (#) in the beginning of each line. For example:
These triple quotes are generally used for multi-line strings. But they can be
used as multi-line comment as well.
"""This is also a
perfect example of
multi-line comments"""
Example:
def double(num):
Built-in Functions
Python Output
a=5
Python Input
input([prompt])
Python Variables
The rules for writing a variable name is same as the rules for writing
identifiers in Python.
Variable assignment
a =5
Multiple assignments
a, b, c =5,3.2,"Hello"
Python Numbers
Integers
Example :
a=5
a = 2.0
a = 1+2j
print(a,"iscomplexnumber?",isinstance(1+2j,complex))
>>> a = 1234567890123456789
>>>a
1234567890123456789
>>> b = 0.1234567890123456789
>>>b
0.12345678901234568
>>> c = 1+2j
>>>c
(1+2j)
Python List
List is an ordered sequence of items. All the items in a list do not need to
be of the same type.
>>> a =[1,2.2,'python']
We can use the slicing operator [ ] to extract an item or a range of items
from a list. Index starts form 0 in Python.
a = [5,10,15,20,25,30,35,40]
# a[2] = 15
>>> a =[1,2,3]
>>>a[2]=4
>>>a
[1, 2 , 3 ]
Python Tuple
Tuples are used to write-protect data and are usually faster than list as it
cannot change dynamically.
We can use the slicing operator [] to extract items but we cannot change
its value.
t = (5,'program', 1+3j)
# t[1] = 'program'
# Generates error
Python Strings
s = 'Hello world!'
# s[4] = 'o'
# s[6:11] = 'world'
# Generates error
Python Set
a = {5,2,3,1,4}
print("a = ", a)
# data type of variable a
print(type(a))
>>> a ={1,2,2,3,3,3}
>>>a
{1,2,3}
Set are unordered collection, indexing has no meaning. Hence the slicing
operator [] does not work.
>>> a ={1,2,3}
>>>a[1]
Traceback(most recent call last):
TypeError:'set'object does not support indexing
Python Dictionary
Dictionaries are defined within braces {} with each item being a pair in
the form key:value. Key and value can be of any type.
>>> d ={1:'value','key':2}
>>>type(d)
<class'dict'>
int()
float()
str()
list()
tuple()
dict()
set()
Examples : -
>>>float(5)
5.0
>>>int(10.6)
10
>>>int(-10.6)
-10
>>>float('2.5')
2.5
>>>str(25)
'25'
>>>int('1p')
>>>set([1,2,3])
{1,2, 3}
>>>tuple({5,6,7})
(5,6,7)
>>>list('hello')
['h','e','l','l','o']
>>>dict([[1,2],[3,4]])
{1:2,3:4}
>>>dict([(3,26),(4,44)])
3. Python Operators
Operators are special symbols in Python that carry out arithmetic or logical
computation.
The value that the operator operates on is called the operand.
Arithmetic operators
Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication etc.
X + y
+ Add two operands or unary plus
+2
Example:
x = 15
y=4
print('x + y =',x+y)
print('x - y =',x-y)
print('x * y =',x*y)
print('x / y =',x/y)
print('x // y =',x//y)
print('x ** y =',x**y)
Comparison operators
> Greater that - True if left operand is greater than the right x>y
< Less that - True if left operand is less than the right x<y
Example :
x = 10
y = 12
print('x == y is',x==y)
print('x != y is',x!=y)
print('x >= y is',x>=y)
Logical operators
x = True
y = False
print('x or y is',x or y)
print('not x is',not x)
Bitwise operators
Assignment operators
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
Special operators
Python language offers some special type of operators like the identity
operator or the membership operator.
Identity operators
True if the operands are not identical (do not refer to the x is not
is not
same object) True
Example :
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]
print(x2 is y2)
print(x3 is y3)
Membership operators
In a dictionary we can only test for presence of key, not the value.
Example :
x = 'Hello world'
y = {1:'a',2:'b'}
print('H' in x)
print('hello' not in x)
print(1 in y)
print('a' in y)
If BOOLEAN EXPRESSION:
STATEMENTS
Flow chart:
Example:
food = 'spam'
if food == 'spam':
print('Ummmm, my favorite!')
print('I feel like saying it 100 times...')
print(100 * (food + '! '))t
if else statement
It is frequently the case that you want one thing to happen when a condition it
true, and something else to happen when it is false.
Flow chart:
The syntax :
if BOOLEAN EXPRESSION:
STATEMENTS_1 # executed if condition evaluates to True
else:
STATEMENTS_2 # executed if condition evaluates to False
Example:
else if ladder:
Sometimes there are more than two possibilities and we need more than two
branches.
Syntax:
if x < y:
STATEMENTS_A
elif x > y:
STATEMENTS_B
else:
STATEMENTS_C
Flowchart :
Example:
if choice == 'a':
print("You chose 'a'.")
elif choice == 'b':
print("You chose 'b'.")
elif choice == 'c':
print("You chose 'c'.")
else:
print("Invalid choice.")
Nested conditionals
One conditional can also be nested within another. (It is the same theme of
composibility, again!)
Syntax:
if x < y:
STATEMENTS_A
else:
if x > y:
STATEMENTS_B
else:
STATEMENTS_C
Example
Syntax
Body of for
Flowchart
sum = sum+val
range() function
print(range(10))
# Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(range(2, 8)))
# Output: [2, 3, 4, 5, 6, 7]
We can use the range() function in for loops to iterate through a sequence of
numbers.
It can be combined with the len() function to iterate though a sequence
using indexing. Here is an example.
Example:
Example
digits = [0, 1, 5]
for i in digits:
print(i)
else:
The while loop in Python is used to iterate over a block of code as long as
the test expression (condition) is true.
Syntax
while test_expression:
Body of while
Flowchart
Example :
n = 10
i=1
while i <= n:
sum = sum + i
The while loop can be terminated with a break statement.In such case,
the else part is ignored..
counter = 0
print("Inside loop")
counter = counter + 1
else:
print("Inside else")
Syntax
break
Flowchart
if val == "i":
break
print(val)
print("The end")
Syntax
continue
Flowchart
Syntax
pass
def function(args):
pass
class example:
pass
7. Python Functions
What is a function ?
Functions help break our program into smaller and modular chunks.
As our program grows larger and larger, functions make it more organized
and manageable.
Types of Functions
Syntax:
deffunction_name(parameters):
"""docstring"""
statement(s)
Example:
def greet(name):
parameter"""
>>>greet('Paul')
Docstring
The first string after the function header is called the docstring and is short
for documentation string.
It is used to explain in brief, what a function does.
This string is available to us as __doc__ attribute of the function.
>>>print(greet.__doc__)
Thisfunction greets to
the person passed into the
name parameter
Syntax
return [expression_list]
This statement can contain expression which gets evaluated and the value is
returned.
If there is no expression in the statement or the return statement itself is not
present inside a function, then the function will return the Noneobject.
For example:
>>>print(greet("May"))
Hello, May. Good morning!
None
Example :
defabsolute_value(num):
if num >= 0:
return num
else:
return -num
# Output: 2
print(absolute_value(2))
# Output: 4
print(absolute_value(-4))
Example
defmy_func():
x = 10
x = 20
my_func()
Example.
"""
"""
greet("Kate")
Example:
defcalc_factorial(x):
if x == 1:
return 1
else:
return (x * calc_factorial(x-1))
num = 4
steps :
Advantages of Recursion
1. Recursive functions make the code look clean and elegant.
2. A complex task can be broken down into simpler sub-problems using
recursion.
3. Sequence generation is easier with recursion than using some nested
iteration.
Disadvantages of Recursion
type() function
isinstance() function
a=5
print(type(a))
print(type(5.0))
# Output: (8+3j)
c = 5 + 3j
print(c + 3)
# Output: True
print(isinstance(c, complex))
Number system
In Python, we can represent these numbers by appropriately placing a
prefix before that number. Following table lists these prefix.
Example :
# Output: 107
print(0b1101011)
print(0xFB + 0b10)
# Output: 13
print(0o15)
Type Conversion
We can convert one type of number into another. This is also known as
type conversion .
>>>1+2.0
3.0
built-in functions
We can also use built-in functions like int(), float() and complex() to convert
between types explicitly.
>>>int(2.3)
2
>>>int(-2.8)
-2
>>>float(5)
5.0
>>>complex('3+5j')
(3+5j)
Python Mathematics
Example
import math
# Output: 3.141592653589793
print(math.pi)
# Output: -1.0
print(math.cos(math.pi))
# Output: 22026.465794806718
print(math.exp(10))
# Output: 3.0
print(math.log10(1000))
# Output: 1.1752011936438014
print(math.sinh(1))
# Output: 720
print(math.factorial(6))
import random
print(random.randrange(10,20))
print(random.choice(x))
# Shuffle x
random.shuffle(x)
print(x)
# Print random element
print(random.random())
List datatype
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
# list with mixed datatypes
my_list = [1, "Hello", 3.4]
Also, a list can even have another list as an item. This is called nested
list.
# nested list
my_list = ['p','r','o','b','e']
# Output: p
print(my_list[0])
# Output: o
print(my_list[2])
# Output: e
print(my_list[4])
# my_list[4.0]
# Nested List
# Nested indexing
# Output: a
print(n_list[0][1])
# Output: 5
print(n_list[1][3])
Negative indexing
Example :
my_list = ['p','r','o','b','e']
# Output: e
print(my_list[-1])
# Output: p
print(my_list[-5])
Example :
my_list = ['p','r','o','g','r','a','m','i','z']
print(my_list[2:5])
print(my_list[:-5])
# elements 6th to end
print(my_list[5:])
print(my_list[:])
# mistake values
odd = [2, 4, 6, 8]
odd[0] = 1
# Output: [1, 4, 6, 8]
print(odd)
odd[1:4] = [3, 5, 7]
# Output: [1, 3, 5, 7]
print(odd)
We can add one item to a list using append() method or add several items
using extend() method.
odd=[1,3,5]
odd.append(7)
print(odd)
odd.extend([9,11,13])
print(odd)
We can also use + operator to combine two lists. This is also called
concatenation.
odd=[1,3,5]
# Output: [1, 3, 5, 9, 7, 5]
print(odd +[9,7,5])
#Output: ["re", "re", "re"]
print(["re"]*3)
odd = [1, 9]
odd.insert(1,3)
# Output: [1, 3, 9]
print(odd)
odd[2:2] = [5, 7]
# Output: [1, 3, 5, 7, 9]
print(odd)
We can delete one or more items from a list using the keyword del.
It can even delete the list entirely.
Example :
my_list = ['p','r','o','b','l','e','m']
delmy_list[2]
print(my_list)
delmy_list[1:5]
print(my_list)
delmy_list
The pop() method removes and returns the last item if index is not provided.
This helps us implement lists as stacks (first in, last out data structure).
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
print(my_list)
# Output: 'o'
print(my_list.pop(1))
print(my_list)
# Output: 'm'
print(my_list.pop())
print(my_list)
my_list.clear()
# Output: []
print(my_list)
List Comprehension:
List comprehension is an elegant and concise way to create new list from an
existing list in Python.
print(pow2)
pow2 =[]
for x in range(10):
pow2.append(2** x)
An optional if statement can filter out items for the new list. Here are some
examples.
all() Return True if all elements of the list are true (or if the list is empty).
Return True if any element of the list is true. If the list is empty,
any()
return False.
enumerate( Return an enumerate object. It contains the index and value of all the
) items of list as a tuple.
sorted() Return a new sorted list (does not sort the list itself).
Tuple Datatype:
What is tuple?
The difference between the two is that we cannot change the elements of
a tuple once it is assigned whereas in a list, elements can be changed.
Advantages of Tuple over List
Since tuple are immutable, iterating through tuple is faster than with list. So
there is a slight performance boost.
Tuples that contain immutable elements can be used as key for a dictionary.
With list, this is not possible.
If you have data that doesn't change, implementing it as tuple will guarantee
that it remains write-protected.
Creating a Tuple
A tuple is created by placing all the items (elements) inside a parentheses (),
separated by comma.
my_tuple = ()
print(my_tuple)
my_tuple = (1, 2, 3)
print(my_tuple)
print(my_tuple)
print(my_tuple)
a, b, c = my_tuple
print(a)
print(b)
print(c)
There are various ways in which we can access the elements of a tuple.
1. Indexing
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[0])
print(my_tuple[5])
print(n_tuple[0][3])
print(n_tuple[1][1])
2. Negative Indexing
my_tuple = ('p','e','r','m','i','t')
# Output: 't'
print(my_tuple[-1])
# Output: 'p'
print(my_tuple[-6])
3. Slicing
my_tuple = ('p','r','o','g','r','a','m','i','z')
print(my_tuple[1:4])
print(my_tuple[:-7])
print(my_tuple[7:])
print(my_tuple[:])
Changing a Tuple
#my_tuple[1] = 9
my_tuple[3][0] = 9
print(my_tuple)
Example :
# Concatenation
# Output: (1, 2, 3, 4, 5, 6)
# Repeat
Deleting a Tuple
we cannot change the elements in a tuple. That also means we cannot delete
or remove items from a tuple.
Example :
my_tuple = ('p','r','o','g','r','a','m','i','z')
#del my_tuple[3]
delmy_tuple
my_tuple
Method Description
index(x
Return index of first item that is equal to x
)
Built-in Functions with Tuple
Function Description
Return True if all elements of the tuple are true (or if the tuple is
all()
empty).
enumerate( Return an enumerate object. It contains the index and value of all the
) items of tuple as pairs.
Take elements in the tuple and return a new sorted list (does not sort
sorted()
the tuple itself).
Set Datatype:
However, the set itself is mutable. We can add or remove items from it.
A set is created by placing all the items (elements) inside curly braces {},
separated by comma or by using the built-in function set().
Example :
# set of integers
my_set = {1, 2, 3}
print(my_set)
print(my_set)
# Output: {1, 2, 3, 4}
my_set = {1,2,3,4,3,2}
print(my_set)
# Output: {1, 2, 3}
my_set = set([1,2,3,2])
print(my_set)
Sets are mutable. But since they are unordered, indexing have no
meaning.
Example :
# initializemy_set
my_set = {1,3}
print(my_set)
#my_set[0]
# add an element
# Output: {1, 2, 3}
my_set.add(2)
print(my_set)
# Output: {1, 2, 3, 4}
my_set.update([2,3,4])
print(my_set)
# Output: {1, 2, 3, 4, 5, 6, 8}
my_set.update([4,5], {1,6,8})
print(my_set)
The only difference between the two is that, while using discard() if the item
does not exist in the set, it remains unchanged.
Example:
# initializemy_set
my_set = {1, 3, 4, 5, 6}
print(my_set)
# discard an element
# Output: {1, 3, 5, 6}
my_set.discard(4)
print(my_set)
# remove an element
# Output: {1, 3, 5}
my_set.remove(6)
print(my_set)
# discard an element
# not present in my_set
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)
# remove an element
Example :
# initializemy_set
my_set = set("HelloWorld")
print(my_set)
# pop an element
print(my_set.pop())
my_set.pop()
print(my_set)
# clearmy_set
#Output: set()
my_set.clear()
print(my_set)
Sets can be used to carry out mathematical set operations like union,
intersection, difference and symmetric difference.
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}
Set Union
Union of A and B is a set of all elements from both sets.
Example :
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use | operator
# Output: {1, 2, 3, 4, 5, 6, 7, 8}
print(A | B)
Example :
Set Intersection
Intersection of A and B is a set of elements that are common in both sets.
Example :
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use& operator
# Output: {4, 5}
print(A & B)
Examples:
Set Difference
Difference of A and B (A - B) is a set of elements that are only in A but not
in B.
Example :
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use - operator on A
# Output: {1, 2, 3}
print(A - B)
Example :
>>>A.difference(B)
{1,2,3}
# use - operator on B
>>> B - A
{8,6,7}
# use difference function on B
>>>B.difference(A)
{8,6,7}
Set Symmetric Difference
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use ^ operator
# Output: {1, 2, 3, 6, 7, 8}
print(A ^ B)
example:
Method Description
Function Description
all() Return True if all elements of the set are true (or if the set is empty).
enumerate( Return an enumerate object. It contains the index and value of all the
) items of set as a pair.
Return a new sorted list from elements in the set(does not sort the
sorted()
set itself).
Dict Datatype
While values can be of any data type and can repeat, keys must be of
immutable type and must be unique.
my_dict={}
# dictionary with integer keys
my_dict={1:'apple',2:'ball'}
# dictionary with mixed keys
my_dict={'name':'John',1:[2,4,3]}
# using dict()
my_dict=dict({1:'apple',2:'ball'})
# from sequence having each item as a pair
my_dict=dict([(1,'apple'),(2,'ball')])
Example :
# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
# my_dict.get('address')
# my_dict['address']
Dictionary are mutable. We can add new items or change the value of
existing items using assignment operator.
If the key is already present, value gets updated, else a new key: value pair is
added to the dictionary.
Example :
# update value
my_dict['age'] = 27
print(my_dict)
# add item
my_dict['address'] = 'Downtown'
Example :
# Output: 16
print(squares.pop(4))
print(squares)
# Output: (1, 1)
print(squares.popitem())
print(squares)
del squares[5]
# Output: {2: 4, 3: 9}
print(squares)
squares.clear()
# Output: {}
print(squares)
del squares
Method Description
Functio
Description
n
Return True if all keys of the dictionary are true (or if the dictionary is
all()
empty).
String Datatype:
Introduction to Strings
Python has several built-in functions associated with the string data type.
These functions let us easily modify and manipulate strings.
Built-in functions are those that are defined in the Python programming
language and are readily available for us to use.
ss = "Sammy Shark"
print(ss.upper())
Ouput
SAMMY SHARK
Now, let’s convert the string to be all lower case:
print(ss.lower())
Ouput
sammy shark
Boolean Methods
Python has some string methods that will evaluate to a Boolean value. These
methods are useful when we are creating forms for users to fill in, for
example.
There are a number of string methods that will return Boolean values:
Method True if
number = "5"
letters = "abcdef"
print(number.isnumeric())
print(letters.isnumeric())
Output
True
False
Now let’s try the Boolean methods that check for case:
movie = "2001: A SAMMY ODYSSEY"
book = "A Thousand Splendid Sharks"
poem = "sammy lived in a pretty how town"
print(movie.islower())
print(movie.isupper())
print(book.istitle())
print(book.isupper())
print(poem.istitle())
print(poem.islower())
Output
False
True
True
False
False
True
print(balloon.split())
Ouput
['Sammy', 'has', 'a', 'balloon.']
print(balloon.replace("has","had"))
Ouput
Sammy had a balloon.
1. Open a file
2. Read or write (perform operation)
3. Close the file
Open a file
We can specify the mode while opening a file. In mode, we specify whether
we want to read 'r', write 'w' or append 'a' to the file.
Mode Description
Open a file for writing. Creates a new file if it does not exist or truncates
'w'
the file if it exists.
Open for appending at the end of the file without truncating it. Creates a
'a'
new file if it does not exist.
Unlike other languages, the character 'a' does not imply the number 97 until
it is encoded using ASCII (or other equivalent encodings).
Close a File
When we are done with operations to the file, we need to properly close the
file.
Closing a file will free up the resources that were tied with the file and is
done using Python close() method.
f = open("test.txt",encoding = 'utf-8')
# perform file operations
f.close()
try:
f =open("test.txt",encoding='utf-8')
# perform file operations
finally:
f.close()
The best way to do this is using the with statement. This ensures that the file
is closed when the block inside with is exited.
We don't need to explicitly call the close() method. It is done internally.
with open("test.txt",'w',encoding='utf-8')as f:
f.write("my first file\n")
f.write("This file\n\n")
f.write("contains three lines\n")
To read a file in Python, we must open the file in ’r’ reading mode.
>>> f =open("test.txt",'r',encoding='utf-8')
>>>f.read(4)# read the first 4 data
'This'
>>>f.read(4)# read the next 4 data
' is '
>>>f.read()# read in the rest till end of file
'my first file\nThis file\ncontains three lines\n'
>>>f.read()# further reading returns empty sting
''
>>>f.readline()
'This is my first file\n'
>>>f.readline()
'This file\n'
>>>f.readline()
'contains three lines\n'
>>>f.readline()
''
>>>f.readlines()
['This is my first file\n','This file\n','contains three lines\n']
seek() method
fileObject.seek(offset[, whence])
Parameters
Offset − This is the position of the read/write pointer within the file.
Return Value
This method does not return any value.
tell ( ) Methode:
We can use the tell() method returns our current position (in number of bytes).
Position = fileObject.tell( )
Return Value
This method return file pointer location.
56
We use modules to break down large programs into small manageable and
organized files. Furthermore, modules provide reusability of code.
We can define our most used functions in a module and import it, instead of
copying their definitions into different programs.
Syntax :
Using the module name we can access the function using dot (.) operation.
For example:
>>> example.add(4,5.5)
9.5
Example.
import math
import math as m
We can import specific names from a module without importing the module
as a whole.
Example
Example
>>> dir(example)
['__builtins__',
'__cached__',
'__doc__',
'__file__',
'__initializing__',
'__loader__',
'__name__',
'__package__',
We don't usually store all of our files in our computer in the same location.
This file can be left empty but we generally place the initialization code for
that package in this file.
Example :
import Game.Level.start
Generally we get two types of errors in any programming Language there are
1. Syntax errors
2. Runtime errors
1. Syntax errors:-
The errors which occurs because of invalid syntax are known as syntax errors.
Whenever we run the python program then internally we will check for the
syntax . If any syntax is written wrongly byte code will not be generated for the
python program
Without generating the byte code program execution will not takes place.
Python programmers has to provide the solutions to syntax errors.
While(1<=3)
print “hello”
2. Runtime errors:-
The errors which occurs at the time of execution of the program are known as
runtime errors.
Generally we will get the runtime errors because of program logic, invalid
input, memory related problems ,……………
With respect to runtime errors corresponding classes are available and we call
those classes as exception classes. Key error, Index error , Zero division error
etc…
At the time of execution of the python program. If any runtime error is
occurred then internally corresponding runtime representation class object will
be created.
If the python program does not contain the code to handle that object then the
program will be terminated abnormally.
Exception handling
Exception handling enables you handle errors gracefully and do something
meaningful about it. Like display a message to user if intended file not found.
Python handles exception using try.. except .. block.
Syntax:
try:
except<ExceptionType>:
try:
f = open('somefile.txt', 'r')
print(f.read())
f.close()
except IOError:
Note: Statements under the else clause run only when no exception is raised.
Note: Statements in finally block will run every time no matter exception occurs
or not.
try:
num1, num2 = input("Enter two numbers, separated by a
comma : ")
result = num1 / num2
print("Result is", result)
exceptZeroDivisionError:
print("Division by zero is error !!")
exceptSyntaxError:
print("Comma is missing. Enter numbers separated by comma
like this 1, 2")
except:
print("Wrong input")
else:
print("No exceptions")
finally:
print("This will execute no matter what")
Raising exceptions
To raise your exceptions from your own methods you need to use raise
keyword like this
Syntax :-
example:-
defenterage(age):
if age < 0:
raiseValueError("Only positive integers are allowed")
if age % 2 == 0:
print("age is even")
else:
print("age is odd")
try:
num = int(input("Enter your age: "))
enterage(num)
exceptValueError:
print("Only positive integers are allowed")
except:
print("something is wrong")
You can use the following code to assign exception object to a variable.
Syntax :-
try:
# this code is expected to throw exception
except ExceptionType as ex:
# code to handle exception
Example:-
try:
number = eval(input("Enter a number: "))
print("The number entered is", number)
exceptNameError as ex:
print("Exception:", ex)
Exception types
12. Python OOPs Concepts
Object
Class
Method
Inheritance
Polymorphism
Data Abstraction
Encapsulation
Object
For example:
Class
For example:
Syntax:
class ClassName:
statement-1>
. ……………
. ……………
. ……………
statement-N
Method
In Python, method is not unique to class instances. Any object type can
have methods.
Inheritance
It specifies that one object acquires all the properties and behaviours of
parent object.
By using inheritance you can define a new class with a little or no changes to
the existing class.
The new class is known as derived class or child class and from which it
inherits the properties is called base class or parent class.
Polymorphism
Encapsulation
In encapsulation, code and data are wrapped together within a single unit
from being modified by accident.
Data Abstraction
class Student:
def __init__(self, rollno, name):
self.rollno = rollno
self.name = name
def displayStudent(self):
print "rollno : ", self.rollno, ", name: ", self.name
emp1 = Student(121, "Ajeet")
emp2 = Student(122, "Sonoo")
emp1.displayStudent()
emp2.displayStudent()
Python Constructors
Creating a Constructor
Every class must have a constructor, even if it simply relies on the default
constructor.
You can create a new attribute for an object and read it well at the time of defining
the values. But you can't create the attribute for already defined objects.
See this example:
class Student:
# Constructor - non parameterized
def __init__(self):
print("This is non parametrized constructor")
def show(self,name):
print("Hello",name)
student = Student()
student.show("irfan")
class Student:
# Constructor - parameterized
def __init__(self, name):
print("This is parametrized constructor")
self.name = name
def show(self):
print("Hello",self.name)
student = Student("irfan")
student.show()
Python Inheritance
It is used to specify that one class will get most or all of its features from its
parent class.
It is a very powerful feature which facilitates users to create a new class with
a few or more modification to an existing class.
The new class is called child class or derived class and the main class from
which it inherits the properties is called base class or parent class.
The child class or derived class inherits the features from the parent class,
adding new features to it. It facilitates re-usability of code.
Image representation:
Python Inheritance Syntax
class BaseClassName():
<statement-1>
.
.
.
<statement-N>
class DerivedClassName(BaseClassName):
<statement-1>
.
.
.
<statement-N>
class Animal:
def eat(self):
print 'Eating...'
class Dog(Animal):
def bark(self):
print 'Barking...'
d=Dog()
d.eat()
d.bark()
Output:
Eating...
Barking...
Python Multilevel Inheritance
We can inherit a derived class from another derived class, this process is
known as multilevel inheritance.
Image representation:
Python Multilevel Inheritance Example
class Animal:
def eat(self):
print 'Eating...'
class Dog(Animal):
def bark(self):
print 'Barking...'
class BabyDog(Dog):
def weep(self):
print 'Weeping...'
d=BabyDog()
d.eat()
d.bark()
d.weep()
Output:
Eating...
Barking...
Weeping
We can derive a child class from more than one base (parent) classes.
Image Representation
The multi derived class inherits the properties of both classes base1 and base2.
class Base1:
pass
class Base2:
pass
class MultiDerived(Base1, Base2):
pass
Output:
first
second
third
import re
The match( ) function returns a match object if the text matches the pattern.
Otherwise it returns None.
pattern = r"Cookie"
sequence = "Cookie"
if re.match(pattern, sequence):
print("Match!")
else:print("Not a match!")
re.search(r'Co.k.e', 'Cookie').group()
'Cookie'
\w - Lowercase w. Matches any single letter, digit or underscore.
re.search(r'Co\wk\we', 'Cookie').group()
'Cookie'
re.search(r'C\Wke', 'C@ke').group()
'C@ke'
re.search(r'Cook\Se', 'Cookie').group()
'Cookie'
\t - Lowercase t. Matches tab.
re.search(r'c\d\dkie', 'c00kie').group()
'c00kie'
\A - Uppercase a. Matches only at the start of the string. Works across
multiple lines as well.
re.search(r'\A[A-E]ookie', 'Cookie').group()
'Cookie'
re.search(r'\b[A-E]ookie', 'Cookie').group()
'Cookie'
\ - Backslash. If the character following the backslash is a recognized
escape character, then the special meaning of the term is taken. For
example, \n is considered as newline.
re.search(r'Back\\stail', 'Back\stail').group()
'Back\\stail'
Repetitions
It becomes quite tedious if you are looking to find long patterns in a sequence.
Fortunately, the re module handles repetitions using the following special
characters:
re.search(r'Co+kie', 'Cooookie').group()
'Cooookie'
re.search(r'Ca*o*kie', 'Cookie').group()
'Cookie'
re.search(r'Colou?r', 'Color').group()
'Color'
pattern = "cookie"
sequence = "Cake and cookie"
re.search(pattern, sequence).group()
match()
pattern = "C"
sequence1 = "IceCream"
sequence2 = "Cake"
re.match(pattern,sequence2).group()
search() versus match()
The match() function checks for a match only at the beginning of the string
(by default) whereas the search() function checks for a match anywhere in
the string.
thread.start_new_thread(function,args)
This method call enables a fast and efficient way to create new threads in
both Linux and Windows.
The method call returns immediately and the child thread starts and calls
function with the passed list of args. When function returns, the thread
terminates.
Example:
import thread
import time
count=0
time.sleep(delay)
count+=1
print"%s: %s"%(threadName,time.ctime(time.time()))
try:
thread.start_new_thread(print_time,("Thread-1",2,))
thread.start_new_thread(print_time,("Thread-2",4,))
except:
import threading
import time
exitFlag=0
class myThread(threading.Thread):
threading.Thread.__init__(self)
self.threadID=threadID
self.name = name
self.counter= counter
def run(self):
print"Starting "+self.name
print_time(self.name,5,self.counter)
print"Exiting "+self.name
def print_time(threadName, counter, delay):
while counter:
if exitFlag:
threadName.exit()
time.sleep(delay)
print"%s: %s"%(threadName,time.ctime(time.time()))
counter-=1
thread1 =myThread(1,"Thread-1",1)
thread2 =myThread(2,"Thread-2",2)
thread1.start()
thread2.start()
import threading
import time
classmyThread(threading.Thread):
threading.Thread.__init__(self)
self.threadID=threadID
self.name = name
self.counter= counter
def run(self):
print"Starting "+self.name
# Get lock to synchronize threads
threadLock.acquire()
print_time(self.name,self.counter,3)
threadLock.release()
while counter:
time.sleep(delay)
print"%s: %s"%(threadName,time.ctime(time.time()))
counter-=1
threadLock=threading.Lock()
threads=[]
thread1 =myThread(1,"Thread-1",1)
thread2 =myThread(2,"Thread-2",2)
thread1.start()
thread2.start()
threads.append(thread1)
threads.append(thread2)
for t in threads:
t.join()
At a low level, you can access the basic socket support in the underlying
operating system, which allows you to implement clients and servers for both
connection-oriented and connectionless protocols.
What is Sockets?
Sockets are the endpoints of a bidirectional communications channel.
Sockets may communicate within a process, between processes on the same
machine, or between processes on different continents.
Sockets may be implemented over a number of different channel types: Unix
domain sockets, TCP, UDP, and so on.
Sockets have their own vocabulary −
1 Domain
The family of protocols that is used as the transport
mechanism. These values are constants such as
AF_INET, PF_INET, PF_UNIX, PF_X25, and so on.
2 Type
The type of communications between the two
endpoints, typically SOCK_STREAM for connection-
oriented protocols and SOCK_DGRAM for
connectionless protocols.
3 Protocol
Typically zero, this may be used to identify a variant
of a protocol within a domain and type.
4 Hostname
The identifier of a network interface −
A string, which can be a host name, a dotted-
quad address, or an IPV6 address in colon (and
possibly dot) notation
A string "<broadcast>", which specifies an
INADDR_BROADCAST address.
A zero-length string, which specifies
INADDR_ANY, or
An Integer, interpreted as a binary address in
host byte order.
5 port
Each server listens for clients calling on one or more
ports. A port may be a Fix num port number.
The socket Module
To create a socket, you must use the socket.socket() function available
in socket module, which has the general syntax −
Once you have socket object, then you can use required functions to create
your client or server program.
1 s.bind()
This method binds address (hostname, port number
pair) to socket.
2 s.listen()
This method sets up and start TCP listener.
3 s.accept()
This passively accept TCP client connection, waiting
until connection arrives (blocking).
1 s.connect()
This method actively initiates TCP server connection.
1 s.recv()
This method receives TCP message
2 s.send()
This method transmits TCP message
3 s.recvfrom()
This method receives UDP message
4 s.sendto()
This method transmits UDP message
5 s.close()
This method closes socket
6 socket.gethostname()
Returns the hostname.
while True:
A Simple Client
host and port, reads any available data from the socket, and then exits −
s.connect((host, port))
print s.recv(1024)