Class 12 NOTES FOR BOARD EXAM 2023-24
Class 12 NOTES FOR BOARD EXAM 2023-24
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.
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.
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))
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
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:
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.
Exception Handling
– Exception handling is the process of dealing with run-time errors. It involves using `try…except` blocks to
catch and handle exceptions.
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.
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”
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]
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.
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:
⮚ 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}
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.
Defining a function(syntax):
def <function name> (parameters1, 2,….) :
<Statement 1>
<Statement 2>
…
…
<Statement n>
return <variable/value/expression>
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
⮚ 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
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)
def sum(a,b):
print(a+b)
def diff(a,b):
print(a-b)
a=10
b=20
sum(5,3)
diff(100,10)
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 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.
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”
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.
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.
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)
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())
f=open(“poem.txt”,‟r‟)
s=f.read()
list1=s.split()
for ele in list11:
if <condition>:
<statements>
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‟
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()
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:
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()
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()
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
Q14. Name two operations performed in stack. Ans. Push and Pop
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
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
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:
Datatypes in mysql:
⮚ 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.
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.
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
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.
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
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 |
+-------------------+-----------------------+
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
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;
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
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:
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.
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.
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
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 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.
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
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.
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