[go: up one dir, main page]

0% found this document useful (0 votes)
19 views66 pages

Class 12 NOTES FOR BOARD EXAM 2023-24

The document provides comprehensive notes on Python programming for Class 12, covering topics such as Python modes, tokens, keywords, identifiers, literals, operators, and data types. It includes detailed explanations of various operators, their precedence, and examples of valid and invalid expressions. Additionally, it discusses built-in functions and standard modules in Python, along with their usage and constants.

Uploaded by

hisas29681
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views66 pages

Class 12 NOTES FOR BOARD EXAM 2023-24

The document provides comprehensive notes on Python programming for Class 12, covering topics such as Python modes, tokens, keywords, identifiers, literals, operators, and data types. It includes detailed explanations of various operators, their precedence, and examples of valid and invalid expressions. Additionally, it discusses built-in functions and standard modules in Python, along with their usage and constants.

Uploaded by

hisas29681
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

EDISON G AGORAM MEMORIAL SCHOOL, CHIDAMBARAM,

COMPUTER SCIENCE (083)


NOTES FOR CLASS 12 BOARD EXAM

Introduction to Python
Python can be used in Interactive mode as well as script mode.
In Interactive mode, the immediate result is shown on the window. Only one statement can be executed at a
time. In Script mode, the file is saved with “.py” extension.
• Tokens- smallest individual unit of a python program.
• Keyword-Reserved word that can‟t be used as an identifier (There are 33 keywords in python)
Python keywords are: in, if, is, as, and, or, not, try, for, del, def, else, elif, while, with, from, True, False,
None, break, continue, class, import, return, pass, except, global, nonlocal, finally, raise, assert, yield,
lambda (33 keywords)
• Identifiers-Names given to any variable, constant, function or module etc. For Example: Mark1,
Student_name

Rules:
⮚ Keywords should not be used
⮚ Upper and lower case characters are treated differently (case sensitive)
⮚ Can be of any length
⮚ Should not begin with a number
⮚ Special characters (except underscore) and spaces are not allowed
Valid Identifiers Invalid identifiers (with reason)
Br_1 None (Keywords cannot be used)
_stud_name_ Stud name (Space is not allowed)
BREAK As+rec (Spl chrs are not allowed)
None 12emp (Cannot begin with a number)
___ (Underscores are allowed) --- ( Spl chars are not allowed)
_ (Underscore is allowed)
• Literals- A fixed numeric or non-numeric value.
String literals -> The text enclosed in quotes. E.g: „abc‟ . Triple quotes is used for multiline
strings. Backslash at the end of multiple lines denotes same line string
Escape sequences: Non graphic characters can be displayed using excape
sequences within a string.
\\ - Backslash \t - horizontal tab
\‟ - single quote \v – vertical tab
\” - double quote \b - backspace
\a - ascii bell \ooo – octal value
\n – new line \xhh – hexadecimal value
Numeric literals -> 12.34, 12365, 0o45, 0O54, 0x54, 0X3, 152E7, 12e-09
Boolean literals -> True, False
Special literal – None
Literal collections
• Comment- Comments are non-executable statement begin with # sign. Docstring-Docstrings are
comments enclosed in triple quotes (single or double).
• Operators – performs some action on data
o Arithmetic(+,-,*,/,%,**,//) NOTE: / returns the answer always in float datatype. When one/more
variable(s) is float, answer will also be in float.

Operator Operation Description Example


+ Addition / Add 2 numbers or concatenate 2 12+24 -> 36
concatenatio strings, list, tuples “12”+”24” -> “1224”
n
- Subtraction Subtracts 2 numbers
* Multiplication Multiplies 2 numbers OR 12*2 -> 24
Replicates str/list/tuple “ab1”*2 -> “ab1ab1”
/ replication
[1,2,5]*3 -> [1,2,5,1,2,5,1,2,5]
/ Division Divides the operand on the left by 8/2 -> 4.0
the operand on the right. Answer
is always a number of float
datatype.
% Modulus Returns the remainder of division 20/6 -> 2
// Floor division Also called integer division. 20/6 -> 3
Returns the quotient after 10 % 3.0 -> 1.0
removing the decimal part.
** Exponent Returns the exponential power of a 4**3 -> 64
number

o Relational/comparison (< , >, <=, >=, = =, !=) Returns True/False as the answer.
s1=”abc”
s2=”A”
s1 > s2 gives True s1 < s2 gives False s1 == s2 gives False
s1 >= s2 gives True s1 <= s2 gives False s1 != s2 gives True
o Logical – and, or , not
Operator Description Example
and If both operands are 1>2 and 3<4 gives False 1 and 0 gives 0
True, output is True 1<2 and 3<=4 gives True [ ] and 1 gives [ ]
or If any ONE operand is 1>2 or 3<4 gives True 2 or 3 gives 2
True, output is True 1>2 or 3>=4 gives False 0 or 5 gives 5
not Returns the reverse of not(2.0==2) gives False
the state. True returns not(3<2) gives True
False and vice versa.

O Assignment-(=,/=,+=,-=,*=,%=,**=,//=) Also called as augmented assignment operators.


Examples:
Let, a=5, then a+=3 will give 8 Note: a+=2 is equal to a=a+2
Let a= “ss”, then a+=”bb” will give “ssbb” a*=3 is equal to a=a*3
Let a=5, then a-=10 will give -5
Let a=10, then a*=5 will return 50
If a=10, then a/=5 will return 2.0
a//=3 will return 3
a%=4 will return 2
a**=2 wil return 100
o Membership – in, not in
in returns True if the variable/value is found in the sequence E.g: 10 in [20,45,0,10,90] will return True
not in returns True if the variable/value is NOT found in the sequence E.g: 10 not in [20,45,0,10,90] will
return False.
o Identity – is, is not
is operator returns True if both variables point towards the same memory location, i.e, the
id(var1) is the same as id(var2).
is not operator returns False if both variables point to the same memory location.
NOTE: „is‟ operator will return True if both values are same and they are small integers(upto
number 256), strings, Boolean. It returns False for float, complex and sequence data types.
„is‟ operator always returns True if both variables are assigned the same value in the same
statement. For e.g: a=b=c=9.875, Here, a is b will return True.
Examples:
A=1900 a=”asd” a=b=19200 a=[1,2,3] a=False
B=1900 b=”asd” a is b -> True, as b=[1,2,3] b=False
A is B -> False a is b -> True both are assigned a is b-> False a is b -> True
Reason: as both are the value in the a=b=[1,2,3]
Numbers are big strings same statement a is b -> True a=1.1
integers more b=1.1
than 256 a is b -> False
NOTE: If == operator returns True, is operator may/may not return True.
If the is operator returns True, then == operator WILL return True.
Truth value testing
The values with truth value as False : None, 0, 0.0, False, „‟, ( ), [ ], { }
All other values are considered to be True.
In an expression of the form X or Y, if X is True then result is X, else Y is the result.
In an expression of the form X and Y, if X is True then Y is the result, else X is the result.
For example: 5 or 0.0 -> 5 is a True value. So result is 5
„‟ or „d‟ -> „‟ is False value, so „d‟ is the result
„‟ and „a‟ -> „‟is False, so „‟ is returned
„a‟ and „f‟ -> „a‟ is True, so „f‟ is returned.

Comparison operators: (Relational operators)


Comparison of strings is done on the basis of Lexicographical ordering implemented via ordinal values
„A‟ has the smallest value among alphabets, „z‟ has the highest value.
NOTE: 1<2<3 is evaluated as a<2 and 2<3
So a<b and b<c can be written as a<b<c
BITWISE OPERATORS:
OPERA OPERATION EXAMPLE DESCRIPTION
TOR If a=23,
b=18
& bitwise and a&b Convert a and b to binary, compare bit by bit and apply rules
of and operation. (If both inputs are 1, then answer is 1)
| bitwise or a|b Convert a and b to binary, compare bit by bit and apply rules
of or operation. (If any one input is 1, then answer is 1)
^ bitwise xor a^b Convert a and b to binary, compare bit by bit and apply rules
of xor operation. (If either input is 1, then answer is 1)
~ bitwise ~a Convert a to binary and find the complement of each bit.
complement

Precedence of operators: (High to low)


Order of Operators Description
precedence
1 ** Exponentiation
2 ~, +, - Complement, unary plus, unary minus
3 * , / , % , // Multiply, divide, modulus, floor division
4 +, - Addition, subtraction
5 <=, < , > , >= , = = , ! = Relational/comparison operators
6 =, %=, /=, //=, -=, +=, *=, **= Assignment operators
7 is, is not Identity operators
8 in, not in Membership operators
9 not
10 and Logical operators
11 or

NOTE: An expression is evaluated from left to right if the operators are of equal precedence.
For e.g: 1//2*5%3 -> All operators are of equal precedence, So, evaluate from left to right.
Exponents must be evaluated from right to left. For e.g: 2**3**4 -> First evaluate 3**4 and then 2**x
3**2**1**2 -> Evaluate as 3**(2**(1**2))

VALID EXPRESSIONS: INVALID expressions:


A=12 12= a
a=b+c A + b =20
a,b=10,20 a,b=20
a=10,20,30 (a will become a tuple with (10,20,30)) x,y=20,30,40
c=000 (will be considered as 0) c=001 (will cause error as 001 is NOT a number)
a,b,c=000,100,000 (a and c will have 0, b will store a,b,c=001,009,008 (Will cause error as 009,001 and
100) 008 are INVALID numeric literals)
Data type:
The following are the basic types of variables in Python:
Type Description
int Stores a whole number.
bool Stores either value True(1) or False(0). It is a subtype of int datatype
float Stores numbers with a fractional part.
Complex Stores a number having real and imaginary part (a+bj)
String Stores text enclosed in single or double quote
List Stores list of comma separated values of any data type between square [ ] brackets
Tuple Stores list of comma separated values of any data type between parentheses ( )
single element tuple should be added with a comma E.g: (10,)
Let a=(10) b=([1,2,3]) Here a and b are not tuples.
Dictionary Unordered set of comma-separated key:value pairs, within curly braces {}. It is a mapping
datatype.
None A special data type with a single value. It is used to signify the absence of value in a
situation. None supports no special operations, and it is neither False nor zero
Immutable datatypes: int, float, complex, str, tuple
Mutable datatypes: list, set, dictionary
NOTE:Converting a data type to another is called type casting. We can use int(), float(), str() , list() tuple()
etc to type cast one data type to another. This is called explicit type conversion.
For E.g: if n=‟2.2‟, float(n) will convert „2.2‟ into floating value 2.2
But, int(n) will cause error, bool(n) will return True
If n=‟‟, bool(n) will return False, int(n) and float(n) will cause an error as an empty string cannot be
converted to int or float
In an expression 3.0 +5 -> python will convert 5 to 5.0 and then adds and gives the result as 8.0 This is
called implicit type conversion.

Built-in functions:
Function Description
id( ) Returns the unique identity of an object. It returns the memory location of the object.
type( ) Returns the data type of an object
abs() Returns the absolute value of a number
bin() Returns the binary version of a number
bool() Returns the boolean value of the specified object
chr() Returns a character from the specified Unicode code
eval() Evaluates and executes an expression
hex() Converts a number into a hexadecimal value
id( ) Returns the id of an object
oct() Converts a number into an octal
ord() Convert an integer representing the Unicode of the specified character
pow(x,y) Returns the value of x to the power of y
pow(x,y,z) Returns the value of x to the power of y modulus z (i.e, x**y%z)
divmod(x,y) Returns a tuple with the quotient and remainder
divmod(7,2) returns (3,1) where 3 is the quotient and 1 is the remainder
range() Returns a sequence of numbers, starting from 0 and increments by 1 (by default)
round(n,m) Rounds a number
type() Returns the type of an object
eval( ) Returns the evaluation of a given expression. For e.g: a=eval(„3*10‟) will return 30 to a
a=eval(input()) -> If we type 30.5 + 2.2, a will store 32.7, a will be of data type float.
a=eval(input()) -> If we type [1,2,3] the list [1,2,3] will be saved inside a
a=eval(input()) -> If we type 20, the integer 20 will be saved in a, type(a) will give int

Standard modules in Python: Python library has many built-in modules that are really handy to
programmers. Some modules are math module, statistics module, random module
How to use a module in our program?
We have to import the module in our program and call the function name with module name.
Example 1:
import math
print(math.sqrt(16))
Example 2:
import math as m
print(m.sqrt(16))
Example 3:
from math import sqrt # To import only the needed function
print(sqrt(16)) # Note: module name should not be included in this method
Example 4:
from math import * #Imports all functions from the module.
print(pow(4,2)) # Should not refer to module name in this method of import
To know more about a module, we can use help()
Type help(“math”) to know more about functions inside math module.
Constants in math module:
print(math.pi) → 3.141592653589793

print(math.e) → 2.718281828459045
Functions in math module
Function Syntax Arguments Returns Example Output
math.ceil(x) x may be an integer or ceiling value of x >>> math.ceil(-9.7)
floating point number -9
>>> math.ceil (9.7)
10
>>> math.ceil(9)
9
math.floor(x) x may be an integer or floor value of x >>> math.floor(-4.5)
floating point number -5
>>> math.floor(4.5)
4
>>> math.floor(4)
4
math.fabs(x) x may be an integer or absolute value of x >>> math.fabs(-6.7)
floating point number 6.7
>>> math.fabs(-4)
4.0
math.pow(x,y) x, y may be an integer xy (x raised to the >>> math.pow(3,2)
or floating point power y) 9.0
number >>> math.pow(4,2.5)
32.0
>>> math.pow(6.5,2)
42.25
>>> math.pow(5.5,3.2)
233.97
math.sqrt(x) x may be a positive square root of x >>> math.sqrt(144)
integer or floating point 12.0
number >>> math.sqrt(.64)
0.8
math.sin(x) x may be an integer or sine of x in radians >>> math.sin(0)
floating point number 0
in radians >>> math.sin(6)
math.cos(x) cos of x in radians -0.279

math.tan(x) tan of x in radians

math.exp(x) x may be any int or Gives the natural math.exp(8)


float number logarithm e raised to 2980.9579870417283
the power of x

Functions in Random module


random( ) – generates a floating point number from 0 to 1 (excluding 1)
randint(a,b) – generates an integer between a and b, including both a and b
E.g: random.randint(5,50) will generate any one number between 5 to 50 including 5 and 50.
randrange(a,b,step) – generates an integer from a to b, excluding b, with a step value
For e.g: randrange(5,20,5) will generate numbers 5 or 10 or 15.
Functions in statistics module
mean( ) – returns the mean value of a given sequence
Eg: statistics.mean([10,20,30,40,50]) will return 30
median( ) - returns the median value of a given sequence
mode( ) – returns the mode value of a given sequence
FLOW OF CONTROL
range( ) function – generates a sequence of numbers of datatype list.
range( n) will produce a list of numbers from 0 to n-1.
range(4) -> 0,1,2,3 range(5,10) -> 5,6,7,8,9 range(5,15,3) -> 5,8,11,14
range(9,3,-1) -> 9,8,7,6,5,4 range(10,2,-2) -> 10,8,6,5
Counting loop -> for loop (used when we exactly know the number of times of loop execution)
Conditional loop - > while loop (used when we don‟t know the number of times of execution). while loop
is called an entry controlled loop.
break statement -> when break is used, the loop stops execution. The loop terminates and the statement
after the loop is executed. In nested loops, if a break stmt is given in the inner loop, the inner loop is
terminated, but the outer loop execution continues.
continue statement -> When continue statement is used, the iteration stops at that point, skips the rest of the
statements and proceeds to the next iteration. It forces the next iteration of the loop.
else statement in for, while loop: else statement gets executed if the loop works normally till the last
iteration and does not break anywhere. If the loop breaks anywhere, the else part will NOT be executed. If
the while loop is not executed even once, the else part gets executed.
TYPES OF ERRORS:
1. Syntax errors – Syntax refers to the formal rules governing the construction of valid statements in a
language. If the rules of the language are not followed syntax errors occur. For e.g, missing a quote, bracket,
giving =+ instead of += etc. Syntax errors are detected when we have not followed the rules of the particular
programming language while writing a program. These errors are also known as parsing errors. On
encountering a syntax error, the interpreter does not execute the program unless we rectify the errors

2. Semantics error – They occur if the statements are not meaningful.For example 10+20=b -> as an
normal expression may look good but does not make any meaning in the program.

Syntax errors and semantic errors are called Compile time errors because they are indicated during
compilation. We cannot run the program without rectifying them.

3. Run Time Error: Errors that occur while the program is running. The program is free of syntax errors
and occurs during execution. Some of the example of run time error are:
● Division by Zero
● Using of undefined variable
● Trying to access a non existing file

3. Logical Error: Errors in the program‟s logic, which do not produce errors but lead to incorrect results. If
the program is syntactically correct, but produces incorrect result, it may have a logical error. It may not
show an error message. Exception will not be raised.
Some of the example of logical error are:

⮚ Giving wrong operator precedence


⮚ using wrong variable name for calculation

EXCEPTIONS – Exception is an irregular situation that occurs during run time. Error is a bug that stops
the code from execution. An exception is a type of error that occurs during program execution. Python
generates an exception whenever an error is encountered.

Built-in Exceptions:
IndexError When the wrong index of a sequence is accessed.
ImportError It occurs when an imported module is not found.
KeyError It occurs when the key of the dictionary is not found.
NameError It occurs when the variable is not defined.
TypeError It occurs when a function and operation are applied in an incorrect type. sqrt(“w”)
EOFError Raised when one of the built-in functions hits the end of file condition while reading data
IOError Raised when an I/O operation fails for an I/O related reason. E.g: File not found, Disk full
ValueError Raised when a built-in operation of function receives an argument with an inappropriate
value. E.g: int(“as”)
ZeroDivisionError Raised when the second argument of a division or modulo operation is zero.
OverflowError Raised when the result of an arithmetic operation is too large to be
represented.

Error vs. Exception


– Error: Any mistake or issue in the code.

– Exception: An unexpected situation or error during program execution.

Exception Handling
– Exception handling is the process of dealing with run-time errors. It involves using `try…except` blocks to
catch and handle exceptions.

Why should an Exception be handled?


Each and every exception has to be handled by the programmer to avoid the program from crashing
abruptly. This is done by writing additional code in a program to give proper messages or
instructions to the user on encountering an exception. This process is known as exception
handling.
Handling Multiple Exceptions
In Python, you can handle multiple exceptions in the same program by using multiple except blocks within a
try block. Each except block is responsible for handling a specific type of exception.

def divide_numbers(a, b):


try:
result = a / b
except ZeroDivisionError:
print("Error: Division by zero!")
result = None
except ValueError:
print("Error: Invalid input value!")
result = None
except TypeError:
print("Error: Invalid data type!")
result = None
except Exception as e:
print(f"An unexpected error occurred: {e}")
result = None
finally:
print("Exception Handing in Python...")
return result
Important points regarding exceptions and their handling:
• Python categorises exceptions into distinct types so that specific exception handlers (code to handle that
particular exception) can be created for each type.
• Exception handlers separate the main logic of the program from the error detection and correction code.
The segment of code where there is any possibility of error or exception, is placed inside one
block. The code to be executed in case the exception has occurred, is placed inside another
block. These statements for detection and reporting the exception do not affect the main logic
of the program.
• The compiler or interpreter keeps track of the exact position where the error has occurred.
• Exception handling can be done for both user-defined and built-in exceptions.

How are Exceptions handled in Python?


1. When an error occurs, Python interpreter creates an object called the exception object. This object
contains information about the error like its type, file name and position in the program where the
error has occurred
2. This object is handed over to Run time system which is called “Throwing an exception”.
3. The Runtime system now searches the module for the Exception handlers in all the modules used in
the program which is stored in the “Call stack”.
4. If the runtime system is not able to find an appropriate exception, the program terminates.

try..except..finally blocks:
Exceptions, if any, are caught in the try block and handled in the except block. While writing or debugging a
program, a user might doubt an exception to occur in a particular part of the code. Such suspicious lines of
codes are put inside a try block. Every try block is followed by an except block. The appropriate code to
handle each of the possible exceptions (in the code inside the try block) are written inside the except clause.
While executing the program, if an exception is encountered, further execution of the code inside the try
block is stopped and the control is transferred to the except block. When an exception is raised, a search for
the matching except block is made till it is handled. If no match is found, then the program terminates.
However, if an exception is raised for which no handler is created by the programmer, then such an
exception can be handled by adding an except clause without specifying any exception. This except clause
should be added as the last clause of the try..except block.

The syntax of try … except clause is as follows


try: [ program statements where exceptions might occur] except [exception-name]: [ code for exception
handling if the exception-name error is encountered]

else clause
We can put an optional else clause along with the try...except clause. An except block will be executed. only
if some exception is raised in the try block. But if there is no error then none of the except blocks will be
executed. In this case, the statements inside the else clause will be executed.

Finally Clause
The try statement in Python can also have an optional finally clause. The statements inside the finally block
are always executed regardless of whether an exception has occurred in the try block or not. It is a common
practice to use finally clause while working with files to ensure that the file object is closed. If used, finally
should always be placed at the end of try clause, after all except blocks and the else block.

Example:
print ("Handling exception using try...except...else")
try:
numerator=50
denom=int(input("Enter the denominator: "))
quotient=(numerator/denom)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed")
except ValueError:
print ("Only INTEGERS should be entered")
else:
print ("The result of division operation is ", quotient)
finally:
print ("OVER AND OUT")

In the above program, the message “OVER AND OUT” will be displayed irrespective of whether an
exception is raised or not.

String: Text enclosed inside the single or double quotes is referred to as a String.
String Operations: String can be manipulated using operators like concatenation (+), repetition (*)
and membership operators like in and not in.

Operation Description
Concatenation Str1 + Str2 (Both must be strings)
Repetition Str * x (One must be a string, one should be an integer)
Membership in , not in
Comparison str1 > str2
(>, >=, <, <=, ==, != )
Slicing String[range]

Examples:
„1‟+‟1‟ gives „11‟ „1+1‟+‟=‟ gives „1+1=‟
If ab=3, „ab‟+ab - > gives error because ab is a number
„st‟*3 gives “ststst” „py‟ in „python‟ -> True „PY‟ in „python‟ -> False „p y‟ in „python‟ - > False
String comparison: Strings are compared using the ordinal numbers.
„A‟ has ordinal value 65, „Z‟ has value 90, „a‟ has value „97‟, „z‟ has value 122.
0 to 9 numbers have ordinal value 48 to 57.
„a‟ > „AP‟ -> True
„AAAAA‟ > „a‟ -> False
String slicing: (A string is sliced only from left to right unless a negative step value is given)
s=‟abcdefghij‟
s[:3] slices string with index 0 to 2 -> “abc” s[4:] slices string from index 4 onwards -> „efghij‟
s[:] returns entire string s[::2] returns alternate characters „acegi‟
s[::-1] returns the reverse of the string s[::-2] returns the reverse with alternate characters
s[15] will cause error as the index is NOT found s[-13] will cause error as the index is NOT found
s[-1:-9:-2] will return the reverse order from -1 till -8 with alternative chars

NOTE:
⮚ s[-20:3] will not cause error, s[3:45] will not cause any error. Index numbers will not generate OUT
OF BOUND ERROR during slicing.
⮚ name=”PYTHON”
for I in range(-1,-(len)-1,-1):
print(name[I],end=‟‟) -> will display “NOHTYP”

String Methods and Built-in functions:

Function Description
len() Returns the length of the string.
capitalize() Converts the first letter of the string in uppercase, others to lowercase
split() Breaks up a string at the specified separator and returns a list of substrings.
S=‟as df‟ S=‟asersf‟
S.split( ) will return [„as‟,‟df‟] S.split(„s‟) will return [„a‟,‟er‟,‟f‟]
S.split(„h‟ will return [„as df‟] S.split(„er‟) will return [„as‟,‟sf‟]
s='asadfa'
s.split('a') will return ['', 's', 'df', '']

partition( ) divides the string into 3 parts and returns a tuple containing the 3 parts.
S=‟asertf‟
S.partition(„er‟) -> will return („as‟,‟er‟,‟tf‟)
S.partition(„ „) -> will return („asertf‟,‟‟,‟‟)
replace() It replaces all the occurrences of the old string with the new string.
s=‟adadad‟
s.replace(„a‟,‟d‟) will give „dddddd‟, s.replace(„a‟,‟‟) will give „ddd‟
find() It is used to search the first occurrence of the substring in the given string.
Returns -1 if the substring is NOT found.
s.find(„a‟) -> returns the index of the first occurrence
s.find(„a‟,2,8) -> finds the occurrence within the given index range
index() It also searches the first occurrence and returns the lowest index of the substring.
Results in an ERROR if the substring is NOT found.
isalpha() It checks for alphabets in an input string and returns True if the string contains only letters.
„AS FG‟.isalpha() is False as it contains a space.
isalnum() It returns True if all the characters are alphanumeric. Returns False even if there is a space
isdigit() It returns True if the string contains only digits. Returns False even if there is a space
title() It returns a string with first letter of every word in uppercase and rest in lowercase.
count() It returns number of times substring str occurs in the given string.
s.count(„a‟,2,6) will count the occurrence from index 2 to 5 alone. If the element is not found
it returns 0.
lower() It converts the string into lowercase
islower() It returns True if all the letters in the string are in lowercase.
upper() It converts the string into uppercase
isupper() It returns True if all the letters in the string are in uppercase.
lstrip() It returns the string after removing the space/substring from the left of the string
„abcdefg‟.lstrip(„abc‟) will return „defg‟
rstrip() It returns the string after removing the space/substring from the right of the string
„abcdefg‟.rstrip(„fg‟) will return „abcde‟
„abde‟.rstrip(„fe‟) will return „abcd‟ -> will search and remove substrings „f‟,‟e‟ or „fe‟
strip() It returns the string after removing the space from the both side of the string
„abca‟.strip(„a‟) will return „bc‟, „abcde‟.strip(„a‟) will return „bcde‟
isspace() It returns True if the string contains only whitespace characters, otherwise returns False.
„ „.isspace() -> True, „ - „.ispace() -> False
istitle() It returns True if the string is properly title-cased (First letter of every word is in capitals)
join( ) s=‟abc‟
s.join(„++‟) will return „a++b++c‟
LISTS:
A list is a collection of comma-separated values (items) of same or different type within square
brackets. List types can be of three types: 1. Empty list 2. Long List 3. Nested List
Lists are ordered, indexed, immutable data type.
L=[1,2,3] -> L[1]=10 will change the list to [1,10,3]
But, tuples inside lists cannot be changed. In L=[1,2,(2,3)], L[2][0]=1 will cause an error. But L[2]=3 can
change the entire element. It will result in L=[1,2,3]

L=[„abc‟,‟xy‟], here L[1][1]=‟a‟ will cause an error as strings are immutable.


If L=[1,2,3,4,5,6], L[1:4]=[100] will return L as [1,100,5,6]
Lists can be unpacked into individual variables. For e.g, if L is [1,2,3],
a,b,c=L will store 1 in a, 2 in b and 3 in c. The number of variables and list elements should be equal.
L=[1,2,3,4,5,6] L=[1,2,3,4,5,6]
>>> L[1:4]='ab' >>>L[3:]=[10,20,30]
L will return [1, 'a', 'b', 5, 6] L will return [1, 2, 3, 10, 20, 30]

Creating lists:
L1=list(„abc‟) will create L1 as [„a‟,‟b‟,‟c‟]
L1=list(range(4)) will create a list L1 as [0,1,2,3]
L1=list(input()) -> If you type „123‟, L1 will store [„1‟,‟2‟,‟3‟]
L1=eval(input()) -> we can directly type [1,2,3,4] in the input with square brackets
List operators:
Concatenation -> + Replication -> * Membership operators -> in, not in
List concatenation:
L=[1,2]
L=L+2 or L=L+‟ab‟-> will cause error, as an int or str or other data cannot be concatenated with a list.
NOTE: L+=‟ab‟ will result in [1,2,‟a‟,‟b‟]
L=L+[[1,2]] will result in [1,2,[1,2]]
List replication:
L=[1,2,3,4,5]
L[1:3]*2 will return [2, 3, 2, 3]
Membership operators:
If L=[„a‟,‟b‟,‟abc‟] , „a‟ in L will return True, „c‟ in L will return False because it checks the entire element
as a whole and not individual elements.
Comparing lists:
l1,l2=[1,2],[3,4]
l1>l2 will return False. It will compare element by element. If l1 and l2 are of int and string datatype it will
cause error. For e.g l1=[1,2], l2=[„a‟,‟b‟] , l1>l2 will show error
NOTE: In nested list, l=[1,5,[12,24],6] -> l[2] will return [12,24], l[2][1] will return 24
List slicing is done the same way as in strings.
Copying Lists:
A=[10,20]
B=A -> This will create a false copy of A, which means both A and B will refer to the same list.
If an element is added or deleted from A, it will also be reflected in B.
To avoid this, a true copy of a list has to be created. A true copy of a list can be created as follows:
b=list(a) (or) b=a.copy() (or) b=a[:]
By these ways, A and B will be two individual lists. Changes done in one list will not affect the other.
Built-in Function (Manipulating Lists)
Function Description
list() Converts the given sequence into a list. For e.g: list(„abc‟) will return [„a‟,‟b‟,‟c‟]
append() It adds a single item to the end of the list. Only one element can be added at a time.
For eg: if L=[1,2], L.append(3) will be [1,2,3], L.append((1,2)) will give [1,2,(1,2)]
extend() It adds one list at the end of another list. A single integer or float can‟t be added.
If L=[1,2,3] , L.extend([4,5,6]) will return [1,2,3,4,5,6]
L.extend(10) will return error, as a single number can‟t be added using extend.
insert() It adds an element at a specified index. Other elements will move one position to the
right.
If L=[1,2,3], L.insert(1,10) will return [1,10,2,3], L.insert(7,10) add 10 at the end.
L.insert(-10,10) will add 10 at the beginning of the list.

reverse() It reverses the elements (in place) in a list.


index() It returns the index of the first matched item from the list. If it is not found, an error is
raised
len() Returns the length of the list i.e. number of elements in a list
sort() This function sorts the items of the list. (sorts in place). Does not return anything.
A1.sort() will sort list A1 in ascending order. A1.sort(reverse=True) will sort in descending.
sorted() This function sorts and returns a new list. The old list remains unchanged.
B=sorted(A, reverse=True)
NOTE: To use sort(), sorted(), elements should be of the same datatype. Nested lists can‟t be sorted.
clear() It removes all the elements from the list. The list becomes empty.
count() It counts how many times an element has occurred in a list and returns it. It returns 0 if the
element is not found.
pop() It removes the element from the end of the list or from the specified index and also returns it.
If L=[10,20,30], L.pop(0) will pop out the element from index 0. If the index is not given, the
last element is popped out. Error is returned if the index is out of range. An error is returned
when the list is empty.
del <index> It removes the specified element from the list L[1:3] will remove elements of index 1,2
del L[3] will delete the element in index 3. It returns out of range, if index is not found.
remove() It is used when we do not know the index of the element. We can delete the element by
giving the element itself. If the element is not found, an error is raised.
max() Returns the element with the maximum value from the list
min() Returns the element with the minimum value from the list
sum() Returns the sum of the elements in a list.
NOTE: sum( ) works only for numbers(int, float, complex). Numbers in nested lists cannot be added.
max() and min() works for same datatype. But, not for combination of elements and nested lists and
complex numbers.

TUPLE:
Tuple is a data structure in python which is indexed and immutable. A tuple consists of multiple values in a
single variable separated by commas. Tuples are enclosed within parentheses().
Creating Tuples:
T= ( ) (Creates an empty tuple)
T=(1,2,3,x,3*2) -> will assign x value to index 3 and 6 in index 4.
For single element assign with a comma at the end. T=(10,)
Note: T=(10) -> is not a tuple. It is stored as an integer.
Common Tuple Operations: (Similar to lists)
Operation Description
Concatenation Tuple1 + Tuple2
Repetition Tuple * x
Slicing Tuple[range]
Membership in and not in

Tuple Functions:
Function Description
del It is used to delete the tuple. E.g: del T1 will delete the entire tuple, del T1[1] will cause an
error. We cannot delete individual elements or slices as tuples are immutable.
index( ) It returns the index of first matched item from the tuple.
len( ) Returns the length of the tuple i.e. number of elements in a tuple
count( ) It counts how many times an element has occurred in a tuple and returns it.
any ( ) It returns True if a tuple is having at least one item otherwise False.
sorted( ) It is used to sort the elements of a tuple. It returns a list after sorting.
sum( ) It returns the sum of the elements of the tuple.
max( ) Returns the element with the maximum value from the tuple.
min( ) Returns the element with the minimum value from the tuple.

NOTE: count(), index(),sum(), max(), min(), sorted(), len() functions work in the same way like lists.
If t=(1,2,(2,3)), sum(t) will cause an error.
If t=((1,2),(2,3)), max(t) or min(t) will work well. If t=(1,2,(2,3)), max(t) and min(t) will cause an error.
Packing and unpacking tuples:
Creating a tuple from a set of values is called packing. E.g: t=(a,b,c) will create a tuple t with 3 values.
Creating individual variables from a tuple‟s element is called unpacking.
E.g: a,b,c,d=T1 will create 4 variables from the values of tuple T1.
Indirectly changing the elements‟ value in a tuple:
� Unpack the tuple elements, change and values and pack them into a tuple again.
� Convert the tuple to a list, change the value of elements and convert the list to tuple again.

DICTIONARY:
Python Dictionaries are a collection of some key-value pairs. Dictionaries are mutable unordered
collections with elements in the form of a key:value pairs that associate keys to values. Dictionaries are
enclosed within braces {}. It is also called as mapping datatype.
Creating a dictionary:
E.g: emp= {„name‟:‟john‟‟age‟:25,‟pay‟:10000}
emp={ } will create an empty dictionary.
emp(“name”)=”John” -> will add “name” as a key and “John” as its value. If the key called “name” already
exists, the value will be replaced with the new value.
Creating a dictionary from name, value pairs:

⮚ emp= dict(name=”John”,sal=1000) will create a dictionary as {“name”:”John”,”sal”:1000}

⮚ To create a dictionary from 2 tuples, one with the keys, one will become the values, For E.g:
emp=dict(zip((„name‟,‟age‟,‟sal‟),(„Anu‟,28,20000))) , This will create a dictionary as follows:
{„name‟:‟Anu‟,‟age‟:28,‟sal‟:20000}

⮚ emp=dict([(„name‟,‟Anu‟),(„sal‟,20000),(„age‟,28)]) will also create a dictionary as given above.


Nested Dictionary:
D1={„Jack‟:{„roll‟:101,‟age‟:45,‟sal‟:25000},‟sam‟ :{„roll‟:105,‟age‟:28,‟sal‟:35400}}
D1[„Jack‟] will print {„roll‟:101,‟age‟:45,‟sal‟:25000}
D1[„Jack‟][„age‟] will return 45
To check if a key is present in the dictionary:
If emp= {„name‟:‟john‟‟age‟:25,‟pay‟:10000}, „name‟ in emp will return True,
„john‟ in emp will return False, „john‟ not in emp will return True
To check if a value is present in a dictionary:
If emp= {„name‟:‟john‟‟age‟:25,‟pay‟:10000}, „name‟ in emp.values( ) will return True,
Functions / Methods in Python:
Function Description
dict( ) It creates a dictionary from a given sequence.
If a1=[(1,10),(2,20)], d1=dict(a1) will create a dictionary {1:10,2:20}
If a=(1,2,3) , d1=dict(a) will cause an error as it does not have a key-value pair.
get( ) It returns the value for the given key , For E.g: d.get(„name‟) will return the value „john‟
If key is not available then it returns None, if d.get(“Names”,‟Sry‟) is not found, „Sry‟ will be
printed on the screen.
items( ) It returns the content of dictionary as a list of tuples having key-value pairs.
keys( ) It returns a list of the key values in a dictionary, emp.keys( ) will return a list of dict_keys
values( ) It returns a list of values from key-value pairs in a dictionary, emp.values( ) will return a list
of dict_values
copy( ) It creates a copy of the dictionary. This creates a shallow copy. If the values are immutable,
the changes will not be reflected in the other dict. If the values are mutable, it will be
reflected in the other dictionary.
len( ) Returns the length of the Dictionary i.e. number of key:value pairs in a Dictionary
fromkeys( ) It is used to create a dictionary from a collection of keys(tuple/list)
For E.g: D1=dict.fromkeys([1,2,3],100) will create D1 as {1:100,2:100,3:100}, If the value
100 is not given, the values will be assigned as None.
setdefault() This method works in two ways. <dict>.setdefault(<key>,<value>)
If the key is not present in the dictionary, it will be added as a new key:value pair.
If the key is already present, the old value will be retained.
If d={„a‟:10,‟b‟:20,‟c‟:15}, d.setdefault(„d‟,50) will add „d‟:50 to the dictionary.
d.setdefault(„a‟,30) will not change the value of „a‟.
clear( ) It removes all the elements from the Dictionary. It becomes empty.
sorted( ) It sorts the elements of a dictionary by its keys. All keys have to be of the same datatype to
sort.
D=sorted(D1, reverse=True) -> sorts Dict D1 based on descending order of keys
D=sorted(D1.keys()) -> same as sorted(D1) will return a list of sorted keys alone.
D= sorted(D1.values()) -> will return a list of sorted values from the dict.
update( ) This method will merge a dictionary with another dictionary. New keys will be added.
Existing keys‟ values will be updated. For e:g, if D1={1:10,2:20,3:30}, D2={4:40,2:60}
D1.update(D2) will change D1 as {1: 10, 2: 60, 3: 30, 4: 40}
pop( ) It removes and returns the element of the respective key.
For eg: if d={1:20,2:40,3:70}, d.pop(3) will pop and return the value of the given key.
Returns an error if the key is not found. To avoid an error, d.pop(5,”Sry”) will print “Sry” if
the key is not found.
popitem( ) Removes and returns the last item added to the dict. Key is not needed for method.
max( ) Returns the max. key in the Dictionary. To find the max. value, use max(d.values())
min( ) Returns the min. key in the Dictionary. To find the min. value, use min(d.values())
sum( ) Returns the sum of keys in the dictionary. To add the values, use sum(D1.values())

FUNCTIONS
A function is a sub program that acts on data and often returns a value. It ensures code reusability and
modularity.
A function is a set of statements that take inputs, do some specific computation, and produce output. The
idea is to put some commonly or repeatedly done tasks together and make a function so that instead of
writing the same code again and again for different inputs, we can call the function. This reduces the size of
the program.

We can create functions that can:


o Can perform some functionality
o have arguments if needed
o can return a result

Defining a function(syntax):
def <function name> (parameters1, 2,….) :
<Statement 1>
<Statement 2>


<Statement n>
return <variable/value/expression>

Calling a function (Invoking):


<Function name> (arguments)
Example:
#Function to add 2 numbers
def add(x,y) : #Line 1
z=x+y #Line 2
return z #Line 3
a=int(input()) #Line 4
b=int(input()) #Line 5
c=(add(a,b)) #Line 6
print(c)

In the example given above: #Line1 is the function header.


#Line 2 and 3 are the function statements.
#Line 4,5,6 belong to the main program referred as “_main_”
add(a,b) in #Line 6 is the function calling/invoking statement.
x,y are called as parameters/formal parameters / formal arguments
a,b are called as arguments / actual arguments / actual parameters
The number of arguments passed in the function call and parameters in the function definition should match.

Order of execution:
1) All function defn. statements alone are executed first. (not the stmts inside the function)
2) main statements are executed line by line.
3) When function call statement is encountered, the execution transfers to function definition.
4) All statements inside function definition are executed.
5) When return statement is encountered, execution comes back to the main function to the statement again.
Example:
def add(x,y): # L1 Order of execution
print(“Sum”) #2 #L1 -> 4 -> 7 -> 8 -> 9 -> 1 -> 2 -> 3 -> 9 -> 10
return x+y #3 -> 4 -> 5 -> 6 -> 10
def sub(x,y): #4
print(“Difference”) # 5 Important:
return x-y #6 Lines 7,8,9,10 are top level statements stored in a
a=10 #7 name called _main_ . This name is stored in a built-
b=20 #8 in python variable called _name_.
print(add(a,b)) #9 E.g: print(_name_) will print “_main_”
print(sub(a,b)) # 10

Python function types:

⮚ Built-in functions: These are always available for use. E.g: len( ), input( ) type( ) etc.
⮚ Functions defined inside modules: These functions are defined in specific modules. They can be
used only when the corresponding module is imported. E.g: sin( ) inside math module, mean( ) in
statistics module.
⮚ User defined functions: These are defined by the programmer and used.
Different ways of calling/invoking a function:
add(10,20) -> directly passing the values as arguments
add(a,b) -> passing variables as arguments
add(a,20) or add(10,b)
add(2*3-5,a**b) -> using expressions in the place of arguments. The expression is computed and the value
is passed as an argument.
Passing arguments
1. Positional arguments (Required arguments) : The arguments that are mandatory and are passed in the
given order as defined in the function header are called positional or required arguments.
def sum(a,b,c,d):
………..
………..
sum(5,10,7,8) -> all values are passed in the same order as given in the function definition.
2. Default arguments : The arguments whose default values are defined in the function header. These
arguments can be skipped during a function call. In that case, the default value is assigned for the variable.
def sum(a,b,c=10,d=5):
_________
_________
sum(5,7) -> only 2 values are passed for a and b. Parameters c and d will take the default values 10 and 5.)
sum(1,4,8,10) -> all values are passed. So parameters c and will take the values 8 and 10 respectively.
3. Keyword / Named arguments :
Generally, the order of arguments should be the same as parameters. In case we want to change the order of
passing arguments, we can pass the values by mentioning the names of the arguments.
E.g: sum(b=5,d=3,a=1,c=10) -> Here the order of passing arguments has changed. So, the name of the
argument is given while passing. These kinds of arguments are called keyword/named arguments.

RULE:
Positional/required arguments should be in the left, default arguments should be in the right side. For E.g:
def sum(a,b,c=10,d=5): -> Correct
def sum(a,b=10,c=5,d=5): -> Correct
def sum(a=10,b=5,c,d): -> Incorrect (a,b, are default. They should come in the right side. C,d are required
arguments. They should be in the left).
Returning values from functions
● Functions returning some value (Non void functions)
● Functions not returning any value (Void functions)
Example : void function without arguments
def hi( ):
print(“Hello”)
print(“Happy morning”)
print(10+20)
hi( ) -> function call

Example : void function with arguments


def hi(p,r,t):
print(“Simple Interest=”,p*r*t/100)

hi(2000,2.5,5) -> function call

Note: Both examples given above do not have return statements.


Example: Non-void function without arguments
def hi():
a=input(“Enter ur name”)
return(“Welcome”+a)
print(hi())
Example: Non-void function with arguments
def si(p,r,t):
ans=p*r*t/100
return ans
x=float(input())
y=float(input())
z=float(input())
print(si(x,y,z))
Returning multiple values:
When more than one value is returned, it is in the form of a tuple.
def swap(a,b,c):
a,b,c=c,a,b
return a,b,c
x=swap(10,20,30)
print(x) # Here x is a tuple holding(30,10,20)
NOTE:
When we try to print when no value is returned, no error will occur. None will be printed.
def hi():
print(“Hiiii”)
print(hi())
When a statement is given after „return‟, it will not get executed.
def hi( ):
Output will be A
print(“A”)
print(“B”) B
return ‘C’ will not be printed as it is given after
print(“C”) print statement.
hi( )
NOTE:
⮚ A void function returns None
⮚ We can call a function from another function and so on.
⮚ Non-void functions are also called Fruitful functions.
⮚ Void functions are called non-fruitful functions.

SCOPE OF VARIABLES
The part() of a program within which a name(variable) is accessible / recognised is called its scope.
Global scope: A name declared in the top level segment (_main_) of a program will have global scope. It
can be used in the whole program, inside all blocks, inside all functions.
Variables declared outside all functions are called global variables. We can even declare them before
all the function definitions.
Local scope: A variable declared or used within a function is said to have local scope. They can be used
only within this function. They can not be referred outside the function.
Global and local variable can have the same name as they are saved as separate variables.
LEGB Rule:
The scope of a variable is considered by following LEGB rule.
Enclosing Global
Local scope
Built-in
scope scope scope
Example: (Nested function)
num1=100
def outer( ):
num1=10
def inner( ):
num2=20
print(num1)
print(num2)
inner( )
outer( )
print(num1)
Example:
Here a1, b1 are global variables.
a1=10
b1=20 a and b are local variables in diff( )
def sum( ): function.
print(a1+b1)
def diff( ):
print(a+b)
sum( )
diff(100,200)

Example: Storage of Variables with different scope

def sum(a,b):
print(a+b)
def diff(a,b):
print(a-b)
a=10
b=20
sum(5,3)
diff(100,10)

Example: Storage of Variables with different scope

def sum(a,b,c):
s=a+b+c
return s
def average(x,y,z):
ans=sum(x,y,z)
return ans/3
a1=10
a2=20
a3=30
q=average(a1,a2,a3)
print(q)
Name Resolution (Resolving scope of a variable):
For every name reference in a program, python follows LEGB rule. First, python checks the local
namespace for the value. If it is not found, it searches for the variable in the enclosing namespace. If it is not
found, it searches in the global environment. If it is not found there, it searches in the built-in environment.
If it is not found there too, Python reports an error -> “Variable not defined”

Other examples:
E.g 1: Variable in Global scope but not in local scope.
def sum(x,y):
print(x+y)
print(num1)
num1=10
num2=20
sum(10,20) Output:
E.g 2: Same variable in local as well as global scope. 25
def hi( ): 15
x=15 25
print(x) # Refers to local variable x
x=25
print(x) # Refers to global x
hi( )
print(x) # Refers to global x

E.g 3: Global variable used in local scope


def hi( ):
global x Output:
x=15 # global variable x value changes to 15 25
print(x) 15
x=25
print(x) 15
hi( )
print(x)

E.g 4: Mutable type value passed to a function


def fn(mylist) :
mylist.append(3) #Changes made in mylist will also reflect in list1 as list is mutable.
return #To avoid this, follow the code given in E.g: 5
list1=[1,2]
print(list1) # will print [1,2]
fn(list1)
print(list1) # will print [1,2,3]

E.g 5:
def fn(mylist):
new=[1,2]
mylist=new
mylist.append(3)
return
list1=[1,2]
fn(list1)
print(list1) # list1 will print [1,2]
FILE HANDLING
A file is a sequence of bytes on the disk/permanent storage where a group of related data is stored. File is
created for permanent storage of data. Those data are to be retrieved later on. File handling in Python
enables us to create, update, read, and delete the files stored on the file system through our python program
In Python, File Handling consists of following three steps:
⮚ Open the file.
⮚ Process file i.e perform read or write operation.
⮚ Close the file
Types of Files:
There are two types of files:
1) Text Files - A file whose contents can be viewed using a text editor is called a text file. A text file is
simply a sequence of ASCII or Unicode characters. Python programs, contents written in text editors are
some of the example of text files. The end of line (EOL) character in a text file is „\n‟.
Text files are of 2 types:
⮚ Regular Text files – The text files which store the text in the same typed format. These files have an
extension „.txt‟
⮚ Delimited Text files – In these types of files, a specific character is stored to separate the values like
a comma or a tab. Tab separated values in a file are called as TSV files. Comma separated values in a
file are called CSV files.
2) Binary Files - A binary file stores the data in the form of a stream of bytes. A binary file has no delimiter.
They are NOT in human readable form. We can‟t read a binary file using a text editor. Binary files have
different extensions like „.bin‟,‟.dat‟ etc.

DIFFERENCE BETWEEN TEXT FILES / BINARY FILES

TEXT FILES BINARY FILES

Stores information as normal ASCII characters, Stores information in binary form(0s and 1s). Not in
human readable form. human readable form.

Stores only plain text Can store text, image, audio, video etc.

saved with extension “.txt” or “.csv” saved with extension “.dat” or “.bin”

Each line is terminated by the End Of Line (EOL) No delimiter is needed


character (\n)

Opening a file:
Before any reading or writing operation of any file, it must be opened first of all. Python provides the built
in function open() for it. On calling this, a file object is created for file operations.

(Method 1) Syntax:
file_object = open(<filename>,<access mode>)
where file_name = name of the file ,enclosed in double quotes. access_mode= Determines the what kind of
operations can be performed with file,like read,write etc.
For example: file1=open(“c:\\temp\\file1.txt”,”r”)
When the path is given, the slashes are doubled to suppress Escape sequence for slash.
However, you can prefix „r‟ in the front to mention that no special meaning to be considered for slash.
Example: file1=open(r“c:\temp\file1.txt”,”r”)
Note: If the file name is given without any path, python will create/search in the current working directory.
(Method 2) Syntax:
with open(<filename>,<access mode>) as file_object
For example:
with open (“c:\\temp\\file1.txt”,”r”) as file1:
Statement 1
Statement 2
………….
Note: All the lines of code should be indented as a block. The file will be automatically closed when the
code gets over. No need to used close( ) function.

File object/ File Handle: File objects are used to read or write data to a file on disk. Whenever a read /
write operation is executed, it is done from the position where the file handle exists.

File Access mode: When Python opens a file, it needs to know in which mode, the file is being opened.
The file Access modes are:
Text File Binary Description Notes
Mode File Mode
„r‟ „rb‟ Read only Default mode:
● We can ONLY read data
● Raises an error if the file does not exist
● Cursor is placed at the beginning of the file.
„w‟ „wb‟ Write only o We can ONLY write data.
o If the file does not exit, a new file is created.
o If it exists, the data will be erased/truncated/over
written
o Cursor is placed at the beginning of the file.
„a‟ „ab‟ Append o File is in APPEND ONLY mode.
o If the file does not exist, a new file is created.
o If it exists, the data will be retained and new data will
be added/appended to the end
o Cursor is placed at the end of the file.

„r+‟ „rb+‟,‟r+b‟ Read and write o Raises an error if the file does not exist
o Both reading and writing operations can take place.
o Cursor is placed at the beginning of the file.
„w+‟ „wb‟,‟w+b‟ Write and read o If the file does not exist, a new file is created.
o If it exists, the data will be erased.
o Both reading and writing can take place.
o Cursor is placed in the beginning of the file.
„a+‟ „ab+‟,‟a+b‟ Write and read o If the file does not exist, a new file is created.
o If the file exists, the existing data is retained, new data
is appended at the end.
o We can read, write and append in the file.
o Cursor is placed at the end of the file.
Closing files: An open file is closed by close( ) method.
Syntax: f.close() where f is the file object.

Common File object attributes: Consider the file object as f1,


f1.closed: It returns true if the file is closed and false when the file is open.
f1.encoding: Encoding used for byte string conversion.
f1.mode: Returns file opening mode
f1.name: Returns the name of the file which the file object holds.
f1.newlines: Returns “\r”, “\n”, “\r\n”, None or a tuple containing all the newline types seen.

Functions used in file handling:


Consider “f1” as the file object in the following examples.
Method Syntax Description
read( ) f1.read(n) Used to read from a text file. (in the form of a
E.g: string) n refers to the number of bytes to read. It
S=f1.read( ) or S=f1.read(n) is optional.
Here S will be of string datatype. f1.read(5) will read 5 bytes from the file.
Again f1.read(5) will read the next 5 bytes.
f1.read() will read the entire file as a string.
readline( ) f1.readline(n) It will read a line of text from a text file. (in the
E.g: form of a string)
S=f1.readline( ) or f.readline(n) f1.readline( ) will read a complete line.
here S is a string f1.readline(10) -> if n is given, it will read only n
number of characters from the current position of
the file handle.
readlines( ) f1.readlines(n) Reads all lines from a text file (in the form of a
E.g: list of strings)
S=f.readlines( ) or f.readlines(n) Where each list element will be one line from the
Here S will be a list. file.
write( ) f1.write(str1) Str1 value will be written on to the text file. The
content should be a string. If Str1 is a number or
other data types, it will cause an error.
writelines( ) f1.writelines(list1) list1 should be a list having each line as a list
element.
Contents will be written line by line onto the text
file.

dump( ) pickle.dump(data,filehandle) Pickle module should be imported to use this.


E.g: Used to write data onto a binary file.The data
pickle.dump(list1,file1) written may be any valid datatype of python.
load( ) obj=pickle.load(filehandle) Pickle module should be imported to use this.
E.g: rec=pickle.load(file1) Used to read data from a binary file.
reader( ) robj=csv.reader(filehandle,delimiter=‟#‟) csv module should be imported to use this
comma is the default delimiter.(optional) method.
reader object is needed to read data onto a csv
file.
writer( ) wobj=csv.writer(filehandle.delimiter=‟#‟) csv module should be imported to use this
comma is the default delimiter. It is method. writer object is needed to use
optional. writerow(s) function, to write data onto a csv file.
writerow( ) writerobject.writerow(data) Writes one row of data onto the writer object of a
E.g: wobj.writerow(list1) csv file.
where list1 is a single row of data
writerows( ) writerobject.writerows(data) Writes multiple rows of data onto the writer
E.g: wobj.writerows(list1) object of a csv file.
where list1 is a nested list of records
tell( ) filobject.tell( ) This function returns the current position of the
E.g: pos=file1.tell( ) file pointer in a file that is open.
seek( ) fileobj.seek(offset [,reference mode]) This function places the file pointer at the
where offset is the number of bytes, specified position in a file that is open.
reference mode is a number specifying
the beginning(0), current(1) or end of
file(2).
E.g: f1.seek(30) – place the cursor at 30th
byte from the beginning

f1.seek(30,1) – place the cursor at 30th


byte from the current file position
f1.seek(-10,2) – places the cursor at the
10the byte (backward direction) from the
end of the file.
flush( ) file1.flush( ) The changes made in a file is stored in the file
buffer and not reflected in the file. It is done only
when the file is closed. We can use the flush()
method to clear the buffer and write the contents
from buffer to the file. This is how programmers
can forcefully write to the file as and when
required.

THE PICKLE MODULE

Pickling or Serialisation is the process of converting Python object hierarchy into a byte-stream.
Unpickling or deserialization is the process of converting the byte-stream into an object.
Pickle module contains the load( ) and dump( ) methods to pickle or unpickle data.

Absolute and relative path:


Current
working
folder

file.txt

Absolute path:
The absolute paths are from the topmost level of the directory structure. Absolute path is the path of a file
from the root. The path is like: “Drive:\folder\subfolder\filename.extension”
Example: The absolute path of hij.py is “E:\Accounts\hij.py”
The absolute path of first.txt is “E:\Sales\East\first.txt”
Relative path:
If the current working folder is East, if we want to refer another file in the same folder, we should give the
relative path name as “.\ first.txt”
Crrrent folder is referred using “ .\ ” (single dot)

Parent folder is referred using “ ..\” (double dot)


If we want to refer to a file inside the parent folder of East, i.e, Sales, the filename should be given as
“..\ try.txt”. If we want to refer to a file inside the subfolder of the parent folder, refer as “..\West\file.txt”
If you want to open xy.py inside Accounts folder, we must give f=open(r"..\..\Accounts\xy.py")

FILE HANDLING PROGRAMS


Text file handling
→ To access a text file line by line:
Sample programs: Read a text file and print the lines starting with “T”, Read a text file line by line and write
the lines starting with “A” to a new text file,Read a text file and find out how many empty lines are there
etc.,
STEPS: Open a file handle in “r” mode
Use readlines( ) to read the file
Use a for loop to read the list content line by line.
Check the first letter / empty line
Print the line or write the line onto a new file
Close the file
→ To access a text file word by word:
Sample programs: Read a file and count the number of words, no. of words beginning with “S”, no. of
words with more than 6 letters, write them in another text file/ print them on the screen
STEPS: Open a file handle in “r” mode
Read the text file using read( ) onto a variable
Split the variable
Use a for loop and access word by word
Close the file
→ To access specific number of line:
Sample program: Read the first 5 lines of a file and write in another file
Steps: Open the file handle, read the file using readline( ) using a for loop and print / write onto another file.
Type 1: To read a file and check character by character, count or print it:
f= open(“poem.txt”,‟r‟)
s=f.read()
for ch in s:
“””Write the code to check or count”””
f.close()

Condition to be checked Program line to count To print


Count the number of vowels if ch in „aeiouAEIUO‟: if ch in „aeiouAEIUO‟:
cnt+=1 print(ch)
print(cnt)

Count the number of uppercase if ch.isupper(): To print upper to lower:


cnt+=1 if ch.isupper():
print(ch.lower())

Count the lowercase characters if ch.islower(): To Print lowercase letters:


cnt+=1 If ch.islower():
print(ch)
Count the number of the given
alphabet E.g: „a‟ if ch==‟a‟:
cnt+=1

Input an alphabet and count its


occurrence al=input(”Enter an alphabet to
count”)
if ch==al:
cnt+=1
Count the number of digits
if ch.isdigit():
cnt+=1

Count the number of spaces


if ch==‟ „:
cnt+=1

Count the number of alphabets


if ch.isalpha():
cnt+=1

Type 2: To read a file character by character and write it in another file based on a condition.
NOTE: Open two file handles, one file for reading and another file for writing+reading

f1=open('poem.txt','r')
f2=open('newpoem.txt','w+')
s=f1.read()
for ch in s:
if ch.islower(): -> This condition should be changed according to the question
f2.write(ch)
f2.flush()
f2.seek(0)
print(f2.read())

Type 3: To read a file and check word by word, count, print it

f=open(“poem.txt”,‟r‟)
s=f.read()
list1=s.split()
for ele in list11:
if <condition>:
<statements>

Type 4: To read a file line by line:


f=open(“poem.txt”,‟r‟)
line= „ ‟
while line:
line=f.readline()
<condition>

Type 5: Create a file and write in the file.


To input line by line and write it
f=open(“file1.txt”,‟w+‟)
while True:
s=input(“Enter a line of text: “)
f.write(s+‟\n‟)
if input(“Press q to quit”)==‟q‟:
break
f.seek(0)
print(“Contents of the new file”)
print(f.read())

To input all lines and write it in one go (Using write function)


f=open(“file1.txt”,‟w+‟)
s=””
while True:
s=input(“Enter a line of text: “)
s=s+‟\n‟
if input(“Press q to quit”)==‟q‟:
break
f.write(s)
f.seek(0)
print(“Contents of the new file”)
print(f.read())

To input all lines and write it in one go (Using writelines function)


f=open(“file1.txt”,‟w+‟)
list1=[]
while True:
s=input(“Enter a line of text: “)
list1.append(s+‟\n‟)
if input(“Press q to quit”)==‟q‟:
break
f.writelines(s)
f.seek(0)
print(“Contents of the new file”)
print(f.read())

NOTE: When you know the number of lines to be written, you can use for loop instead of while and the
quit statement. For example: To write 5 lines,
for I in range(5):
s=input(“Enter a line of text: “)
s=s+‟\n‟

Binary file Handling


Binary files: A binary file stores information as a stream of bytes. We can use Files with extensions „.dat‟
and „.bin‟ for binary files. They are not in human readable form.
Serialization / Pickling is the process of converting a Python object hierarchy into a stream of bytes so that
it can be written into a file.
Deserialization / Unpickling is a process whereby a byte-stream is converted back into an object hierarchy.
File opening modes:
The file opening modes mean the same like in a text file, except a letter ‟b‟ is to be added viz.,
„rb‟,‟rb+‟,‟w‟,‟wb+‟,‟a‟,‟ab+‟
MODULE: The pickle module has to be imported to work with binary files.
FUNCTIONS:
load( ) – used to read the contents from a binary file
NOTE: The load( ) function throws an exception when there are no records to be read. So, load( ) should be
inside a try statement to handle EOFError.
dump( ) – used to write the contents onto a binary file
PROGRAMS:
1. Write student information in the form of a list onto a binary file „bin1.dat‟.
import pickle
f1=open(“bin1.dat”,‟w+)
l1=[101,‟Anu‟,98] # To write in the form of a dictionary use l1={„no‟:101,‟name‟:‟Anu‟,‟mark‟:98}
l2=[105,‟Paari‟,68]
l3=[111,‟Shyam‟,85]
pickle.dump(l1,f1)
pickle.dump(l2,f1)
pickle.dump(l3,f1)
f1.close()
2. A. WAP to input/get student data (Name, mark1, mark2, mark3) from the user and write onto a
binary file “binary1.dat”
import pickle
f1=open(“binary1.dat”,‟w‟)
n=int(input(“How many students?”))
for x in range(n):
name=input(“Enter the name”) #Line1
m1=int(input(“Enter mark1”)) #Line2
m2=int(input(“Enter mark2”)) #Line3
m3=int(input(“Enter mark3”)) #Line4
list1=[name,m1,m2,m3] #Line5
pickle.dump(list1,f1) #Line6
f1.close()

2.B.To input the data till the user wishes to continue and write it onto a binary file:
import pickle
f1=open(“binary1.dat”,‟w‟)
ch==‟y‟
while ch==‟y‟:
name=input(“Enter the name”)
m1=int(input(“Enter mark1”))
m2=int(input(“Enter mark2”))
m3=int(input(“Enter mark3”))
list1=[name,m1,m2,m3]
ch=input(“Press y to continue”)
pickle.dump(list1,f1)
f1.close()

3. To write a dictionary for Prg 2 A/B: Change Line1 to Line 6 as follows


stu={}
name=input(“Enter the name”)
m1=int(input(“Enter mark1”))
m2=int(input(“Enter mark2”))
m3=int(input(“Enter mark3”))
stu={„name‟:name,‟m1‟:m1, ‟m2‟:m2, ‟m3‟:m3 }
pickle.dump(stu,f1)

3. WAP to read student information from a binary file:


import pickle
f=open("bin1.dat",'wb+')
print(“Student Records”)
try:
while True:
print(pickle.load(f))

except EOFError:
f.close()

4. WAP to read student information from a binary file with mark1 more than 80:
import pickle
f=open("bin1.dat",'wb+')
print(“Student Records”)
stu=[]
try:
while True:
s=pickle.load(f)
if s[0]>80: #Condition line
print(s) #Print Line

except EOFError:
f.close()

NOTE: The condition line has to be changes according to the search condition given in the question.
For all subjects more than 70, the condition line should be -> if s[0]>70 and s[1]>70 and s2[70]
For any one subject more than 90, the condition line should be -> if s[0]>90 and s[1]>90 or s2>90]
For searching students whose name start with „S‟, the cond. Line should be -> if s[0].startswith(„S‟):

5. WAP to search for specific records and write it in another binary file:

NOTE: Same as Prg 4 , except:


● 2 files should be open(1 in read mode, 1 in write mode)
● the #Print line has to changed as pickle.dump(s,f2)

import pickle
f1=open("bin1.dat",'rb')
f2=open("newbin.dat",'wb')
print(“Student Records”)
stu=[]
try:
while True:
s=pickle.load(f1)
if s[0]>80: #Condition line
print(s)
pickle.dump(s,f2)

except EOFError:
print(“Records written in a new file successfully”)
f1.close()
f2.close()

Steps to write in a binary file:


1. import pickle, open file handle
2. Open for loop for n number of records or while loop for unknown number of records
3. Input the values like rollno, name, mark etc.
4. Combine the values onto a list or dictionary
5. Dump the list/dictionary to the binary file
6. close the file handle

Steps to read from a binary file:


1. import pickle, open file handle
2. Open try block and “while True:” inside the try block
3. Load the records to a list l or dictionary d
4. print the list l or d (If the read action is based on a condition, check the condition and then print the
record)
5. close the file handle

Steps to copy records from a binary file to a new binary file


1. import pickle
2. open to file handles, one to read, one to write.
3. Open try block and “while True:” inside the try block
4. Load the records to a list l or dictionary d
5. Check for the condition to write and then dump the record to the new file
6. Close both file handles in the except block

Steps to update a binary file – Method 1


1. import pickle
2. open file handle in „wb+‟ mode
3. Inside try block, store the position of file handle and then load the record.
4. Update the record into a new list (sometimes based on a condition)
5. seek to the previous stored position
6. dump the new list
7. close the file in the except block

Steps to update a binary file – Method 2


1. import pickle, import os
2. Open 2 file handles, one to read and one to write
3. Open try block and “while True:” inside the try block
4. Load the records to a list l
5. Update the records and save to a new list.
6. Dump the new list to the new file.
7. Close both files in except block.
8. Remove the old file
9. Rename the new file with old file

CSV file handling


CSV stands for Comma Separated Values. CSV is just like a text file , in a human readable format which is
extensively used to store tabular data , in a spreadsheet or database. The separator character of CSV file is
called a delimiter , Default delimiter is Comma(,) , other delimiters are tab(\t), colon(:), pipe(|) and
semicolon(;) characters
CSV module provides two types of objects:
*reader - to read from the csv files
* writer - to write onto a csv file

Writing in a csv file:


Syntax of writer, writerow / writerows( ):
csv.writer( )- Returns a writer object which writes data into csv file
<writerobject>.writerow() – writes one row of data on to the file
<writerobject>.writerows( ) – write mutiple rows on to the file

1. import csv module import csv


2. Open the csv file in write mode f=open(„student.csv‟, „w‟,newline=“ ”)
3. Declare a writer object fw=csv.writer(f)
4. Input the details of the student for i in range(5):
5. Write the details onto a list sno=int(input(“Enter roll no”))
sn=input(“Enter name”)
m=input(“Enter mark”)
st_data=[sno,sn,m]
6. Use writerow and write it to the csv file fw.writerow(st_data)
7. Close the file f.close( )
Using writerows( ) method:

Keep adding the students‟ data onto a nested list. Now, use the writerows( ) method outside the loop and
write it to the csv file.
Reading from a csv file:
1. import csv module
2. Open the csv file in read mode f=open(“student.csv”,”r”,newline=“ ”)
3. Declare a reader object fr=csv.reader(f)
4. Print the reader object using a for loop for i in fr:
5. Close the file print(fr)
f.close( )
In case of a different delimiter, it has to be mentioned while declaring the reader / writer object as follows:
fr=csv.reader(f,delimiter=”@”) or fw=csv.writer(f,delimiter=”#”)

To write, read and display the contents of a csv file with a different delimiter.:
import csv
stu = []
def write_csv_data():
with open('InputData.csv','w',newline='') as F:
W = csv.writer(F,delimiter='#')
ch = 'y'
while ch.lower() == 'y':
roll=int(input('Enter the roll number'))
name = input('Enter the student name:')
totalmarks = int(input('Total marks:'))
stu = [roll,name,totalmarks]
W.writerow(stu)
ch = input('Do you want to continue y/n: ')
def read_csv_data():
with open('InputData.csv','r') as F:
R = csv.reader(F,delimiter='#')
print(„Student details‟)
for Data in R:
print(Data[0],Data[1],Data[2])
write_csv_data()
read_csv_data()

DATA STRUCTURES - STACKS


Q.1 What do you mean by Data Structure?
Ans: Data Structure means organization of data. A data structure has well defined operations or behavior
like searching, sorting, traversal etc..

Q2. How is Data Structure different from Data Type?


Data Structure provides information regarding organization of data where as Data Type provides
information regarding the domain of values and operations that can be perform on data

Q3. Define - Stack, Queue, Tree.


Stack – A stack is a linear list also known as LIFO list with the special property that items can be added or
removed from only one end called the top.
Queue – A queue is a linear list also known as FIFO list with the special property that items can be added
added at one end and removed from the other.
Tree – A non-linear hierarchical organization of data as nodes and links between them where the topmost
node called root and bottom most nodes called leaves.

Q4. Name some operations commonly performed on data structures?


Ans: Traversal, Insertion, Deletion, Searching, Sorting, Merging etc.

Q5. What is traversing? Write python code to traverse a stack/list.


Ans: Traversing means accessing or visiting or processing each element of any data structure. #List traversal
L=[10,20,30,40,50]
for x in L :
print(x)

Q6. What is data structure and why do we need it?


Ans: Data structure is a particular way of storing and organizing information in a computer so that it can be
retrieved and used most productively. Different kinds of data structures are meant for different kinds of
applications, and some are highly specialized to specific tasks.

Q7.what is a stack ? What basic operations can be performed on them?


Ans: A stack is a collection of objects that supports fast last-in, first-out (LIFO) semantics for inserts and
deletes.
Basic operation are:
a) Push – insertion of element
b) Pop – deletion of an element
c) Peek- viewing topmost element without removing
d) Display- view all the element

Q8. Name any one linear data structure in python. Ans . List
Q9. Python list are ______________ in Nature (static/dynamic)
Q10. “Lists are dynamic in nature” What do you mean by this statement?
Ans. This means that list can be grown or shrink in size means elements can be deleted or added in list.
Q11. Name the end where we add or remove element in stack.Ans. Top

Q12.What is the full form of LIFO? Last In First Out

Q13. Give two example of stack from daily life.


Ans. A pile of book, a stack of carrom coins etc.

Q14. Name two operations performed in stack. Ans. Push and Pop

Q15. What is the order of inserting elements in the following stack?

Ans. Order is: A, B, C, D


Q16. Insertion into stack is called ______ (push/pop)

Q17. Reversing a number or a word/string is an example of ______(stack)

Q18. In stack addition or removal of elements takes place at ___ (one/both) end of the list.

Q19. If the elements “A”, “B”, “C” are added in the Stackin the following order, first A then B and in last C.
In what order, it will come out of queue? Ans. C, B ,A

Q20._________ function is used to add an element in stack. Ans. Push/ append()

Q21. What happens when we try to push an element in a full stack?


Answer : If the stack is full and does not contain enough space to accept an entity to be pushed, the stack is
then considered to be in an overflow state.

Q22. Write the applications of a stack.


Ans: Reverse of a line
Evaluation of a postfix expression
Conversion of infix to postfix expression
Delimiter checking

STACK PROGRAMS
1. Consider a dictionary which contains names and marks as key value pairs of 6 students. Write a
program, with separate user defined functions to perform the following operations:
● Push the keys (name of the student) of the dictionary into a stack, where the corresponding value (marks)
is greater than 75.
● Pop and display the content of the stack.

Source code
d={"Ron":76,"Jai":45,"Bob":89,"Ali":65,"Anu":90,"Tom":82}
def push(stack,k):
stack.append(k)
def pop(stack):
if stack!=[]:
return stack.pop()
else:
return None
stack=[ ]
for k in d:
if d[k]>=75:
push(stack,k)
while True:
if stack!=[]:
print(pop(stack),end=" ")
else:
break

2:Consider a list which stores 10 numbers .Write a program with separate user defined functions to perform
the following operations based on this list.
● Traverse the content of the list and push the numbers into a stack which are divisible by 5.
● Pop and display the content of the stack.
Source code
N=[2,5,10,13,20,23,45,56,60,78]
def push(stack,k):
stack.append(k)
def pop(stack):
if stack!=[]:
return stack.pop()
else:
return None
stack=[ ]
for k in N:
if k%5==0:
push(stack,k)
while True:
if stack!=[]:
print(pop(stack),end=" ")
else:
break

3. Write a function push(student) and pop(student) to add a new student name and remove a student
name from a list student, considering them to act as PUSH and POP operations of stack Data
Structure in Python.

st=[ ]
def push(st):
sn=input("Enter name of student")
st.append(sn)
def pop(st):
if(st==[]):
print("Stack is empty")
else:
print("Deleted student name :",st.pop())

4. Write a menu based program to add, delete and display the record of hostel using list as stack data
structure in python. Record of hostel contains the fields : Hostel number, Total Students and Total
Rooms
host=[ ]
ch='y'
def push(host):
hn=int(input("Enter hostel number"))
ts=int(input("Enter Total students"))
tr=int(input("Enter total rooms"))
temp=[hn,ts,tr]
host.append(temp)
def pop(host):
if(host==[]):
print("No Record")
else:
print("Deleted Record is :",host.pop())
def display(host):
l=len(host)
print("Hostel Number \tTotal Students\tTotal Rooms")
for i in range(l-1,-1,-1):
print(host[i][0],"\t\t",host[i][1],"\t\t",host[i][2])

while(ch=='y' or ch=='Y'):
print("1. Add Record\n")
print("2. Delete Record\n")
print("3. Display Record\n")
print("4. Exit")
op=int(input("Enter the Choice"))
if(op==1):
push(host)
elif(op==2):
pop(host)
elif(op==3):
display(host)
elif(op==4):
break
ch=input("Do you want to enter more(Y/N)")

5. Write add(bookname) and delete() method in python to add bookname and remove
bookname considering them to act as push() and pop() operations in stack.

MyStack=[]
def add(bname):
MyStack.append(bname)
def delete(MyStack):
if len(MyStack) > 0:
MyStack.pop()
else:
print("Stack is empty. There is no book name")

Q7. Write addclient(clientname) and remove() methods in python to add new client and
delete existing client from a list "clientdetail", considering them to act as push and pop
operations of the stack.

clientdetail=[]
def addclient(cn):
clientdetail.append(cn)
def remove():
if len(clientdetail)>0:
clientdetail.pop()
else:
print("Stack is empty")

Q8. Julie has created a dictionary containing names and marks as key value pairs of 6 students.
Write a program, with separate user defined functions to perform the following operations:
● Push the keys (name of the student) of the dictionary into a stack, where the corresponding value
(marks) is greater than 75.
● Pop and display the content of the stack.
For example: If the sample content of the dictionary is as follows:
R={"OM":76, "JAI":45, "BOB":89, "ALI":65, "ANU":90, "TOM":82}
The output from the program should be: TOM ANU BOB OM

R={"OM":76, "JAI":45, "BOB":89, "ALI":65, "ANU":90, "TOM":82}


def PUSH(S,N):
S.append(N)

def POP(S):
if S!=[ ]:
return S.pop()
else:
return None
ST=[ ]
for k in R:
if R[k]>=75:
PUSH(ST,k)
while True:
if ST!=[]:
print(POP(ST),end=" ")
else:
break

Q9. Alam has a list containing 10 integers. You need to help him create a program with separate user
defined functions to perform the following operations based on this list.
● Traverse the content of the list and push the even numbers into a stack.
● Pop and display the content of the stack.
For Example: If the sample Content of the list is as follows:
N=[12, 13, 34, 56, 21, 79, 98, 22, 35, 38]
Sample Output of the code should be: 38 22 98 56 34 12

N=[12, 13, 34, 56, 21, 79, 98, 22, 35, 38]
def PUSH(S,N):
S.append(N)

def POP(S):
if S!=[ ]:
return S.pop()
else:
return None
ST=[ ]
for k in N:
if k%2==0:
PUSH(ST,k)
while True:
if ST!=[ ]:
print(POP(ST),end=" ")
else:
break

Q10. Write a function in python, Push(Package) and Pop(Package) to add details of employee contain
information (Empid, Ename and Salary) in the form of tuple in Package and delete a Package from a
List of Package Description, considering them to act as push and pop operations of the Stack data
structure

Package=[]
def Push(Package):
Empid=int(input(“Enter Id of Employee: "))
Ename=input(“Enter Name of employee”)
Salary= int(input(“Enter Salary of an employee”))
T=(Empid, Ename ,Salary)
Package.append(T)
def Pop(Package):
if (Package==[]):
print( "Stack empty")
else:
print ("Deleted element:",Package.pop())

DATABASE CONCEPTS
File System: Contents of a file can be texts, computer program code, comma separated values (CSV), etc.
Files stored on a computer can be accessed directly and searched for desired data. The limitations of file
system are: Difficulty in Access, Data redundancy, Data Inconsistency, Data isolation, Data dependence,
Controlled data sharing.
File system Vs Database system: File system has lot of disadvantages which can be overcome by storing
data in a database.
Database Management System: A database management system (DBMS) or database system in short, is a
software that can be used to create and manage databases. DBMS lets users to create a database, store,
manage,
update/modify and retrieve data from that database by users or application programs. Some examples of
open
source and commercial DBMS include MySQL, Oracle, PostgreSQL, SQL Server, Microsoft Access,
MongoDB. The DBMS serves as an interface between the database and end users or application programs.
Advantages of a database:
To manage large chunks of data: if size of data increases into thousands of records, it will be hard
to manage. Databases can manage large amount of data.
Accuracy: Through validation rule in database, data accuracy can be maintained.
Ease of updating data: We can flexibly update the data according to our convenience. Moreover,
multiple people can also edit data at same time.
Data Security: With databases we have security groups and privileges to restrict access.
Data integrity: In databases, we can be assured of accuracy and consistency of data due to the built
in integrity checks and access controls.
Reduced data inconsistency and redundancy: Mismatched copies of same data and duplication of
data is avoided in a database.
Disadvantages of a Database system:
Increased Complexity: Use of DBMS increases the complexity of maintaining functionalities like security,
consistency, sharing and integrity
Increased data vulnerability: As data are stored centrally, it increases the chances of loss of data due to any
failure of hardware or software. It can bring all operations to a halt for all the users.
Database: A Database is a collection of interrelated data organized and stored together. It can be easily
accessed, managed and updated. In a Database, Data is organized into rows, columns and tables. It is
indexed
to make it easier to find relevant information. It works like a container which contains the various object like
Tables, Queries, Reports etc. in an organized way.
Database Schema: Database Schema is the design of a database. It is the skeleton of the database that
represents the structure (table names and their fields/columns), the type of data each column can hold,
constraints on the data to be stored (if any), and the relationships among the tables. Database schema is also
called the visual or logical architecture as it tells us how the data are organised in a database.
Relational data model: In relational model, tables are called relations that store data for different columns.
Each table can have multiple columns where each column name should be unique. Relations in a database
are not independent tables, but are associated with each other. For example, relation ATTENDANCE has
attribute RollNumber which links it with corresponding student record in relation STUDENT.
Important properties of a relation:
❖ Each attribute in a relation has a unique name. Sequence of attributes in a relation is immaterial.
❖ Each tuple in a relation is distinct. Sequence of tuples in a relation is immaterial.
❖ All data values in an attribute must be from the same domain (same data type).
❖ Each data value associated with an attribute must be atomic.
❖ No attribute can have many data values in one tuple. A special value “NULL” is used to represent
values that are unknown
Common terminologies used in Relational data model:
i) ATTRIBUTE/FIELD: Characteristics or parameters for which data are to be stored in a relation. Simply
stated, the columns of a relation are the attributes which are also referred as fields. For example, GUID,
GName, GPhone and GAddress are attributes of relation GUARDIAN.
ii) TUPLE/ENTITY/RECORD: Each row of data in a relation (table) is called a tuple. In a table with n
columns, a tuple is a relationship between the n related values.
iii) DOMAIN: It is a set of values from which an attribute can take a value in each row. Usually, a data type
is used to specify domain for an attribute. For example, in STUDENT relation, the attribute RollNumber
takes integer values and hence its domain is a set of integer values. Similarly, the set of character strings
constitutes the domain of the attribute SName.
iv) DEGREE: The number of attributes in a relation is called the Degree of the relation. For example,
relation GUARDIAN with four attributes is a relation of degree 4.
v) CARDINALITY: The number of tuples in a relation is called the Cardinality of the relation. For
example,
the cardinality of relation GUARDIAN is 5 as there are 5 tuples in the table.
Types of keys in DBMS

❖ Primary Key – A primary is a column or set of columns in a table that uniquely identifies tuples
(rows) in that table. ❖ Candidate Key - A relation/table can have one or more attributes that takes
distinct values. Any of these attributes can be used to uniquely identify the tuples in the relation.
Such attributes are called candidate keys as each of them are candidates for the primary key.

❖ Alternate Key – Out of all candidate keys, only one gets selected as primary key, remaining keys
are known as alternate or secondary keys.

❖ Foreign Key – Foreign keys are the columns of a table that points to the primary key of another table.
The values of foreign key field are derived from the primary key of another table. They act as a cross-
reference between tables.

❖ Composite Primary key - If no single attribute in a relation is able to uniquely distinguish the tuples,
then more than one attribute are taken together as the primary key. Such a primary key consisting of more
than one attribute is called Composite Primary key. In the relation ATTENDANCE, Roll Number cannot be
used as the primary key as roll number of same student will appear in another row for a different date.
Query: A query is a request to a database for information retrieval and data manipulation (insertion, deletion
or update). It is written in Structured Query Language (SQL)
Referential Integrity: Referential Integrity is the set of rules that ensures that relationships between
records are valid so that users cannot accidentally delete or change data. When referential integrity is
enforced, we cannot enter a value in a foreign key which is not present in the primary key. A record in a
primary key cannot be edited or deleted if it has related records in the foreign key table.
View: A view is a virtual table that does not really exist on its own but is derived from one or
more underlying base tables.
DDL commands: The Data Definition Language commands allow us to perform tasks related to data
definition. We can perform tasks like:

⮚ Create, alter, drop schema objects


⮚ Grant and revoke privileges and roles
⮚ Maintenance commands
CREATE, ALTER, DROP etc.
DML commands: Data Manipulation Language commands enable users to access or manipulate data as
organized by the data model. We can insert, delete, modify or retrieve information.
INSERT, SELECT, UPDATE, DELETE etc.

Datatypes in mysql:

❖ Numeric Data Types:


⮚ INTEGER or INT – up to 11 digit number without decimal.
⮚ SMALLINT – up to 5 digit number without decimal.
⮚ FLOAT (M,D) or DECIMAL(M,D) or NUMERIC(M,D) Stores Real numbers upto M digit length
(including .) with D decimal places. e.g. Float (10,2) can store 1234567.89
❖ Date & Time Data Types:
⮚ DATE - Stores date in YYYY-MM-DD format.
⮚ TIME - Stores time in HH:MM:SS format.
❖ String or Text Data Type:
⮚ CHAR(Size) A fixed length string up to 255 characters. (default is 1)
⮚ VARCHAR(Size) A variable length string up to 255 characters. Char, Varchar, Date and Time
values should be enclosed with single („ „) or double (“ ”) quotes in MySQL.
Data type Description
CHAR(n) Specifies character type data of length n where n could be any value from 0 to 255.
CHAR is of fixed length, means, declaring CHAR (10) implies to reserve spaces for 10
characters. If data does not have 10 characters (e.g., „city‟ has four characters), MySQL
fills the remaining 6 characters with spaces padded on the right.
VARCHAR( Specifies character type data of length where n could be any value from 0 to 65535. But
n) unlike CHAR, VARCHAR(n) is a variable-length data type. That is, declaring
VARCHAR (30) means a maximum of 30 characters can be stored but the actual
allocated bytes will depend on the length of entered string. So „city‟ in VARCHAR (30)
will occupy space needed to store 4 characters only.
INT specifies an integer value. Each INT value occupies 4 bytes of storage. The range of
unsigned values allowed in a 4 byte integer type are 0 to 4,294,967,295. For values larger
than that, we have to use BIGINT, which occupies 8 bytes
FLOAT Holds numbers with decimal points. Each FLOAT value occupies 4 bytes
DATE The DATE type is used for dates in 'YYYY-MM-DD' format. YYYY is the 4 digit year,
MM is the 2 digit month and DD is the 2 digit date. The supported range is '1000-01-01'
to '9999-12-31'.

Types of SQL Commands

⮚ DDL (Data Definition Language) To create database, table structure - commands like CREATE,
ALTER, DROP etc.
⮚ DML (Data Manipulation Language) Record/rows related operations - commands like SELECT....,
INSERT..., DELETE..., UPDATE.... etc.

DDL COMMANDS:
To CREATE Database:
CREATE DATABASE <database name>;
E.g: create database student;
To know the names of all existing databases:
SHOW DATABASES;
To start using a database:
USE <databasename>;
E.g: Use student;
To view the tables in the database:
Show tables;
To remove a database:
DROP DATABASE <databasename>;
Commonly used SQL Constraints
Constraint Description
NOT NULL Ensures that a column cannot have NULL values where NULL means missing/
unknown/not applicable value.
UNIQUE Ensures that all the values in a column are distinct/unique
DEFAULT A default value specified for the column if no value is provided
PRIMARY KEY The column which can uniquely identify each row/record in a table.
FOREIGN KEY The column which refers to value of an attribute defined as primary key in another
table
CHECK Limits the values that can be inserted into a column.

To create a new table:


CREATE TABLE tablename Example:
(attribute1 datatype constraint, create table STUDENT(
attribute2 datatype constraint, Rollno INT UNIQUE CHECK(Rollno>0),
………………. Adm_no int primary key,
……………….. SName VARCHAR(20),
attributeN datatype constraint); Sdob DATE NOT NULL,
Phone_no char(10) UNIQUE,
Team CHAR (12) default “Edison”);
To add constraints:
CREATE TABLE empdetails
(empno int PRIMARY KEY,
ename char(10) NOT NULL,
phone char(15) UNIQUE NOT NULL,
basicpay int DEFAULT 15000 NOT NULL,
age int CHECK(age>18),
dept varchar(10) REFERENCES employee(dep_id)); -> No need to use FOREIGN KEYWORD

Adding names to constraints:


CREATE TABLE empdetails
(empno int,
ename char(10) NOT NULL,
phone char(15) UNIQUE NOT NULL,
basicpay int DEFAULT 15000 NOT NULL,
age int CHECK(age>18),
dept varchar(10),
CONSTRAINT constraint1 PRIMARY KEY(empno));

To view the structure of a table:


Describe <tablename> or desc <tablename>
To delete a table:DROP TABLE <tablename>
To modify a table structure:
The SQL ALTER TABLE command is used to add, delete or modify columns in an existing table. You
should also use the ALTER TABLE command to add and drop various constraints on an existing table.

ALTER TABLE to add a New attribute/ Column in an existing table:


ALTER TABLE table_name ADD <column_name> <datatype> <constraint>;
ALTER TABLE STUDINFO ADD PINCODE INT NOT NULL;
ALTER TABLE STUDINFO ADD(fname char(30), bloodgrp char(5));
ALTER TABLE command to DROP COLUMN/ATTRIBUTE in an existing table:
ALTER TABLE table_name DROP column_name;
ALTER TABLE employee DROP bloodgrp;

ALTER TABLE command to change the DATA TYPE of a column in a table:


ALTER TABLE table_name MODIFY column_name datatype;
ALTER TABLE employee MODIFY name varchar(40);
To add a primary key constraint:
ALTER TABLE <TABLENAME> ADD PRIMARY KEY(fieldname); -> If the field already exists
ALTER TABLE <TABLENAME> ADD PRIMARY KEY(name datatype constraint); -> If the field does
not exist
To add a foreign key constraint:
ALTER TABLE EMPLOYEE ADD FOREIGN KEY(DEPT_ID) REFERENCES
DEPARTMENT(DEPT_ID);

To remove primary key from a table:


ALTER TABLE table_name DROP PRIMARY KEY;
To change a column name/attribute name:
ALTER TABLE student CHANGE ADMNO admission_no VARCHAR(20);
To remove a constraint by its name:
alter table empdetails drop constraint constraint1; -> drop the constraint named constraint1

Create table from an existing table:


CREATE TABLE <tablename> AS (Select * from student where class=7);

DML COMMANDS
To insert records into a table:
INSERT INTO <tablename> VALUES(field1, field2,field3,………..);
E.g: INSERT INTO student values(1001,„Tarun‟,‟Chidambaram‟,‟608001‟,NULL,“B+ve”);
To insert records into specific fields:
INSERT INTO STUDENT(SNO,NAME,BLOODGRP) VALUES(1001,”Anusha”,”B+ve”);
To insert records from another table:
INSERT INTO MARKS SELECT ADMNO,NAME FROM STUDENT WHERE CLASS=6;
Insert into mark(admno,name) select no,studname from personal;
To insert multiple records at the same time:
INSERT INTO STUDENT VALUES (105,'Jack',99,100),(106,'Jill',98,92),(107,'Renu',78,80);
NOTE: While inserting values, char, varchar and date should be enclosed within quotes. Date should be in
YYYY-MM-DD format.

QUERY TO RETRIEVE DATA FROM TABLES:


To display all records: SELECT * FROM <tablename>;
To display few attributes: SELECT field1, field2..fieldn FROM <TABLENAME>;
To give a heading for a displayed column/attribute: (Using Alias name)
SELECT <ATTRIBUTENAME> AS “<ALIAS NAME>” FROM <TABLENAME>;
To display unique records: SELECT DISTINCT <columnname> FROM <table>;
To display records based on a condition (USING WHERE):
We can use relational operators (<, <=, >, >=, =, <> )
select * from stud where phone=”9879876767”;
select no,name from studinfo where aadhaar IS NULL; -> (To select records without adhaar number)
select no,name from studinfo where phone IS NOT NULL; -> (To select records with a phone number)
select * from employee where salary>=10000;
select name from employee where doj<”2000-10-01” and salary<20000;
select name from stud where mark<>100; -> to select all student names who have not scored 100
select name from student where mark between 90 and 100; -> both 90 and 100 are included
select name from student where phy>=90 or chem>=90; -> to display students who have scored more than
90 in either physics or chemistry.
select empno,name from employee where salary NOT BETWEEN 10000 and 20000; -> will display
employees who DO NOT have salary between the given range.

To select only employees from sales and accounts department:


select * from employee where department IN(“Sales”,”Accounts”);
(OR)
select * from employee where department=“Sales” or department=”Accounts”;
(OR)
select * from employee where department=“Sales” || department=”Accounts”;

To select employees other than “Production” and “Sales”


select * from employee where department NOT IN(“Sales”,”Production”);
(OR)
select * from employee where department<>“Sales” and department<>”Production”;
(OR)
select * from employee where department<>“Sales” && department<>”Production”;

To perform simple expressions:


select 100*45/20;
select 25-20*10 from dual; -> dual is a dummy table in mysql to obtain calc. results with 1 row, 1
column
select 200/8 as “Result”; -> will display the answer with heading “Result”

Pattern Matching:
Patterns can be matched by two wildcard characters:
Percent(%) -> matched by any substring
Underscore( _ ) -> matched by a single character
select * from emp where dept LIKE “S_ _ _”; -> names starting with S and having 3 alphabets after.
select * from emp where name LIKE “N%H”; -> names starting with N and ending with H
select * from emp where name NOT LIKE “A%”;->chooseall employees who name DO NOT start with “A”
select * from emp where pin NOT LIKE “608_ _ _” -> choose pin starting with 608 followed by 3 chars
select * from emp where name LIKE “%E” -> matches any word with letter E
select * from emp where name LIKE “a%” or NAME LIKE “s%”-> matches any name starts with „a‟ or „s‟
select * from emp where name LIKE “_ _ _ _ _” -> matches any name exactly with 5 letters
select * from emp where name LIKE “_ _ _ _ _ _ _ %” -> matches any name with minimum 7 letters

SORTING (using ORDER BY clause)


select * from emp where name LIKE “A%” ORDER BY dateofapp; -> to sort by ascending order of
appointed date
select * from stud ORDER BY total DESC -> display students in the descending order of total marks
select * from stud ORDER BY total DESC, name -> if 2 students have same mark they‟re sorted by name

UPDATE VALUES IN A TABLE:


UPDATE employee SET NAME=”SUREKHA” WHERE rollno=23;
UPDATE employee SET mark1=99,mark2=95,mark3=80 WHERE name=”Reshma”;
UPDATE employee SET bonus=salary*10/100;
UPDATE employee SET bonus=salary*10/100 where dept=”Sales”;

DELETE RECORDS FROM A TABLE:


DELETE FROM STUDENT WHERE CLASS=5;
DELETE FROM EMPLOYEE; -> deletes all records from employee table

AGGREGATE FUNCTIONS
Aggregate functions are also called Multiple Row functions. These functions work on a set of records as a
whole and return a single value for each column of the records on which the function is applied.

Differences between Single and Multiple Row Functions


Single Row Functions Multiple Row Functions

1. It operates on a single row at a time. 1. It operates on groups of rows.


2. It returns one result per row. 2. It returns one result for a group of rows.
3. It can be used in Select, Where, and Order by 3. It can be used in the select clause only.
clause. 4. Max(), Min(), Avg(), Sum(), Count() and
4. Math, String and Date functions are examples of Count(*) are examples of multiple row functions.
single row functions.

Aggregate functions in MySql:


FUNCTIONS DESCRIPTION EXAMPLE

MAX( ) Returns the largest value from the specified mysql> SELECT MAX(Price) FROM
column. INVENTORY; Output: 673112.00

MIN( ) Returns the smallest value from the specified mysql> SELECT MIN(Price) FROM
column. INVENTORY; Output: 355205.00

AVG( ) Returns the average of the values in the mysql> SELECT AVG(Price) FROM
specified column INVENTORY; Output: 576091.625000

SUM( ) Returns the sum of the values for the mysql> SELECT SUM(Price) FROM
specified column. INVENTORY; Output: 4608733.00

COUNT(*) Returns the number of records in a table. mysql> SELECT COUNT(*) from
Note: In order to display the number of MANAGER;
records that matches a particular criteria in Output: 4
the table, we have to use COUNT(*) with
WHERE clause.

COUNT(COL Returns the number of values in the specified mysql> SELECT * from MANAGER; |
UMN) column ignoring the NULL values. Note: In MNO | MEMNAME |
this example, let us consider a MANAGER | 1 | AMIT |
table having two attributes and four records. | 2 | KAVREET |
| 3 | KAVITA |
| 4 | NULL |
SELECT COUNT(MEMNAME)
FROM MANAGER;
Output : 4

GROUPING RECORDS USING “GROUP BY” CLAUSE

At times we need to fetch a group of rows on the basis of common values in a column. This can be done
using a group by clause. It groups the rows together, having the same values in a specified column. We can
use the aggregate functions (COUNT, MAX, MIN, AVG and SUM) to work on the grouped values.
HAVING Clause in SQL is used to specify conditions on the rows with Group By clause.

a) Display the number of Cars purchased by each Customer from SALE table.
mysql> SELECT CustID, COUNT(*) "Number of Cars" FROM SALE GROUP BY CustID;

+--------+----------------+
| CustID | Number of Cars |
+--------+----------------+
| C0001 | 2 |
| C0002 | 2 |
| C0003 | 1 |
| C0004 | 1 |
+--------+----------------+

b) Display the Customer Id and number of cars purchased if the customer purchased more than 1 car from
SALE table.
mysql> SELECT CustID, COUNT(*) FROM SALE GROUP BY CustID HAVING Count(*)>3;
+--------+----------+
| CustID | COUNT(*) |
+--------+----------+
| C0001 | 4 |
| C0002 | 5 |
+--------+----------+

c) Display the number of people in each category of payment mode from the table SALE. \
mysql> SELECT PaymentMode, COUNT(PaymentMode) FROM SALE GROUP BY Paymentmode
ORDER BY Paymentmode;
+-------------------+-----------------------+
| PaymentMode | Count(PaymentMode) |
+-------------------+-----------------------+
| Bank Finance | 2 |
| Cheque | 1 |
| Credit Card | 2 |
| Online | 1 |
+-------------------+-----------------------+

d) Find the count,sum of salary for each department.


SELECT deptno,COUNT(*),SUM(salary) FROM employee GROUP BY deptno;
Output:
Deptno COUNT(*) SUM(salary)
D01 3 8750.00
D04 5 10885.00
D08 6 9400.00

e) SELECT deptno, Avg(Comm), Avg(sal) FROM employee GROUP BY Deptno HAVING


Avg(Comm)>750 AND Avg(Sal)>2000;
Output
DeptNo Avg(Comm) Avg(Sal)
D01 780 8900
D02 920 9100
D05 882 12000

JOINS
A Join is a query that combines records from two tables.
I. Cartesian product (X)/ Cross join / Unrestricted Join
Cartesian Product is denoted by X symbol. Let‟s say we have two relations R1 and R2, the cartesian product
of these two relations (R1 X R2) would combine each tuple of first relation R1 with each tuple of second
relation R2.
MySql query for cartesian product will be as follows:
SELECT * FROM table1, table2;
SELECT * FROM table1 CROSS JOIN table2;
If table1 and table2 have the following content:
Table1 Table2
Empno Name Dept Desig
101 Anu Sales Mgr
106 Renu Accts Audit Asst
Sales Accountant
Select * from table1,table2 will return (table1 -> 2 rows, table2 -> 3 rows, 3 x 2=6 rows will be returned)
Output:
Empno Name Dept Desig
101 Anu Sales Mgr
101 Anu Accts Audit Asst
101 Anu Sales Accountant
106 Renu Sales Mgr
106 Renu Accts Audit Asst
106 Renu Sales Accountant

II. Equi Join / Inner Join


This is a join in which columns are compared for equality. We use the equality operator between 2 tables
while specifying the join condition. The common columns are displayed from both the tables..
E.g: SELECT * FROM emp,dept WHERE emp.deptno=dept.deptno;

We can use alias name for tables. E.g:


SELECT * FROM emp e,dept d WHERE e.deptno=d.deptno;

III. Natural Join : A natural join is an operation that creates an implicit join clause based on the common
columns in the two tables being joined. Common columns are the columns that have the same name in both
tables, they are displayed only once in the output table.
E.g: SELECT * FROM employee NATURAL JOIN dept;

STEPS TO CREATE DATABASE CONNECTIVITY APPLICATION:


1. Import mysql.connector package as shown below:
import mysql.connector as Sqlcon
2. Open a connection to MySql database.
Mycon = Sqlcon.connect (host=”localhost”, user=”root”,passwd=”1234”,database=”employee”)
3. Create a cursor instance of the database to access the records.
Cursor=Mycon.cursor( )
4. Execute SQL Query
Cursor.execute(“Select * from employee”)
5. Extract data from the Resultset.
i) data = cursor.fetchall( ) -> returns all records retrieved through the sql query as in step 4
E.g: data = cursor.fetchall( )
ii) data = cursor.fetchone( ) -> returns one record everytime.
E.g: data = cursor.fetchone( )
iii) data = cursor.fetchmany( ) -> returns the specified number of records
E.g: data = cursor.fetchmany(4) -> returns the first 4 records from the sql statement
iv) data = cursor.rowcount -> returns the number of rows retrieved.
6. Close the connection. -> Mycon.close( )

RESULT SET
The result set refers to a logical set of records that are fetched from the database by executing an SQL query
and made available to the application program like Python. The resultset retrieved from mysql to python
retrieves the records in the form of a list of tuples, where every individual record is a tuple.
fetchone( ) - returns a tuple, fetchmany(n),fetchall( ) - always returns a list of tuples (even for a single
record)

fetchone( ) method:
<data> = <cursor>.fetchone(). It will return one record from the resultset as a tuple or a list. First time it will
return the first record, next time it will fetch the next record and so on.Everytime it retrieves one record, the
cursor will move to the next record. When there are no records it returns an empty tuple.
fetchmany(n) method:
<data> = <cursor>.fetchmany(<n>). This method accepts the number of records to fetch and returns a tuple
where each record itself is a tuple. If there are no records then it returns an empty list.
fetchall( ) method:
<data>=<cursor>.fetchall( ) - It will return all the records retrieved as per query in a tuple form. If there are
no records to be fetched, it returns an empty list.

commit( ) method:
MySQLConnection.commit() method sends a COMMIT statement to the MySQL server, committing the
current transaction i.e., making the changes permanent in the database.

execute( ) method:
execute( ) method is used with the cursor object to execute the mysql queries from a python program.

connect( ) method:
connect( ) method is in mysql.connector module which is used to establish a connection between python and
mysql.
There are 4 parameters used in connect( ). They are : host, user, passwd and database. Among these,
database is not compulsory. For Example:
Mycon = Sqlcon.connect (host=”localhost”, user=”root”,passwd=”1234”,database=”employee”)

Use of rowcount:
rowcount is the property of the cursor which will retrieve the number of records retrieved by the cursor so
far. When no records are retrieved it returns 0. Syntax: n=<cursor>/rowcount

TWO METHODS TO FORM QUERY STRINGS:


1) USE OF %s FORMAT SPECIFIER
Example:
cur.execute('select * from salary where netsalary>%s'%(45000))
cur.execute('select * from salary where netsalary>%s and salmonth="%s"'%(45000,"Apr"))
OR
q='select * from salary where netsalary>%s and salmonth="%s"'%(45000,"Apr")
cur.execute(q)

2) USE OF format( ) TO PERFORM QUERIES


In this method we use { } instead of %s , we can also mention the argument number as {0},{1] etc, but
it isnot mandatory.

CONSTRUCT QUERIES USING %s

CONSTRUCT QUERIES USING { } FORMAT


COMPUTER NETWORKS
EVOLUTION OF NETWORKING:
Network: A computer network is a set of nodes like computers and networking devices that are connected
through communication for the purpose of communication and sharing resources(hardware/software) among
the users. Advantages: • Facilitate communication through email / video conferencing / instant messaging
or any other mode. • Share hardware devices like a printer or scanner • Enable file sharing • Share software
or operating programs • Share information Disadvantages of computer network: Lack of robustness as the
entire network depends on one main server, Lack of data security and privacy, cost of network, Viruses can
spread on a network easily because of the interconnectivity.
ARPANET (Advanced Research Projects Agency NETwork): In 1969, The US govt. formed an agency
named ARPANET to connect computers at various universities and defense agencies. The main objective of
ARPANET was to develop a network that could continue to function efficiently even in the event of a
nuclear attack. The first message was communicated between the University of California, Los Angeles
(UCLA) and Stanford Research Institute (SRI). In 1974 the TCP/IP model and protocol were invented
specifically to handle because more and more networks were getting connected to ARPANET. By 1990 the
ARPANET was shut down and dismantled
NSFNET: The National Science Foundation Network was a program of coordinated, evolving projects
sponsored by the National Science Foundation (NSF) from 1985 to 1995 to promote advanced research and
education networking in the United States.
Internet (INTERconnection NETwork): The Internet is a worldwide network of computer networks. It is
not owned by anybody. The internet has evolved from ARPANET. The internet is a globally connected
network system that utilizes TCP/IP to transmit information. The ISPs provide Internet service to the end
users who want Internet connection. The following services are instantly available through internet: Email,
Web-enabled audio/video conferencing services, Online movies and gaming, Data transfer/file-sharing,
Instant messaging, Internet forums, Social networking, Online shopping, Financial services. The Internet
today is run by private companies, not the government.
Interspace: is a client/server software program that allows multiple users to communicate online with real –
time audio, video and text chat in dynamic 3D environments.
Timeline showing evolution of networking

DATA COMMUNICATION TERMINOLOGIES:


Communication: Data communication refers to the movement of encoded information from one point to
another by means of electronic transmission system. It can also be defined as the exchange of data between
two devices via some form of transmission medium which can be wired or wireless. At both the source and
destination, data are in digital form; however, during transmission, they can be in digital or analog form.
COMPONENTS OF COMMUNICATIONS:
The components in communication are: sender, receiver, message, communication media and protocol
Transmitter (Sender): The transmitter is the device that sends the message. It can be a computer,
workstation, telephone handset, video camera, and so on.
Receiver: The receiver is the device that receives the message. It can be a computer, workstation, telephone
handset, television, and so on.
Medium / Transmission media: The medium of transmission may be guided or unguided. The
transmission medium is the physical path by which a message travels from sender to receiver. It can consist
of twisted pair wire, coaxial cable, fiber-optic cable, laser or radio waves (terrestrial or satellite microwave).
Message: The message is the transmission (data) to be communicated. It can consist of text, number,
pictures, sound, or video or any combination of these.
Protocol: A protocol is a set of rules that governs data communication. It represents an agreement between
the communicating devices. Without a protocol, two devices may be connected but not communicating

Components of
communication

Bandwidth: The amount of data that can be transferred from one point to another. It is a measure of the
range of frequencies a transmitted signal occupies. In digital systems, bandwidth is the data speed in bits per
second. In analog systems, bandwidth is measured in terms of the difference between the highest-frequency
signal component and the lowest-frequency signal component. Bandwidth is expressed in Hz, KHz, and
MHz.
The hertz (symbol: Hz) is the derived unit of frequency in the International System of Units (SI) and is
defined as cycles per second.
Data transfer rate: DTR is the amount of data in digital form that is moved from one place to another in a
given time on a network. Data rates are often measured in megabits (million bits) or megabytes
(millionbytes) per second.
bps - bits per second Bps - Bytes per second
Kbps - kilobits per second KBps - Kilo bytes per second
Mbps - megabits per second MBps - Megabytes per second
Gbps - giga bits per second GBps - Giga bytes per second
Tbps - tera bits per second TBps - Tera bytes per second
IP address: IP address, also known as Internet Protocol address, is also a unique address that can be used to
uniquely identify each node in a network. The IP addresses are assigned to each node in a network that uses
the
Internet Protocol for communication. Thus, if we know a computer‟s IP address, we can communicate with
that computer from anywhere in the world. However, unlike MAC address, IP address can change if a node
is removed from one network and connected to another network.
NOTE: (Media Access Control) MAC address is assigned by the manufacturer in the NIC card.

IPV4: The initial IP Address called version 4 (IPV4 in short), is a 32 bit numeric address, written as four
numbers separated by periods, where each number is the decimal (base-10) representation for an 8-bit binary
(base-2) number and each can take any value from 0 - 255. A sample IPV4 address looks like:
192:168:0:178
IPV6: With more and more devices getting connected to the Internet, it was realised that the 32-bit IP
address will not be sufficient as it offers just under 4.3 billion unique addresses. Thus, a 128 bits IP address,
called IP version 6 (IPV6 in short) was proposed. An IPv6 address is represented by eight groups of
hexadecimal (base-16) numbers separated by colons. A sample IPV6 address looks like:
2001:CDBA:0000:0000:0000:0000:3257:9652

Switching Techniques: Switching techniques are used for transmitting data across networks. Different ways
of sending data across the network are:
Circuit Switching:
• First the complete end-to-end transmission path is established between the source and the
destination computers.
• Then the message is transmitted through the path.
• The main advantage of this technique is guaranteed delivery of the message.
• Mostly used for voice communication
Disadvantages:
● Since dedicated channels are used, the bandwidth required is more.
● The utilization of resources is not full.
● Since a dedicated channel has been used, the transmission of other data becomes impossible.
● The time taken by the two stations for the establishment of the physical link is too long.
● Circuit switching is expensive because every connection uses a dedicated path establishment.
● The link between the sender and the receiver will be maintained until and unless the user
terminates the link. This will also continue if there is no transfer of data taking place.

Packet Switching:
• Using TCP protocol a single large message is divided into a sequence of packets
• Each packet is independent and has the address of sender and destination.
• The IP (Internet protocol) does the routing for the packets. It keeps track of all the different routes
available to the destination. If one route is not available it finds the alternate route to the destination.
• At the destination, the TCP protocol re-assembles the packets into the complete message.
• If any packets are lost or damaged, a request is sent to retransmit the same message.
Disadvantages:

● Installation costs of packet switching are expensive.


● The delivery of these packets becomes easy when complicated protocols are used.
● High-quality voice calls cannot use packet switching as there is a lot of delay in this type of
communication.
● Connectivity issues may lead to loss of information and delay in the delivery of the information.
TRANSMISSION MEDIA:
Transmission media is a pathway that carries the information from sender to receiver. We use different types
of cables or waves to transmit data. Data is transmitted normally through electrical or electromagnetic
signals. These signals can be transmitted through copper wires, optical fibers, atmosphere, water and
vacuum Different Medias have different properties like bandwidth, delay, cost and ease of installation and
maintenance. Transmission media is also called Communication channel.
On the basis of transmission of data, the transmission media can be classified in to two categories:
1. Guided (Physical) transmission media
2. Unguided (Wireless) transmission media

Wired Networks – They are also known as Ethernet networks, which is most common type of LAN
technology. A wired network is simply a collection of two or more computers, printers, and other devices
linked by Ethernet cables/ any form of wired media. Ethernet is the fastest wired network protocol, with
connection speeds of 10 megabits per second (Mbps) to 100 Mbps or higher. Computer must have an
Ethernet adapter (sometimes called a network interface card, or NIC) to connect with wire. Most of the
network topology uses wired networks.

GUIDED MEDIA: The guided media refers to the different types of cables used in the network.
Twisted Pair Cable This picture includes twisted-pair cables. These cables are
twisted together in pairs of two wires wrapped together in helix form.
Types: It is available in two types:
Shielded Twisted Pair (STP) – have a braided wired mesh that encases each pair
of insulated wires.
Unshielded Twisted Pair (UTP) – comprise of wires and insulators
Uses: The twisted-pair cables are used in telephone lines, DSL lines, and LAN (Local Area Network)s. In
LANs it is also known as an ethernet cable.
Advantages Disadvantages
Reduces crosstalk Unable to provide connection over long
It is simple and cheap. distances
Easy to install and Low bandwidth
maintain Not suitable for broadband applications
It is very flexible
It has low weight
It can be connected
easily

Coaxial Cables
These types of cables are used for transmission to TV and Set-top boxes. These
cables consist of a solid wire core surrounded by one or more foil or wire shields.
Each foil or shield is separated by some kind of plastic insulator.
Uses: The coaxial cable is used in a telephone network that carries 10,000 voice
signals, digital telephone network with 600 Mbps data transfer rates, in cable TVs,
ethernet LANs and MANs.
Advantages Disadvantages
Suitable for high-speed Expensive than twisted pair cable
communication Not compatible with twisted pair cable
Better shielding than twisted-pair If any fault occurs in the cable causes the failure in the entire
cables network.
Can be used in shared cable network
Can be used for broadband
transmission
Offers bandwidth up to 400Mbps

Optical Fiber cable: It consists of thin strands of glass or glass like material.
These cables carry light from sources used from one end to another. The first
end is considered as source and second is considered as detector. The light
sources are LEDs or LDs. These type of cables use frequency modulation for
data transfer. These cables consists of three pieces:
The core – It is made up of glass or plastic that is responsible for travel of lights
The cladding – It is there to reflect the light back to the core
Protective coating – provide protection to the cable
Uses: Fiber optic cables are used in cable TV, and high speed network
transmissions.

Advantages Disadvantages
Provides high-speed data transmission with greater The installation process is not easy
bandwidth to longer distances. virtually impossible to tap
Strong and protected cables Connection losses are common
Provides secure transmission Most expensive cables
Can be used for broadband transmission
Very reliable
Thinner and lighter in weight so it can withstand more pull
pressure than copper cable.

UNGUIDED MEDIA or Wireless Communication Channel


The unguided or wireless communication channels referred to a wireless connection to the network. There is
no physical connection given through wires in this channel. The connection will be done through either
sensors, antenna or any other component.

Microwave
This type of unguided medil is used for long distance networking. It consists of the following components:
Transmitter, Receiver, Atmosphere. The microwave has a parabolic antenna mounted on towers to send a
beam to other antennas which are tens of kilometres away. As much as the tower is high, the range is
greater. With 100 meters high tower, 100 km distance range will be achieved.
Advantages Disadvantages
Cheaper than cables Insecure connection
Land is required to fix towers only, saves the space of The network can be affected by weather effects such as
land to spread the cables rains, thunderstorms etc.
It can provide easy communication over difficult Limited bandwidth
terrain Very high-cost maintenance
It can communicate over oceans

Radio Wave
It is using the radio frequency modulation for data transmission. It has two parts:
Transmitter – take data or message, encode it into sine wave and transmit into a radio wave
Receiver – decodes the data or message from sine wave it receives
In radio wave both transmitter and receiver antennas to radiate and capture the radio signal.
The advantages and disadvantages are similar as micro wave.

Satellite
It is just a relay system of the microwave. It provides voice, fax, data, video, email, file transfer, and WWW
internet applications. It can provide emergency backup facility when cable communication network crushed
by a disaster. In satellite, dish functions as an antenna and the communication equipment to transmit and
receive data.
The stationary orbits placed about 22,300 miles above the earth‟s surface. These satellites act as relay
system for the communication signals.
Advantages Disadvantages
Covers a large area Due to some technical limitations, cannot spread over large
Best alternative of cables area
It provides good option for commercial over-crowding at low antennas
use High cost
Significant probability of failure

Infrared
It uses an infrared lights send data. We use these infrared at your home in our remotes like TV, set top box,
AC, wireless speakers, automotive doors etc. It transmits data through the air and propagates within a range.
It cannot penetrate the walls. It is suitable for short distances.
Laser
It requires direct light-of-sight. It provides high speed than microwaves. It requires the use of a laser
transmitter and a photo-sensitive receiver at each end. It requires point-to-point transmission and is affected
by weather.

Bluetooth
The Bluetooth is very famous for PDAs and sharing files over PDAs like mobiles, smartphones, laptops and
palmtops. Now a day a variety of devices can be connected through Bluetooth for file sharing. These devices
can be printer, speaker, TV, and so on.

NOTE: Infrared, Laser and Microwave require Line-of-sight transmission.


NETWORK DEVICES
Computer hardware devices transfer data in a fast, secure and correct way with some specific functionality
over same or different networks. Some devices are installed on the device, like Internal modem, NIC card or
RJ45 connector, whereas some are part of the network, like router, switch, etc.

Modem – Modem is short for Modulator Demodulator. It‟s an electronic device used for conversion
between analog signals and digital bits. Modulation means digital to analog signal conversion and its vice
versa is known as demodulation. The modem at the sender‟s end acts as a modulator that converts the digital
data into analog signals. The modem at the receiver‟s end acts as a demodulator that converts the analog
signals into digital data for the destination node to understand. There are 2 types : Internal, External

Ether net card/ NIC(Network Interface Card) – This is commonly used


networking device. This is also known as network adapter card, Ethernet
Card or LAN card. It allows our PC to communicate with other PCs. A PC
uses parallel data transmission to transmit data between its internal parts
whereas the media that connects this PC with other device/PCs uses serial
data transmission. A NIC converts parallel data stream into serial data
stream and vice versa.
Ethernet card uses either a bus or star topology and supports data transfer
rated upto 10 Gbps. Ethernet can connect devices in wired LAN or WAN.
Each NIC has a MAC address, which helps in uniquely identifying the computer on the network. A MAC
address is a 6- byte address with each byte separated by a colon. First 3-bytes have Manufacturer id and last
3-bytes represent Card id. For example in an MAC address 10:BE:05:56:3F:CB

RJ-45 or Registered Jack-45 is an eight-pin connector that is used exclusively with


Ethernet cables for networking.It is a standard networking interface that can be seen at
the end of all network cables. Basically, it is a small plastic plug that fits into RJ-45
jacks of the Ethernet cards present in various Computing devices.

Repeater – A repeater is an analog device that works with signals on the cables to which it is connected. In
a network, data is carried in the form of signals. These signals can travel a specified distance (usually about
100 m). Signals lose their strength beyond this limit and become weak. In such conditions, original signals
need to be regenerated. The weakened signal appearing on the cable is regenerated and put back on the cable
by a repeater. Repeater is a networking device which regenerates the signal and forwards these signal with
more power.

HUB – HUB is used to connect multiple computers in a single LAN


network of one workgroup. Generally HUBs are available with
4,8,12,24,48 ports. When a hub receives a signal on its port, it
repeats the signal and forwards that signal from all ports except the
port on which the signal arrived. The limitation of Hub is that if data
from two devices come at the same time, they will collide. There are
two types of HUB Passive HUB:- It only forwards the signal on all
ports without amplifying the signal. Active HUB:- It forwards the
signal with improvement in the quality of data signal by amplifying it.
SWITCH –Switch is a smart hub used to connect multiple computers together in a LAN. Switches are
available with 4,8,12,24,48,64 ports. Switch makes their switching decisions by using application specific
integrated circuits (ASICs).Due to switching decision capability, switch sends signal to recipient only and
that‟s why switches are called as intelligent hub.

HUB SWITCH
Hub passes the frame to every port Passes the frame to a specific port because it keeps a
record of MAC address.
Creates lot of traffic on network Less traffic Creates lot of traffic on network Less traffic
Hub shares its bandwidth with each and every Switch allocates full bandwidth to each of its port. So
port, so bandwidth divided among all the nodes, user always access maximum amount of bandwidth.
which will degrade performance.
Slow speed Fast speed
A hub does not filter signals A switch does not forward the signals which are noisy
or corrupted.

ROUTER – A router is a network device that can receive the data, analyse it
and transmit it to other networks. A router connects a LAN to the internet.
Compared to a hub or a switch, a router has advanced capabilities as it can
analyse the data being carried over a network, decide/alter how it is packaged
and send it to another network of a different type. For example, data is
divided into packets. If the size is big, the data is repackaged as smaller
packets and then sent over the network by a router. A router can be wired or
wireless. A wireless router can provide Wi-Fi access to smartphones and
other devices. A wired router contains ports to provide wired Internet access.

GATEWAY – It is a networking device capable to convert protocols so that two different network
architecture based system can communicate with
each other. Gateway serves as the entry and exit
point of a network, as all data coming in or going
out of a network must first pass through the gateway
in order to use routing paths. It will pass the data
packet using the best possible route. A gateway can
be implemented in software, hardware, or a
combination of both. Because a network gateway is
placed at the edge of a network, the firewall is
usually integrated with it.

Wi-Fi cards – They are small and portable cards that allow your computer to connect to the internet through
a wireless network. Wi-Fi transmission is through the radio waves. These signals are picked up by Wi-Fi
receivers such as computers and cell phones equipped with Wi-Fi cards. The devices need to be within the
range of a Wi-Fi network to receive the signals and produces a wireless internet connection. Once a
connection is established between user and the network, the user is prompted with a login screen and
password for establishing is a secure connection. Wi-Fi cards can be external or internal. If a Wi-Fi card is
not installed inside your computer, you may purchase an external USB antenna attachment and connect it to
your device. Many computers and mobile devices are equipped with wireless networking capability and do
not require a Wi-Fi card.

Switch Vs. Router - In the OSI model, router is working on a higher level of network layer (Layer 3) than
switch. Router is very different from the switch because it is for routing packet to other networks. It is also
more intelligent and sophisticated to serve as an intermediate destination to connect multiple area networks
together. A switch is only used for wired network, yet a router can also link with the wireless network. With
much more functions, a router definitely costs higher than a switch.
Router Vs Gateway - Gateway regulates traffic between two dissimilar networks, while router regulates
traffic between similar networks. A router is a hardware device that forwards data packets between computer
networks. Routers perform the traffic directing functions on the Internet.

NETWORK TOPOLOGY
The geometrical arrangement of computer resources, network devices along with communication channel is
known as Network structure or Network topology.

Bus Topology – In bus topology, each communicating


device connects to a transmission medium, known as bus.
Data sent from a node are passed on to the bus and hence
are transmitted to the length of the bus in both directions.
That means, data can be received by any of the nodes
connected to the bus. A single backbone wire called bus is
shared among the nodes, which makes it cheaper and easier
to maintain. Both ring and bus topologies are considered to
be less secure and less reliable.
Advantages of a Bus topology Disadvantages of a Bus topology
• Difficult reconnection
• Easy to install • Difficult to find the problem
• Minimal Cable • Difficult to add new devices
• Break stops all transmission of data

Star Topology : In star topology, each communicating device is connected


to a central node, which is a networking device like a hub or a switch. Star
topology is considered very effective, efficient and fast as each device is
directly connected with the central device. Although disturbance in one
device will not affect the rest of the network, any failure in a central
networking device may lead to the failure of complete network. The star
topology uses a separate cable for each node/workstation.
Advantages of a Star topology Disadvantages of a Star topology
• Less expensive than mesh • Everything depends on the hub
• Easy to install, easy to configure
• If one link fails the network can
still function

Ring Topology: In ring topology, each node is connected to two other


devices, one each on either side. The nodes connected with each other thus
forms a ring. The link in a ring topology is unidirectional. Thus, data can be
transmitted in one direction only (clockwise or counterclockwise).
Advantages of a Ring topology Disadvantages of a Ring topology
• Easy to install • Easy to reconfigure • When there is a break the whole system is dead
• Easy to detect a problem

Tree Topology In which a central root node (the top level of the hierarchy) is connected to one or more
other nodes that are one level lower in the hierarchy. In this type of network, data transmitted from source
reaches the centralised device and then passes through every branch to reach its destination.
Advantages Disadvantages
● New node can be added easily. ● If the backbone line breaks, the entire segment goes
down.
● Signal can travel for long distance.
● More difficult to configure
● Isolate and prioritize communication.
● Higher cabling cost
TYPES OF NETWORK
1. Personal Area Network (PAN) – communication between two-three mobile devices or PC for personal
purpose.
2. Local Area Network (LAN) – limited area (within building)
3. Metropolitan Area Network (MAN) – within city
4. Wide Area Network (WAN) – within multiple city/state/ countries

1. Personal Area Network(PAN) – Spread in the proximity of an


individual. Cover an area of a few meters radius (around 10 m). Set up
using guided media(USB cable) or unguided media (Bluetooth, Infrared).
Owned, controlled, and managed by a single person. Examples: A network
of devices such as computer, Phone, MP3/MP4 Player, Camera etc.
Transferring songs from one cell phone to another is a PAN of two phones.
Transferring files from a PC to an MP3 player is a PAN between the two.

2. Local Area Network (LAN) – LANs are the most


frequently used/discussed networks. It is one of the most
common one of the simplest types of network. It is
designed for small physical areas such as an office, group
of buildings. Any of different types of topologies can be
used to design LAN like Star, Ring, Bus, Tree etc. These
types of networks can be from 1km upto 10 km. Data
transfer in LAN is quite high, and usually varies from 10
Mbps to 1000 Mbps.
Characteristics of LAN • private networks means no
need of regulatory control. • Operate at relatively high
speed. • Connects computers in a single building, block or
campus.
Advantages of LAN • Resource Sharing • Software
Applications Sharing • Easy and Cheap Communication • Centralized Data • Data Security • Internet
Sharing
Disadvantages of LAN • High Setup Cost • Privacy Violations • Data Security Threat • LAN Maintenance
Job • Covers Limited Area

3. Metropolitan Area Network(MAN):– Spread within a city .


Covers an area of a few kilometres to a few hundred kilometres
radius. Set up using all types of guided and unguided media.
Owned and operated by a government body or a large
corporation. Examples: A network of schools, or banks, or
Government offices etc. within a city. A MAN is usually
formed by interconnecting a number of LANs and individual
computers. Data transfer rate in MAN is less compared to
LAN. This kind of network can be extended
up to 30-40 km.

4. Wide Area Network (WAN) – Wide Area Network connects computers and other LANs and MANs,
which are spread across different geographical locations of a country or in different countries or continents.
Large business, educational and government organisations connect their different branches in different
locations across the world through WAN. The Internet
is the largest WAN that connects billions of computers,
smartphones and millions of LANs from different
continents.
Characteristics of WAN • Covers large distances
(states, countries, continents). • Communication
medium like satellite, public telephone networks etc and
routers are used to establish connections. Examples: A
network of ATMs, BANKs, National Government
Offices, International Organizations' Offices etc., spread
over a country, continent, or covering many continents.
Advantages of WAN • Long distance business can connect on the one network. • Shares software and
resources • Messages can be sent very quickly to wide range of nodes • Hardware devices can be shared.
Disadvantages of WAN • Need a good firewall to restrict unauthorized access • Setting up a network can be
an expensive, slow and complicated. • Maintaining a network is a full-time job • Security is a major issue
when many different people have the ability to use information

NETWORK PROTOCOL
HTTP: Hyper Text Transfer Protocol is the set of rules for transferring hypertext (text, graphic, image,
sound, video etc) on the WWW. Communication between client computers and web servers is done by
sending HTTP Requests and receiving HTTP Responses. It is an object oriented protocol. It is used since
1990. It runs over TCP.

FTP: File Transfer Protocol (FTP) is the protocol used for transferring files from one machine to another. It
works on a client-server model. It is an effective way to get a geographically dispersed group to work on a
project. It encourages indirect or implicit use of remote computers. It helps to transfer files efficiently.

PPP: Point to Point Protocol (PPP) is a communication protocol which establishes a dedicated and direct
connection between two communicating devices. This protocol defines how two devices will authenticate
each other and establish a direct link between them to exchange data. It is best solution for Dial-up internet
connections. It consists of:
IPCP (IP Control Protocol) – for transportation over PPP link
NCP (Network Control Protocol) – for traffic transportation
LCP (Link Control Protocol) – for link establixhment

SMTP: Simple Mail Transfer Protocol is used when we send emails to other email users (recipients). This
protocol is used to deliver the mail to the recipient‟s mail server. They can be used only to send emails but
cannot receive them. It operates with the MTA (Mail Transfer Agent) to deliver the mail to the correct
device & email inbox.

TCP/IP: Trransmission Control Protocol/ Internet Protocol is a protocol that controls online communication
between computers. TCP enables applications to establish channels of communication via a network. It also
allows a text to be split into various packets before they can be transmitted over the network and then
arranged correctly at the destination network. So, it ensures the reliable transfer of information across the
network. Besides, it also tests errors in the packets and demands for re-transmission if any errors are found.
TCP / IP model is divided into 4 layers.
1) The application layer contains all the protocols needed to communicate with the end-users
2) The transport layer guarantees the delivery of the right information in the right sequence.
3) The Network access layer that constructs and manages the data packets.
4) The Internet layer delivers the packet to its destination.
The Internet Protocol identifies the unique IP address of a device. The 2 types of IP are:
1) IPv4 (32-bits or 4-bytes) : IPv4 addresses are canonically represented in dot- decimal notation, which
consists of four decimal numbers, each ranging from 0 to 255, separated by dots, e.g., 192.168.1.1.
2) IPv6 (128-bits or 16-bytes) An IPv6 address is represented by eight groups of hexadecimal (base-16)
numbers separated by colons. A sample IPV6 address looks like:
2001:CDBA:0000:0000:0000:0000:3257:9652

POP3: Post Office Protocol 3, or POP3, is the most commonly used protocol for receiving email over the
internet. This standard protocol, which most email servers and their clients support, is used to receive emails
from a remote server and send to a local client. It is a one-way client-server protocol to receive email and
hold it in the email server. It is a "store-and-forward" service. It offers a means of downloading email from a
server to the client so the recipient can view the email offline.

HTTPS: The Full Form of HTTPS is Hyper Text Transfer Protocol Secure. HTTPS is a secure HTTP
encrypted using the Secure Sockets Layer or Transport Layer Security (SSL/TLS) convention. It enables
protected communication over the network. If the website is installed with an SSL certificate, then the
website can be considered secure, and users feel safe to pass crucial data such as credit cards, debit cards,
OTP, and so on through it.

TELNET: Telnet is an older Internet TCP/IP protocol that lets you log on to a remote computer system.
Using telnet client software on your computer, you can make a connection to a telnet server (i.e., the remote
host).

VoIP: Voice over Internet Protocol enables voice communication over Internet through compression of
voice into data packets, efficiently transmitted over the network and converted back to voice at the other
end. This protocol is used for instant messaging (chat) and video conferencing over the net. Using VoIP,
you can make phone calls over the internet to landlines, mobile phones and even computer-to-computer
anywhere in the world where an internet connection is available.

INTRODUCTION TO WEB SERVICES


World Wide Web: The World Wide Web (WWW) is an ocean of information, stored in the form of trillions
of interlinked web pages and web resources. The resources on the web can be shared or accessed through the
Internet. One of the features of WWW are: Hyperlinks: Hyperlinks allow users to navigate between different
web pages and resources on the internet by clicking on a link. Sir Tim Berners-Lee invented the
revolutionary World Wide Web in 1990 by defining three fundamental technologies that lead to creation of
web: HTML, URL, HTTP

HTML:
● HTML stands for Hyper Text Markup Language
● HTML is used for creating web pages, describe the structure and design of Web pages using markup
● HTML elements are represented by tags
● The language tells the browser to render the content of the page
● HTML pages are made interactive using hyperlinks
XML:
● XML stands for EXtensible Markup Language
● XML is a markup language for structured information
● XML is used to define tags and the structural relationships between them
● XML was designed to be self-descriptive
● XML is a W3C Recommendation
HTML XML
● HyperText Markup Language. ● eXtensible Markup Language.
● Designed to display data with focus on ● XML was designed to be a software and hardware
how independent tool used to transport and store data,
data looks. with focus on what data is.
● HTML is case insensitive. ● XML is case sensitive.
● HTML is used for designing a web-page to ● XML is used basically to transport data between
be
● the application and the database.
● rendered on the client side.
● Uses custom tags defined by the user.
● HTML has its own predefined tags.
● XML preserves white space.
● HTML does not preserve white space.
● XML is about carrying information hence
● HTML is about displaying data, hence dynamic.
static.

DOMAIN NAME: Domain names are used to identify one or more IP addresses. Domain names are used in
URLs to identify a particular web page. Each website is stored in a web server. It is difficult to remember
their IP addresses. So, we can use the domain name. For example, http://www.kvongcbrd.com/english-
results.htm
The URL is - http://www.kvongcbrd.com/english-results.htm
Domain Name - kvongcbrd.com
Web Page : english-results.htm
Protocol : http
Every domain name has a suffix that indicates which top level domain (TLD) it belongs to.
There are only a limited number of such domains. For example:
.gov - Government agencies
.edu - Educational institutions
.org - Organizations (nonprofit)
.com - commercial business
.net - Network organizations
. in - India
Because the Internet is based on IP addresses, not domain names, every Web server require
a Domain Name System (DNS) server to translate domain names into IP addresses.

URL – Uniform Resource Locator. It is a unique address or path for each resource located on the web. It is
also known as Uniform Resource Identifier (URI). Every page on the web has a unique URL. Examples are:
https://www.mhrd.gov.in,http:// www.ncert.nic.in,http://www.airindia.in, etc.
URL is sometimes also called web address. However, a URL is not only the domain name. It contains other
information that completes a web address, as depicted below:

DNS Server: A DNS server maintains a database of domain names and their corresponding IP addresses.
When we enter a URL on a web browser, the HTTP protocol approaches a computer server called DNS
server to obtain the IP address corresponding to that domain name. After getting the IP address, the HTTP
protocol retrieves the information and loads it in our browser.

WEBSITE: Website is a collection of web pages which are interlinked to one another. These pages are
hypertext pages and link between pages is known as hyperlink. It is a location on a net server. Each website
has a unique address called URL. For example: http://www.microsoft.com

WEB BROWSER: It is the application software though which user can access internet. It is a client that
navigates through the WWW and displays web pages. For example: internet explorer, Google chrome,
Mozilla Firefox, Opera.
WEB SERVER: A Web Server is a Server over the WWW that responds to the requests made by web
browsers. It uses HTTP to serve files from web pages to the users. The request from the clients are
addressed by the web server.

WEB HOSTING:
Web hosting is a service that allows organizations and individuals to post a website on to the Internet.
A web host, or web hosting service provider, is a business that provides the technologies and services
needed for the website or webpage to be viewed in the Internet.
Web hosts allow their customers to store web pages on the servers. Web hosting can be :
1) free of cost 2) shared or virtual hosting – Our website domain is hosted on the web server of the
hosting company 3) Dedicated hosting – renting an entire web server from a hosting company
4) Co-location hosting – server is used by the company and other physical needs by the hosting company

TIPS FOR CASE BASED QUESTIONS:


1. Name the most suitable wing/block where the server should be installed:
Tip: Select the block/wing with the max. number of computers.
2. Suggest the best/suitable cable layout
Tip: Draw star topology with the Server block placed in the center. (OR) connect the buildings having the
shortest distance. So, N buildings will require N-1 wires. NOTE: No loops or Ring topology. You have to
draw the LAYOUT
3. Suggest the placement of the following Devices:
(a) Hub/Switch: Should be placed in all buildings/office/wings to connect all the computers.
(b) Repeaters: In between the building/office/wing where distance is more than 100 metres to
regenerate/amplify signals.
(c) Modem(Internet connecting device): Should be installed in the office where the server is installed.
(d) Firewall (both hardware/software): A network security device to provide security / to prevent
unauthorized access / to secure data / to prevent cyberattack / to prevent malicious software in a
network

4. Which communication medium/Communication technology is used for connecting offices/blocks/wings?


(i) Compromise with cost, not with speed – keywords (High speed / effective / best)
* Cable connection(Guided): Optical fibre
* Wireless connection (UnGuided): Satellite (for out of city/state/country)
(ii) Compromise with speed, not with cost – keywords (Economic / low cost/ cheap )
* Cable connection(Guided): Twisted pair / co-axial (Broadband)
* Wireless connection (UnGuided): Radio wave / Microwave
NOTE: Best wired medium is Optical fibre, Best wireless medium is Satellite
Moderate wireless connection is Microwave / Radiowave. (If area is hilly, Radiowave is preferred)
For Low cost connection: Dial-up connection is suggested. For fast connection - Broad band connection is
suggested.
Given a choice of Ethernet cable or Co-axial cable, best one is Ethernet cable.
5. Device used for connecting computers to a network:
Tip: Switch / Hub (Best answer). In choose the correct answer if switch/hub is not given, you can choose
Router / Modem
6. Which of the following device is used to connect two systems, especially if the system use different
protocols?
Ans: Gateway
7. Use of protocols:
Ans: Connect a system to a network / communicate – TCP/IP
Used for emails – SMTP and POP3
Used by web to display content – HTTP
To display content over the web in a secured way – HTTPS
To connect a remote system/device – Telnet
To share/transfer files over a network – FTP
Turns/translates domain names to IP addresses – DNS
Automatically assigns an IP address - DHCP
☺☺☺☺☺☺☺☺☺☺☺☺☺

You might also like