0% found this document useful (0 votes)
17 views70 pages

Python Programming Basics and Concepts

The document provides comprehensive notes on Python programming, covering tokens, operators, string methods, lists, tuples, sets, dictionaries, control statements, loops, and functions. It includes examples of common operations and code snippets for various tasks such as conditionals, loops, and list comprehensions. Additionally, it explains mutable vs immutable types and provides insights into built-in functions and data structures.

Uploaded by

bibhutirath615
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)
17 views70 pages

Python Programming Basics and Concepts

The document provides comprehensive notes on Python programming, covering tokens, operators, string methods, lists, tuples, sets, dictionaries, control statements, loops, and functions. It includes examples of common operations and code snippets for various tasks such as conditionals, loops, and list comprehensions. Additionally, it explains mutable vs immutable types and provides insights into built-in functions and data structures.

Uploaded by

bibhutirath615
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

Python Notes

Tokens (Lexical Unit)- The smallest individual unit of a program.


Few tokens are-
• Keywords- pre-defined special words. E.g. for, del, class, str
• Identifiers- User defined words or names. E.g. Functions, variables etc.
• Literals-data types having fixed values. E.g. Str, Boolean, numeric, None etc.
• Operators-triggers some action when applied to a variable or object. E.g. Unary (+, -, not) and Binary
(arithmetic, relational (greater small), logical (or, and, not), bitwise (are used to change individual bits
in an operand-binary and, or, xor), assignment, shift, membership (it tests membership in a sequence),
identity (compare the memory locations)
• Punctuators- symbols used to organize programming sentences. E.g. ‘ “ {} [] ().

Arithmetic- %-------gives remainder after dividing. //-------- gives quotient. **------Exponent.


Relational------ <,>, ==, etc.
Assignment- =, +=, -=, /=.
Membership------in , not in.
Operators Precedence- all execute left to right but exponential executes right to left.
Based on PEARL and Logical Not>and>OR.

What is PEARL? It is sequences of executions.


P- Parenthesis () Exponential Arithmetic Relational Logical.

Commonly Used String Methods:


Case Conversion:
• lower(): Returns a copy of the string with all characters converted to lowercase.
• upper(): Returns a copy of the string with all characters converted to uppercase.
• capitalize(): Returns a copy of the string with the first character capitalized and the rest
lowercase.
• title(): Returns a copy of the string in title case, where the first letter of each word is capitalized.
• swapcase(): Returns a copy of the string with uppercase characters converted to lowercase and
vice versa.
Whitespace and Character Manipulation:
• strip(): Returns a copy of the string with leading and trailing whitespace removed.
• lstrip(): Removes leading whitespace.
• rstrip(): Removes trailing whitespace.
• replace(old, new): Returns a copy of the string with all occurrences of old replaced by new
Searching and Finding:
• find(substring): Returns the lowest index in the string where substring is found, or -1 if not found.
• startswith(prefix): Checks if the string starts with the given prefix.
• endswith(suffix): Checks if the string ends with the given suffix.
Splitting and Joining:
• split(separator): Splits the string into a list of substrings based on the separator. If no separator is
provided, it splits on whitespace.
Content Checking:
• isalnum(): Returns True if all characters in the string are alphanumeric (letters or numbers).
• isalpha(): Returns True if all characters in the string are alphabetic (letters).
• isdigit(): Returns True if all characters in the string are digits.
• islower(): Returns True if all cased characters in the string are lowercase.
• isupper(): Returns True if all cased characters in the string are uppercase.
• isspace(): Returns True if all characters in the string are whitespace characters.
Built-in Functions that operate on strings:
• len(string): Returns the length (number of characters) of the string.
• str(object): Returns the string representation of an object.

List- it contains mixed datatypes.


e.g- L= [3,5,0.5,” nitin”, 5+5j, True]
List’s function-
Append---------------- [Link](data) --------------add data in the end
Extend------------------ [Link](data) ---------------- add data after iterating.
Insert------------------- [Link](index, data) -------------- add data at particular index.
Pop--------------------- [Link](index) ------- remove data from -1 index(default)
Remove--------------- [Link](data) ------- delete data which come first.
e.g – l[2].remove(data)
reverse --------------- [Link]() ------- permanent reverse data.
e.g – using slicing we can do also l[::-1]
sort-------------------- [Link]() or [Link](reverse=True) ------ sort data ascending.
[Link](data) --------- tells index number
Count----------- [Link](data) ------------frequency of element.
append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the first item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list


Mutable/ Immutable- When you can access index number to change element in the memory is termed
as mutable object and not, immutable.
E,g- List is mut… and str is immutable
Code- s=”nitin”
[Link](‘n’, ‘m’) ------------------------------ mitin ( is it showing mutability--- No-----it is reassigning data, data
remains same)
Tuples- Almost kind of list but it is immutable.
E.g t=(3, 4, 5+4j, ‘nitin’, 0.5) All things like Slicing/ Indexing can be done
but mutable things can’t done.
Functions- Count and Index.

SET------{Immutable collection of unique data} Note- Blank is dict


No slicing and indexing applicable here.
Functions-
• [Link](data)
• [Link](data)
Dict- {key : value} Key should be unique.
Note- No special case in key.

Functions-
• D[key] for indexing.
• D[key]=value For adding new key value in dict.
• Del d[key] for deleting key and value in dict we use del function.
• [Link]() for getting keys
• [Link]() for values
• [Link]() for all i.e. k & v.
• [Link](key) remove key with value. (key must be given)

Conditional/Control Statements
IF-elif Statement- Used for multiple conditions.
Code Number One- marks=int(input(‘enter your marks’))
If marks >= 80 :
Print(‘you will be a part of A section’)
elif marks>=60 and marks<80:
print(‘you will be a part of B section’)
elif marks>=40 and marks<60:
print(‘you will be a part of C section’)
else :
print(‘you will be a part of D section’)

Code Number Two- price =int(input(‘enter the price’)) IF-Else Statement


If price> 1000:
Print(‘I will not purchase’)
Else:
Print(‘I will purchase’)

Code-a=int(input('enter the value of first angle '))


b=int(input('enter the value of second angle '))
c=int(input('enter the value of third angle '))
sum=a+b+c
print(sum)
if sum>180 or sum<180:
print('triangle is not possible')
else:
print('triangle is possible')

Code Number Three- price =int(input(‘enter the price’)) Nested-IF-Else Statement


If price> 1000:
Print(‘I will not purchase’)
If price>5000:
Print(‘this is too much’)
Elif price<2000:
Print(‘it okay price’)
Else:
Print(‘I will purchase’)

Loop
Example- There is a list x=[1,2,3,3,4,7,5,6,9] add 1 to all the elements in the list to get the output
y=[2,3,4,4,5,8,6,7,10].
For Loop-
For i in x:
Print(i) all elements gets separated.
Again new code-
For i in x:
Print(i+1) it adds one to all elements.
Output-
Y=[]
For i in x:
Print(i+1)
[Link](i+1)
y desired output.

Question-2- There is a list l=['nitin', 'sharma', 'bhangel', 'jeetram colony']. Make all the element in upper case
in new list y[].
Code-
l=['nitin', 'sharma', 'bhangel', 'jeetram colony']
y=[]
for i in l:
[Link]([Link]())
print(y)
1,2,4,6,7,2.5,’nitin’, ‘sharma’]. Task- separate the elements in two different list i.e. one contains numeric and
another contains string.

Code-
a=[]
b=[]
l=[10,'nitin', 'sharma',1,4,6,2.5,9]
for i in l:
if type(i)==int or type(i)==float:
[Link]
Question 3 – There is a list l=[end(i)
else:
[Link](i)
print(a,b)

"""Finding square and square root of numbers in the list"""


import math
l=[1,2,3,4,5,6,7,8,9,10]
for i in l:
print(i**2, [Link](i))

For- Else Loop- Else will execute when for loop executed successfully.
l=[1,2,3,4,5,6,7,8,9,10]
for i in l:
print(i**2)
else:
print("i have done sir")

""" Break condition- Used to break the loop at certain condition"""


l=['nitin', 'sharma', 'tyagi', 'naik']
for i in l:
if i=="tyagi":
break
print(i)
""" For-Else-Break condition"""
l=['nitin', 'sharma', 'tyagi', 'naik']
for i in l:
if i=="tyagi":
break
print(i)
else:
print('executes the program')
Ouput- nitin, Sharma (why ?- for loop gets terminated)

""" Continue condition""" Continue the program except for the condition.
l=['nitin', 'sharma', 'tyagi', 'naik']
for i in l:
if i=="tyagi":
continue
print(i)
""" For-Else-continue condition"""
l=['nitin', 'sharma', 'tyagi', 'naik']
for i in l:
if i=="tyagi":
continue
print(i)
else:
print('executes the program')

"""Range Function-it is generating function used to generate data excluding last"""


Code 1 l=list(range(11))
print(l) o/p- [1,2,3,4,5,6,7,8,9,10]
code 2 l=list(range(0,21,2))
print(l)
a=list(range(-10, 0))
print(a)
"""For loop using Range functions"""
l=['nitin', 'sharma', 'tyagi', 'naik']
for i in range(len(l)):
print(l[i])
"""For loop using Range functions-To reverse data"""
l=['nitin', 'sharma', 'tyagi', 'naik']
for i in range(len(l)-1,-1,-1):
print(l[i])
"""For loop using Range functions-To get data on even number"""
l=[23,4,34,56,32,5,67,234,567,899,55678,990]
list(range(0,len(l),2))
for i in range(0,len(l),2):
print(l[i])
"""For loop using Range functions-To get sum of all data"""
l=[23,4,34,56,32,5,67,234,567,899,55678,990]
sum(l)
#OR
result = 0
for i in l:
result=result+i
print(result)

"""Extracting values from dictionary using for loop"""


d={"name":'nitin','class':'12th','cover':'syllabus'}
print([Link]())
for i in [Link]():
print(d[i])
"""Extracting items from dictionary using for loop"""
d={"name":'nitin','class':'12th','cover':'syllabus'}
for i in [Link]():
print(i)
Question- How to print Fibonacci series –
n=int(input('Enter your limit '))
a,b=0,1
for i in range(n):
print(a)
c=a+b
a=b
b=c
While Loop- runs till conditions.
Example- a=1
while a<=10:
print(a)
a=a+1
Result- 1,2,3,4,5,6,7,8,9,10.
Question One-Find the sum of n numbers.
n=int(input('Enter your limit '))
starting_point=0
counter=1
while counter<=n:
starting_point=starting_point+counter
counter=counter+1
print(starting_point)
Question 2- Find factorials of a given number.
n=int(input('Enter your limit '))
f=1
while n>0:
f=f*n
n=n-1
print(f)
Question 3- How to print Fibonacci series –
n=int(input('Enter your limit '))
a,b=0,1
counter=0
while counter<n:
print(a)
c=a+b
a=b
b=c
counter=counter+1

Question 4- Reversing any name backward-


l=input('enter the word ')
r=""
lenth=len(l)
while lenth>0:
r=r+l[lenth-1]
lenth=lenth-1
print(r)

Question 5- code to print tables-


n=int(input('enter the number '))
i=1
while i<=10:
result=n*i
print(n,'*', i, '=', result)
i=i+1
Question 6- Prime numbers
n=int(input("enter your number"))
enter your number15
>>> c=0
>>> i=1
>>> while i<=n:
... if n%i==0:
... c=c+1
... i=i+1
... if c==2:
... print("It is a prime number")
... else:
... print("not a prime number")
...
not a prime number
Question 7- Palindrome number
n=int(input("enter your number"))
enter your number626
r=0
z=n
while n>0:
... r=(r*10)+n%10
... n=n//10
... if r==z:
... print("palindrome")
... else:
... print("not")
Q8-Ouput based
n=245
>>> z=0
>>> while n>0:
... z=z+n%10
... n=n//10
... print(z)
Q9-Bubble Sorting-
l=[12,21,23,32,34,43,56,76,87,78]
>>> n=len(l)
>>> for i in range(n-1):
... for j in range (n-i-1):
... if l[j] > l[j+1]:
... l[j], l[j+1]=l[j+1], l[j]
... print(l)
...
[12, 21, 23, 32, 34, 43, 56, 76, 78, 87]
comprehension-Short hand code writing
Q1- Write a code to write square of number in a list.
l=[2,6,12,43,15]
print([i**2 for i in l])
Q2- Write a code to separate even of number from a list.
l=[2,6,12,43,15]
print([i for i in l if i%2 ==0])
Q3- Write a code to change case of string in a list.
l=['nitin', 'name', 'sharma', 'python']
print([[Link]() for i in l])
Q4-Square of values in a dictionary-
d={"k1":1,'k2':8,'k3':98}
print({k:v**2 for k,v in [Link]()})
Q4-Filtering of values greater than 2 in a dictionary-
d={"k1":1,'k2':8,'k3':98}
print({k:v for k,v in [Link]() if v>2})
#Creating a Function-
What is Function?
• Function is named set of code written to carry out a specific task.
• It can be used repeatedly at different places within a program.
• We can define as many functions as desired in program.
Advantages of function
• Increases Code reusability
• Reduces program complexity
• Increases readability of programs
• Reduces chances of errors in program
• Eases program updating.
Types of function
• Built in function
• Functions in module
• User defined function

User defined function


• The items enclosed in “[ ]” are called parameters and they are optional.
• Function may or may not return a value.
• Function header always ends with a colon (:).
• Function name should be unique. Rules for naming identifiers also apply for function naming.
• The statements outside the function indentation are not considered as part of the function.
Syntax:
def <functionname> ([parameters]):
statements
—-,,——–
return <value>
example:
create a user defined function to display a line like “——————–“ (20 dashes)
Create a user defined function ‘area’ to calculate and display area of rectangle.

Arguments and Parameters


• An argument is a value passed to the function during the function call which is received in
corresponding parameter defined in function header.
• The no of arguments in calling and called function should be same.
Example
Write a function to find factorial of a number, where number is passed as an argument.

Write a function to calculate average of five numbers stored in a list.


Default parameter
• Python allows assigning a default value to the parameter. A default value is a value that is pre-decided
and assigned to the parameter when the function call does not have its corresponding argument.
• The default parameter must be trailing parameters in the function header.

Example:
Write a function power to find x to the power y. if y is not inputted square of x should be calculated.
Function returning a value
• A function may return a value when called.
• Python uses ‘return’ keyword to return the value(s) from the function.
Example:
Write a function to find and return largest among ten numbers stored in a list.

Built in function
Functions in Modules
Python offers many built in modules. Some of most commonly used modules are listed below:
• Math module
• Random module
• Statistics module

How to use module


to import specific functions of given module ‘from’ statement can be used as given below

Flow of execution
Scope of variable
• Scope of variable refers to accessibility scope of a variable within a program or part of a program.
• A variable can have either local or global scope.
Local variable
• A variable that is defined inside any function or block is called local variable.
• It can be accessed only in the function or a block where it is defined.
• It exists only till the function executes.
Global variable
• A variable that is defined outside any function or any block is known as a global variable.
• It can be accessed in any function defined onwards.
• Any change made to global variable is permanent and affect all the functions where it is used.
• if you want to use modified value of global variable outside the function, then the keyword ‘global’
should be prefixed to the variable name in the function.
Example:
Program to define and access Global variable outside of function

Example: Accessing modified value of global variable outside function


To create a function, we need def- to define the function.
def test():
print("this is very very first fucntion")
Note- Print command generates non-type output i.e. it’s not a str, list, int, float etc. so generally we do not use
print command to generate output in functions.
We use return command for this to give output type as it is like input.
To call out a function we use functionname()
Case- def test():
print("this is very very first fucntion")
test() + “good”
run this code- Output is - unsupported operand type(s) for +: 'NoneType' and 'str'
Why ?
Print(data)-----non-type data + str

Instead we use return-


def test():
return"this is very very first fucntion"
test() + ‘good”
Output is – this is very very first function good.
Return- it gives same data to user i.e. str to str and int to int .
Code- def test3():
return 'nitin', 23, 0.5
Assigning Values using functions-
def test3():
return 'nitin', 23, 0.5
a,b,c=test3()
Assigning values with operations-
def test4(a,b,c):
d=a**c-b
return d
print(test4(2,3,4))
Creating a separator functions-
def test6(m):
... a=[]
... b=[]
... c=[]
... d=[]
... for i in l:
... if type(i)==int:
... [Link](i)
... elif type(i)==float:
... [Link](i)
... elif type(i)==str:
... [Link](i)
... elif type(i)==list:
... for j in i:
... if type(j)==int:
... [Link](j)
... else:
... continue
... return a,b,c,d
Dynamic Inputs
def test7(*args):
return args
*args ------------is used to give dynamic inputs which have any number. It returns data in tuples.
Note- you can use anything at args like *nitin. Generally, we use args which stands for arguments.

Another example- def test8(*args, a):


Return args, a
Inputs are – test8(1,2,3,4,5, a=”nitin”) o/p- ((1,2,3,4,5), ‘nitin’)

Another example-
def test8(**dict):
... return dict
test8(a='nitin', b= 'cousre', c='python')
o/p {'a': 'nitin', 'b': 'cousre', 'c': 'python'}

Generator Functions- to optimize memory utilization.


Yield functions- Example Generating Fib series.
def test_fib(n):
... a,b=0,1
... for i in range(n):
... yield a
... a,b=b,a+b
...
>>> for i in test_fib(15):
... print(i)

Next--------- s=’nitin sharma’


Next(s)
o/p----- not iterable
s1=iter(s)
check type(s1)
now,
next(s1)
o/p n
next(s1)
i
Fib Series using while Functions- def test_fib():
... a,b=0,1
... while True:
... yield a
... a,b=b,a+b
Fib=test_fib()
For I in range(10):
Print(next(fib))

Counting_Generator- def count_test(n):


... count=1
... while count <=n:
... yield count
... count=count+1
...
>>> c=count_test(15)
>>> for i in c:
... print(i)
>>> def matching(n):
... match n:
... case 1:
... print("mon")
... case 2:
... print("Tues")
... case 3:
... print("wed")
... case 4:
... print("thur")
... case 5:
... print("fri")
... case 6:
... print("sat")
... case 7:
... print("Sun")
...
>>> matching(5)
fri
Map Function-
Syntax- map(func, iterable)

Example- l=[23,43,233,44]
Def sq(x):
Return x**2

Map(sq, l)

List(map(sq,l)) o/p- [square of every number]


Using lambda function- list(map(lambda x : x**2, l))

Another Example- Adding two list –


a=[122,32,123,455]
b=[344,32,455,24]
list(map(lambda x,y : x+y, a,b))
op- [466, 64, 578, 479]
Try Yourself-
• list(map(lambda x,y : x*y, a,b))
• list(map(lambda x,y : x/y, a,b))
• list(map(lambda x,y : x-y, a,b))
• list(map(lambda x,y : x-y, b,a))
• a=[122,32,123,455,66], b=[344,32,455,24]
>>> list(map(lambda x,y : x+y, a,b))

Reduce Function
Before using reduce functions, firstly we have to import it.
How ?- from functools import reduce
Syntax- reduce(func, iterable)
a=[2,3,4,5]
reduce(lambda x,y: x+y, a)
0p- 10
Try ?
• reduce(lambda x,y: x*y, a)
• reduce(lambda x,y: x**y, a)
• reduce(lambda x,y: x/y, a)
• reduce(lambda x,y: y/x, a)
• reduce(lambda x,y,z: x+y+z, a)
• reduce(lambda x,y: x+y, [1])

Finding greatest number in the list-


a=[23,54,244,3,5,6,4,23,4,67,8,5,64564,35435423]
reduce(lambda x,y,: x if x>y else y, a)
35435423

Filter Function-
Syntax-filter(func, iterable)
a=[23,54,244,3,5,6,4,23,4,67,8,5,64564,35435423]
list(filter(lambda x: x%2==0, a))
[54, 244, 6, 4, 4, 8, 64564]
Try-
list(filter(lambda x: x%2 !=0, a))
Example- str greater than 5 characters l=['nitin', 'santosh', 'himanshu', 'aggrawal', 'monu', 'ram']
list(filter(lambda x: len(x)>5, l))
['santosh', 'himanshu', 'aggrawal']

#Working With Files


F=open(‘[Link]’, ‘w’)
W=write mode
To give date in the file we use
[Link](“data”)
[Link]()
close is mandatory to push data in file if we do not use close command files remain unchanged or as it
is as before.

To add more data in the file-


We use
F=open(‘[Link]’, ‘a’)
A= append mode.
R for read mode.
[Link]()
[Link](0)
Code-
f=open("[Link]", 'w')
>>> [Link]("new code")
8
>>> [Link]()
>>> f=open("[Link]", 'a')
>>> [Link](" for mu writing file")
20
>>> [Link]()
>>> f=open("[Link]", 'r')
>>> [Link]()
'new code for mu writing file'
Code for line by line-
[Link]()
''
>>> [Link](0)
0
>>> [Link]()
'new code for mu writing file'
>>>
Seek is used for cursor movement in the python.

File size-
import os
>>> [Link]("[Link]")
28
To remove file
[Link]("[Link]")

Rename a file-
[Link]("[Link]", "[Link]")

To create a copy of a file-


Import shutil
[Link](“[Link]”, “[Link]”)

Other way to create file-


with open ("[Link]", 'r') as f:
... print([Link]())
Dictionary
data={1:'nitin', 2:'sharma', 3:'code'}
>>> import json
>>> f=open("[Link]", 'w')
>>> f=open("[Link]", 'w')
>>> [Link](data,f)
>>> [Link]()
>>> f=open("[Link]", 'r')
>>> [Link]()
'{"1": "nitin", "2": "sharma", "3": "code"}'

#Writing data from a list to a file


>>> l=[1123, 'name', 'maarks']
>>> f=open('[Link]', 'w')
>>> [Link](l)
Traceback (most recent call last):
File "<python-input-3>", line 1, in <module>
[Link](l)
~~~~~~~~~~~~^^^
TypeError: write() argument must be str, not int
>>> l=['1123', 'name', 'maarks']
>>> [Link](l)
>>> [Link]()

Code-2
f=open('[Link]')
>>> [Link]()
'My name is nitin Sharma.\n'
>>> [Link]()
'i am the teacher of class 12th CS.\n'
>>> [Link]()
'i am teaching python to class 12th.'
>>> [Link]()
''
>>> [Link](5)

[Link]()
['me is nitin Sharma.\n', 'i am the teacher of class 12th CS.\n', 'i am teaching python to class 12th.']

#Practice Code-
1. Find number of characters in a file or rewrite it in another file in reverse.
2. Find number of lines in a file.
3. Find number of words in a file. data1=[Link]()
4. Find number of vowels or consonants in a file.
V=c=0
for i in d:
... if [Link]():
... if i in "aeiouAEIOU":
... v+=1
... else:
... c+=1
... print(v, c)
5. Find number of sentences in a file.
C=0
for i in d:
... if i==".":
... c+=1
... print(c)
6. Number of repeated words like python in a file.
c=0
>>> for i in data1:
... if i=="python" or i=="Python": (or if [Link]()==’PYTHON’:)
... c+=1
... print(c)
7. Printing those lines which start with My-
for i in a:
... x=[Link]()
... if x[0].upper()=="MY":
... print(i, end="")

#user specific location file creation-


f=open("C:\\Users\\DELL\\OneDrive\\Desktop\\[Link]", 'w')
>>> [Link]("new code")
8
>>> [Link]()

Or
f=open(r"C:\Users\DELL\OneDrive\Desktop\[Link]", 'w')
>>> [Link]("new code")
8
>>> [Link]()
Absolute Address-The complete address of a file.
E.g- C:\Users\DELL\OneDrive\Desktop\[Link]
Relative Address-The address of a file from a particular position.

#Binary File operations-


Extension- .dat
• Stored data as it is like data stores in HDD/SDD.
• Secured file as compared to text file. (Why? - because content can read only by a program.)
• Stores data in byte-stream i.e. your data get changed to byte stream and this process is called pickling
or serialization.
• Reverse of above process is called unpickling or de-serialization.
• Functions in binary files- load() for read and dump() for write and these functions are available after
importing pickle module. (Import pickle)
• Mode-
▪ Rb------read
▪ Wb-----write
▪ Ab------append
▪ Rb+-----read and write
▪ Wb+-----write & read
▪ Ab+-------append &read
d=["Nitin", 101 , 93]
>>> f=open("[Link]", 'wb')
>>> d=["Nitin", 101 , 93]
>>> [Link](d,f)
>>> [Link]()
>>> f=open("[Link]", 'rb')
>>> [Link](f)
['Nitin', 101, 93]

Import pickle
for i in [Link](f):
... if type(i)==complex:
... print([Link])

f=open("[Link]",'rb')
>>> for i in [Link](f):
... if type(i)==list:
... print(i[1])
...
23
>>> [Link](0)
0
>>> f=open("[Link]",'rb')
>>> for i in [Link](f):
... if type(i)==list:
... for j in i:
... if j==23:
... print(j)

CSV File
• Stands for comma separated values.
• Data stored in tabular form i.e. rows and column.
• Extension is .csv.
• We can use only after importing csv module. (Import csv)
• Some functions are-
o Writerow()------------------for one row.
o Writerows()-----------------for more than one row.
o Writer()----------------------writes data.
o Reader()---------------------reads data.

Key Note-
• If we use f=open(“[Link]”, ‘w’), it will buffer data into file when we use [Link]().
• But in case of---with open ("[Link]", 'r') as f:------------it doesn’t require [Link]() functions as it
automatically buffer data into the file.

def write():
... with open ("[Link]", 'w') as f:
... f_w=[Link](f)
... f_w.writerow(['Roll', "Name", "Marks"])
... while True:
... roll=int(input("enter roll numver "))
... name=input("enter name ")
... marks=int(input("enter marks "))
... data=[roll, name, marks]
... f_w.writerow(data)
... option=int(input("1- more data\n2- break\n3-enter choice"))
... if option==2:
... break

Output-
Roll Name Marks

101 nitin 93

102 mohit 63

Note- in above output- you will observe one additional line in the table it is because in csv file it is default to
add extra line the output.
Question- How will overcome these extra lines?
New code-
def write():
... with open ("[Link]", 'w', newline=’’) as f:
... f_w=[Link](f)
... f_w.writerow(['Roll', "Name", "Marks"])
... while True:
... roll=int(input("enter roll numver "))
... name=input("enter name ")
... marks=int(input("enter marks "))
... data=[roll, name, marks]
... f_w.writerow(data)
... option=int(input("1- more data\n2- break\n3-enter choice"))
... if option==2:
... break

Output-
Roll Name Marks
101 nitin 93
102 mohit 63
103 rohit 85

#Reading the data


def read():
... with open("[Link]", 'r') as f:
... f_r=[Link](f)
... for i in f_r:
... print(i)
...
>>> read()
['Roll', 'Name', 'Marks']
['101', 'nitin', '93']
['102', 'mohit', '63']
['103', 'rohit', '85']

#searching the data


def search():
... with open ("[Link]", 'r') as f:
... f_r=[Link](f)
... c=0
... roll=int(input("enter roll number to seacrh "))
... next(f)
... for i in f_r:
... if int(i[0])==roll:
... c=1
... print(i)
... break
... if c==0:
... print("no result found")

#Maximum number in data


def max():
... import csv
... with open ('[Link]' , 'r') as f:
... fr=[Link](f)
... c=-1
... next(fr)
... for i in fr:
... if int(i[2])>c:
... c=int(i[2])
... z=i
... print(z)
#Minimum number in data
def min():
... import csv
... with open ('[Link]' , 'r') as f:
... fr=[Link](f)
... c=101
... next(fr)
... for i in fr:
... if int(i[2])<c:
... c=int(i[2])
... z=i
... print(z)
#Exception Handling
Python is first compiled & interpreted.
These errors occur when
we didn't follow
programming stntax.
Syntax
Error/parsing errors.
Example- print('hello)
These error can caught by
compiler. Program doesn't
Error run if occurs.

These are run time errors


Exception that causes termination of
Error our program.
E.g- print(a)
More e.g-1. a=”nitin”
B=a/2
Print(b)

2. A=5
Print(a/0)

Result/problem-
• The whole program is terminated when an exception is encountered.
Exception Handling- To overcome the termination of program when exception error occurred.
Types of Exception-
1. Built-in Ex-
a. That are already defined.
b. exceptions are usually defined in the compiler/interpreter. These are called built-
in exceptions.

print(a)
Traceback (most recent call last):
File "<python-input-0>", line 1, in <module>
print(a)
^
NameError: name 'a' is not defined
>>> print(10/0)
Traceback (most recent call last):
File "<python-input-1>", line 1, in <module>
print(10/0)
~~^~
ZeroDivisionError: division by zero
>>> print("ram"/2)
Traceback (most recent call last):
File "<python-input-2>", line 1, in <module>
print("ram"/2)
~~~~~^~
TypeError: unsupported operand type(s) for /: 'str' and 'int'
import nitin
Traceback (most recent call last):
File "<python-input-3>", line 1, in <module>
import nitin
ModuleNotFoundError: No module named 'nitin'

2. User defined ex.


a. The exceptions that are handled by a user.
b. User-defined exceptions in Python are custom exceptions created by the
programmer to handle specific error conditions not covered by built-in
exceptions. They enhance code readability, maintainability, and robustness by
allowing developers to define custom error conditions and behaviours.

How to overcome using codes?


4 Ways-
a. Try------------It contains segments in which exception errors can occur.
b. Except--------It executes this code when in try section gets an error.
c. Else------------It executes code when there is no error occurs.
d. Finally---------It executes in every conditions i.e. error or no error is found.

a=5
>>> b=3
>>> c=3
>>> a/(b-c)
>>> try:
... a/(b-c)
... except:
... print("error aa gya h")
...
error aa gya h

a=int(input("enter your number"))


enter your numberram
Traceback (most recent call last):
File "<python-input-5>", line 1, in <module>
a=int(input("enter your number"))
ValueError: invalid literal for int() with base 10: 'ram'
>>> try:
... a=int(input("enter your number"))
... except:
... print("arey bhaiya interger daalo string nahi")
...
enter your number"ram"
arey bhaiya interger daalo string nahi

try:
... print(s)
... c=s/0
... except NameError:
... print("error")
... except:
... print("another error")
...
error
>>> try:
... s=2
... print(s)
... c=s/0
... except NameError:
... print("error")
... except:
... print("another error")
...
2
another error

try:
... print("hello")
... except:
... print("error")
... else:
... print("no error")
...
hello
no error

try:
... print("hello")
... except:
... print("error")
... else:
... print("no error")
... finally:
... print(" jay Ho")

#User defined exceptions-


We use raise command-
x="nitin"
>>> if not type(x) is int:
... raise Exception ("Int allowed")
...
Traceback (most recent call last):
File "<python-input-8>", line 2, in <module>
raise Exception ("Int allowed")
Exception: Int allowed

# Python Data Structure--- Stack & Queue


Data Structures- Data Structures are a way of storing and organizing data in a computer in a
efficient manner.
Python has built-in support for several data structures, such as lists, dictionaries, and set.
Other data structures can be implemented using Python classes and objects, such as linked
lists, stacks, queues, trees, and graphs.

Algorithms are a way of working with data in a computer and solving problems like sorting,
searching, etc.

In this, we will concentrate on these Data Structures: Two Types-


Linear Data Structures-
• Lists /Arrays
• Stacks
• Queues
• Linked Lists
• Hash Tables/ Dictionary
Non-Linear Data Structures
• Trees
o Binary Trees
o Binary Search Trees
o AVL Tree
• Graph

Stack- A stack is a linear data structure that follows the Last-In-First-Out (LIFO) or FILO (First in
last out) principle/mechanism.

E.g.- Think of it like a stack of pancakes - you can only add or remove pancakes from the top.
Stack of plates in a wedding or party.
Bangles wear by women is also a example of stack.
Programming world example- Recursion and Expression evaluate (PEDMAS).

Stacks can be implemented by using arrays or linked lists.


Basic operations we can do on a stack are:
• Push: Adds/insert a new element on the stack.
• Pop: Removes and returns the top element from the stack.
• Peek: Returns the top (last) element on the stack.
• Size: Finds the number of elements in the stack.
• Display: to show data from last element to first.

Concepts-
• StackUnderFlow- if we use POP to delete a data in a empty stack it is called………..
• PUSH-Add data just like append.
F
E
D
C
B
A
• POP- deletes last element.
• Display all-----display all element in a stack from last index to zero.

Codes-Push
#########################################################################
a=[]
>>> def push(a):
... element=int(input("enter the value "))
... [Link](element)
... print("Push done ")

>>> push(a)
enter the value 20
Push done
>>> a
[20]

##########################################################################
a=[]
def Pop(a):
... x=[Link]()
... return "deleted value=", x

>>> a=[1,2,3]
>>> Pop(a)
('deleted value=', 3)
>>> a
[1, 2]

########################################################################
a=[1,2,3,4,5,6]
>>> def peek(a):
... return "Top element is=",a[-1]
...
>>> peek(a)
('Top element is=', 6)

#######################################################################
a=[1,2,3,4,5,6,7,8,9]
>>> def display(a):
... for i in range(len(a)-1,-1,-1):
... print(a[i])
...
>>> display(a)
9
8
7
6
5
4
3
2
1

######################################################################
a=[1,2,3,4,5,6,7,8,9]
def size(a):
... return "size is=", len(a)
...
>>> size(a)
('size is=', 9)

##########################################################################
Summary-
We learn today------
push(a)
Pop(a)
peek(a)
display(a)
size(a)

##########################################################################
a=[]
>>> while True:
... option=int(input("1 for push\n2 more Pop\n3 for peek\n4 for display\n5 for size\n6 for
exit "))
... if option==1:
... push(a)
... elif option==2:
... if len(a)==0:
... print("stack over flow")
... else:
... Pop(a)
... elif option==3:
... if len(a)==0:
... print("stack over flow")
... else:
... peek(a)
... elif option==4:
... if len(a)==0:
... print("stack over floe")
... else:
... display(a)
... elif option==5:
... size(a)
... elif option==6:
... break
... else:
... print("wrong entry")
...
1 for push
2 more Pop
3 for peek
4 for display
5 for size
1 for push
2 more Pop
3 for peek
4 for display
5 for size
6 for exit 1
enter the value 12
Push done
1 for push
2 more Pop
3 for peek
4 for display
5 for size
1 for push
2 more Pop
3 for peek
4 for display
5 for size
6 for exit 1
enter the value 34
Push done
1 for push
2 more Pop
3 for peek
4 for display
5 for size
1 for push
2 more Pop
3 for peek
4 for display
5 for size
6 for exit 2
('deleted value=', 34)
1 for push
2 more Pop
3 for peek
4 for display
5 for size
1 for push
2 more Pop
3 for peek
4 for display
5 for size
6 for exit 3
('Top element is=', 12)
1 for push
2 more Pop
3 for peek
4 for display
5 for size
1 for push
2 more Pop
3 for peek
4 for display
5 for size
6 for exit 4
12
1 for push
2 more Pop
3 for peek
4 for display
5 for size
1 for push
2 more Pop
3 for peek
4 for display
5 for size
6 for exit 5
('size is=', 1)
1 for push
2 more Pop
3 for peek
4 for display
5 for size
1 for push
2 more Pop
3 for peek
4 for display
5 for size
6 for exit 6
>>> a
[12]

############################################################################
Reasons to implement stacks using lists/arrays:
• Memory Efficient: Array elements do not hold the next elements address like linked list
nodes do.
• Easier to implement and understand: Using arrays to implement stacks require less
code than using linked lists, and for this reason it is typically easier to understand as
well.
A reason for not using arrays to implement stacks:
• Fixed size: An array occupies a fixed part of the memory. This means that it could take
up more memory than needed, or if the array fills up, it cannot hold more elements.

def push(a):
... element=input("enter characters ")
... [Link](element)
... data=int(input("enter number "))
... [Link](data)
...
>>> push(a)
enter characters Nitin
enter number 23
>>> a
['Nitin', 'Rohit', 'Mohit', 'Nitin', 23]
>>> a[-1] + 1000

def stack():
... a=[]
... while True:
... option=int(input("1 for push\n2 for pop\n3 for peek\n4 for size\n5 for display\n6 for
exit "))
... if option==1:
... push(a)
... elif option==2:
... if len(a)==0:
... print("stack over flow")
... else:
... Pop(a)
... elif option==3:
... if len(a)==0:
... print("stack over flow")
... else:
... peek(a)
... elif option==4:
... size(a)
... elif option==5:
... if len(a)==0:
... print("stack over flow")
... else:
... display(a)
... elif option==6:
... break
... else:
... print("wrong input, please select correct input")

Common Stack Applications


Stacks are used in many real-world scenarios:
• Undo/Redo operations in text editors
• Browser history (back/forward)
• Function call stack in programming
• Expression evaluation

Polish String-"Polish string" refers to a string representation of mathematical expressions using


Polish notation. Polish notation, also known as prefix notation, is a way of writing
mathematical expressions where the operator precedes its operands.
Three types
• Infix-----Operators lie inside. E.g- a+b
• Prefix----Operations lie before. E.g +ab
• Postfix----Operations lie after. E.g ab+
Stack Uses----- Recursion & Evaluation of Expression.
System Process-
Infix Postfix Evaluate
#How to convert infix to postfix?
To know about this, firstly we must understand the precedence of operators or order of
operators in which system evaluate.
Bracket
[],{},()
Exponent
**, ^
Divide, multiply
/, *
Add, Subtract
Logical operator Q1- A+B*C/(E-F)
NOT, AND, OR Sol—A+B*C/EF-
Relational Operator A+BC*/EF-
<,> A+BC*EF-/
ABC*EF-/+
Q2- A*((B*C)+(D*F))/E
A*(BC*+DF*)/E
A*BC*DF*+/E
ABC*DF*+*/E
ABC*DF*+*E/
Q3- (A+B)*(C*D-E)*F/G Ans—AB+CD*E-*F*G/

Q4- NOT A OR NOT B AND NOT C


ANOT OR BNOT AND CNOT
ANOT OR BNOT CNOT AND
ANOT BNOT CNOT AND OR
#Python Libraries
Library- Super set which contains a set of modules.
• Library and Package terms are used interchangeably.
• A package is a way to organize related modules into a directory hierarchy, providing a
structured approach to managing and distributing code. Essentially, it is a directory
containing Python modules and a special file named __init__.py is made in a desire
folder which is going to be used as LIB.
• __init__.py is a empty file.
• A library may have one or more packages/sub-packages.

Step for making a package-


• Decide basic structure of the packages like you are looking at above picture.
• Create a directories\sub directories i.e. folder sub-folder.
• Every folder/sub-folder must have __init__.py file.
• We must associate this package to python’s site-package folder of the current python
installation.
• For site package-
o Import sys
o Print([Link])
'C:\\Users\\DELL\\AppData\\Local\\Programs\\Python\\Python313\\Lib\\site-packages'
• Move your package folder to above location.
• Note- app data is a hidden files so we must do show all files.
Output-
import Bhavna
import [Link]
[Link]()
this is the data for board claases

OR
from Bhavna import details
[Link]()
this is the data for board claases

OR
[Link].board10()
data of clas 10th
Random Module
It generates random numbers or values.
It has following functions -
• random()- generates random decimal values in range 0 to less than 1.
o import random
>>> [Link]()
0.889835960882264
• randint()-generates integers between two including numbers.
o [Link](1,10)
7
• [Link](2)—Generates n size random bytes.
b'\x17\r'
• randrange()-generates random values between a range.
o [Link](0,10,3)
0
SQL- Structure Query Language
SQL-It is a kind of RDBMS where data is stored in Tabular format.
Data-Data are raw facts and figures that are given to computer system.
It can be meaningful or not.
Information- Processed data is called information. It is always meaningful.

Data Processed Information


Bhavna

Students Teacher

Computer Nitin

Database-It is and organised collection of data.

Data Organize Database


Example- Dictionary- Words are arranged in alphabetical order.
Telephone Directory etc.

Benefits of database-
• Data searching becomes extremely fast.
• Data becomes consistent. (same data or updating easy)
• Data integrity- completeness of data.
• Data is accurate.
• Data is centralised (accessed by everyone)

Database

Relational database object oriented


Hierarchical database network database
management system database
management system management system.
(RDbMS) management system

DBMS- It is a software that organizes the data.


RDBMS- In RDBMS, data is stored in rows and column i.e. in a table.

Data process Information Organize Database RDMS MYSQL

RDBMS- MS Access, oracle, Mysql.


Note- In RDBMS, Some nomenclature are there.
Table Relation
Column/Field Attributes
Rows Tuple
Number of rows Cardinality (Ex. Heading)
Number of columns degree
domain Pool of values (Gender has 3)
Commands- These are words/phrases that carries out some well-defined task.
MYSQL- This allows us to store data and manipulated data in n number of ways. It is nothing
but collection of commands. For each table we have a command.
There are a lot of command which are categorized in three ways-
• DDL- Data Definition Language.
• DML- Data Manipulation Language.
• TCL/DCL- Transaction Control Language or Data Control Language.

DDL- Data Definition Language- The commands that deals with defining database. Related to
structure of table.
E.g. Create, Alter, Drop etc.

DML- Data Manipulation Language- related to manipulation of database. Related to data.


E.g. Insert, delete, update etc. (Select)

TCL/DCL- Transaction Control Language or Data Control Language- Commands that are
associated with controlling all over operations of a database. E.g.- Grant , Revoke in DCL.

Transactions- it is set of operations which is either complete successful or never imitated.


Example- Downloading failed at 99%.

TCL Commands- Commit or Rollback.

Constraint- SQL constraints are used to specify rules for the data in a table. Constraints are
used to limit the type of data that can go into a table. This ensures the accuracy and reliability
of the data in the table. If there is any violation between the constraint and the data action,
the action is aborted.

Following Constraints-
• Primary Key- It states that a filed which has been made primary cannot contain
duplicate values as well as it cannot be left behind. (Combination of the NOT NULL and
UNIQUE constraints.) Example account number of bank, student roll number of cbse,
Aadhar card etc. (uniquely identifier)
• Foreign Key-A FOREIGN KEY constraint links a column in one table to the primary key in
another table. This relationship helps maintain referential integrity by ensuring that the
value in the foreign key column matches a valid record in the referenced table.
Order
Customers Table:

C_ID NAME ADDRESS
O_ID ORDER_NO C_ID
1 RAMESH DELHI
1 2253 3

2 SURESH NOIDA
2 3325 3
3 DHARMESH GURGAON
3 4521 2

4 8532 1

• NOT NULL- It states that a filed which has been made NOT NULL cannot contain null
values.
• UNIQUE Key- It states that a field which has been made unique cannot contain duplicate
values. Example- Mobile Number, (the UNIQUE constraint allows NULL values but still
enforces uniqueness for non-NULL entries.)
• CHECK-The CHECK constraint allows us to specify a condition that data must satisfy
before it is inserted into the table. This can be used to enforce rules, such as ensuring
that a column’s value meets certain criteria (e.g., age must be greater than 18).
• DEFAULT-The DEFAULT constraint provides a default value for a column when no value is
specified during insertion. This is useful for ensuring that certain columns always have a
meaningful value, even if the user does not provide one. Like age is left will be 18
automatically.
• INDEX- Indexes are used to retrieve data from the database more quickly than
otherwise. The users cannot see the indexes; they are just used to speed up
searches/queries. Note: Updating a table with indexes takes more time than updating a
table without (because the indexes also need an update). So, only create indexes on
columns that will be frequently searched against.

Composite Key Concept-


Emp Code Name DOB POST DOJ Salary

Here, Emp code will be used as primary because it cannot be null and always has unique
values.
Let us assume a case in which data is same like above table but emp code column is not there.
Name DOB POST DOJ Salary

Now question is which will be act as primary key?


Any guess???

Any idea?

Answer- we will use 2 or more values like Name+ DOB+ DOJ to make uniqueness. These 2 or
more values or field are termed as composite key.
Definition- A composite key in SQL combines two or more columns to uniquely identify each
record in a table. Database designers use composite keys when a single column cannot ensure
uniqueness.

Candidate Key Concept-


When 2 or more column can act as primary are termed as candidate key from which we select
primary key. And others rest are termed as alternate key.

Data about data is called Metadata. Anything that describes the database—as opposed to
being the contents of the database—is metadata. Thus, column names, database names, user
names, version names, and most of the string results from SHOW are metadata.

SQL Datatypes- A person must decide what type of data that will be stored inside each column
when creating a table. The data type is a guideline for SQL to understand what type of data is
expected inside of each column, and it also identifies how SQL will interact with the stored
data.
SQL datatypes are-
a) Int- for integer
b) Decimal- for floating values
c) Char- A FIXED length string (can contain letters, numbers, and special characters). The
size parameter specifies the column length in characters - can be from 0 to 255. Default
is 1. It fills unused with blank or white space.
d) VARCHAR- A VARIABLE length string (can contain letters, numbers, and special
characters). The size parameter specifies the maximum string length in characters - can
be from 0 to 65535. It releases unused
e) Date- A date. Format: YYYY-MM-DD. The supported range is from '1000-01-01' to '9999-
12-31'.
Char Varchar
A FIXED length string A VARIABLE length strin
Processing is faster Processing is slower
Size-0 to 255 Size- 0 to 65535
Total character 256 65536
It fills unused with blank or white space. It releases unused

Practical
Downloading Steps-
1) Type MySQL in google.
2) open official website- [Link]
3) click on downloads
4) click on MySQL Community (GPL) Downloads » bottom of the page.
5) Click on MySQL Installer for Windows on left bottom of the page.
6) Select version and operating OS.
7) Click on second link with higher data size.
8) Click on no thanks, just start my download.
9) Run the downloaded setup.
10) Select Custom then MYSQL Server and Application (workbench + mysql shell). Click right
arrow to drag it.
11) Click next and execute, next, next, next.
12) Select 1st options for authentication with password.
13) Create password Bhavna@123. Then next, next, execute and finish.
14) Select the path - C:\Program Files\MySQL\MySQL Server 8.0\bin
15) Copy the path and search environment variable in start.
16) Click open and go to environment variable and go to system variable and double click on
path.
17) Click on New and paste the copied path and execute all ok.

User name- root password-Bhavna@123

In cmd you can go for Mysql – just type mysql -u root -p.
And for version check type mysql –version.
Working with MYSQL
Creating Database-(Space not allowed)
• create database name;
o example- create database cs_12;
▪ Query OK, 1 row affected (0.05 sec)
Checking databases or Show-
• show databases;
+--------------------+
| Database |
+--------------------+
| cs_12 |
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
5 rows in set (0.00 sec)
Working with created database-
• use cs_12;
Database changed
mysql> create table employee(
-> code integer primary key,
-> name varchar(30) NOT NULL,
-> designation varchar(30) NOT NULL,
-> salary decimal check(salary>10500),
-> doj date,
-> state varchar(30),
-> mobile char(10) unique key,
-> gender char default 'M'
-> );
Query OK, 0 rows affected (0.15 sec)
It creates structure of a table.
mysql> show tables;
+-----------------+
| Tables_in_cs_12 |
+-----------------+
| employee |
+-----------------+
1 row in set (0.03 sec)

mysql> desc employee; ------------→


To see structure of a table.

mysql> select * from employee; It means no data.


Empty set (0.02 sec)
Now, we have to insert data-
mysql> insert into employee values(001, 'Nitin', 'Teacher', 25000, '2025-04-23', 'UP',
'9999397961', 'M');
Query OK, 1 row affected (0.01 sec)

Checking data- Select command is used to extract data from a database.


mysql> select * from employee;

You can add one by one data to this table.


insert into employee values(002, 'Mohit', 'Teacher', 22000, '2023-04-23', 'MP', '1236547890',
'M');
Query OK, 1 row affected (0.01 sec)

mysql> select * from employee;


+------+-------+-------------+--------+------------+-------+------------+--------+
| code | name | designation | salary | doj | state | mobile | gender |
+------+-------+-------------+--------+------------+-------+------------+--------+
| 1 | Nitin | Teacher | 25000 | 2025-04-23 | UP | 9999397961 | M |
| 2 | Mohit | Teacher | 22000 | 2023-04-23 | MP | 1236547890 | M |
+------+-------+-------------+--------+------------+-------+------------+--------+
2 rows in set (0.00 sec)

mysql> select code,name,salary from employee; User defined is displayed.


+------+-------+--------+
| code | name | salary |
+------+-------+--------+
| 1 | Nitin | 25000 |
| 2 | Mohit | 22000 |
+------+-------+--------+
2 rows in set (0.00 sec)

Where is used to apply condition, as seen in example below-we have to get data for code=2.
mysql> select * from employee where code=2;
+------+-------+-------------+--------+------------+-------+------------+--------+
| code | name | designation | salary | doj | state | mobile | gender |
+------+-------+-------------+--------+------------+-------+------------+--------+
| 2 | Mohit | Teacher | 22000 | 2023-04-23 | MP | 1236547890 | M |
+------+-------+-------------+--------+------------+-------+------------+--------+
1 row in set (0.01 sec)
mysql> select * from employee where state='mp';
+------+-------+-------------+--------+------------+-------+------------+--------+
| code | name | designation | salary | doj | state | mobile | gender |
+------+-------+-------------+--------+------------+-------+------------+--------+
| 2 | Mohit | Teacher | 22000 | 2023-04-23 | MP | 1236547890 | M |
+------+-------+-------------+--------+------------+-------+------------+--------+
1 row in set (0.01 sec)

mysql> select * from employee where salary>22500;


+------+-------+-------------+--------+------------+-------+------------+--------+
| code | name | designation | salary | doj | state | mobile | gender |
+------+-------+-------------+--------+------------+-------+------------+--------+
| 1 | Nitin | Teacher | 25000 | 2025-04-23 | UP | 9999397961 | M |
+------+-------+-------------+--------+------------+-------+------------+--------+
1 row in set (0.00 sec)

mysql> select * from employee where doj<'2024-01-01';


+------+-------+-------------+--------+------------+-------+------------+--------+
| code | name | designation | salary | doj | state | mobile | gender |
+------+-------+-------------+--------+------------+-------+------------+--------+
| 2 | Mohit | Teacher | 22000 | 2023-04-23 | MP | 1236547890 | M |
+------+-------+-------------+--------+------------+-------+------------+--------+
1 row in set (0.01 sec)

mysql> select * from employee where salary>15000 and state="mp";


+------+-------+-------------+--------+------------+-------+------------+--------+
| code | name | designation | salary | doj | state | mobile | gender |
+------+-------+-------------+--------+------------+-------+------------+--------+
| 2 | Mohit | Teacher | 22000 | 2023-04-23 | MP | 1236547890 | M |
+------+-------+-------------+--------+------------+-------+------------+--------+
1 row in set (0.01 sec)

mysql> select * from employee where state="up" or state="mp";


+------+-------+-------------+--------+------------+-------+------------+--------+
| code | name | designation | salary | doj | state | mobile | gender |
+------+-------+-------------+--------+------------+-------+------------+--------+
| 1 | Nitin | Teacher | 25000 | 2025-04-23 | UP | 9999397961 | M |
| 2 | Mohit | Teacher | 22000 | 2023-04-23 | MP | 1236547890 | M |
+------+-------+-------------+--------+------------+-------+------------+--------+
2 rows in set (0.00 sec)

mysql> select * from employee where gender="f";


mysql> select * from employee order by salary;
+------+-------+-------------+--------+------------+-------+------------+--------+
| code | name | designation | salary | doj | state | mobile | gender |
+------+-------+-------------+--------+------------+-------+------------+--------+
| 2 | Mohit | Teacher | 22000 | 2023-04-23 | MP | 1236547890 | M |
| 1 | Nitin | Teacher | 25000 | 2025-04-23 | UP | 9999397961 | M |
+------+-------+-------------+--------+------------+-------+------------+--------+
2 rows in set (0.00 sec)
Arrange data in ascending order by default.(does not change original data)

mysql> select * from employee order by salary desc;


+------+-------+-------------+--------+------------+-------+------------+--------+
| code | name | designation | salary | doj | state | mobile | gender |
+------+-------+-------------+--------+------------+-------+------------+--------+
| 1 | Nitin | Teacher | 25000 | 2025-04-23 | UP | 9999397961 | M |
| 2 | Mohit | Teacher | 22000 | 2023-04-23 | MP | 1236547890 | M |
+------+-------+-------------+--------+------------+-------+------------+--------+
2 rows in set (0.00 sec)

Arrange data in descending order

mysql> select * from employee where salary>15000 and salary<23000;


+------+-------+-------------+--------+------------+-------+------------+--------+
| code | name | designation | salary | doj | state | mobile | gender |
+------+-------+-------------+--------+------------+-------+------------+--------+
| 2 | Mohit | Teacher | 22000 | 2023-04-23 | MP | 1236547890 | M |
+------+-------+-------------+--------+------------+-------+------------+--------+
1 row in set (0.00 sec)
OR
mysql> select * from employee where salary between 15000 and 23000;
+------+-------+-------------+--------+------------+-------+------------+--------+
| code | name | designation | salary | doj | state | mobile | gender |
+------+-------+-------------+--------+------------+-------+------------+--------+
| 2 | Mohit | Teacher | 22000 | 2023-04-23 | MP | 1236547890 | M |
+------+-------+-------------+--------+------------+-------+------------+--------+
1 row in set (0.01 sec)

mysql> select * from employee where salary not between 15000 and 23000;

mysql> select * from employee where state in ('up','mp');


+------+-------+-------------+--------+------------+-------+------------+--------+
| code | name | designation | salary | doj | state | mobile | gender |
+------+-------+-------------+--------+------------+-------+------------+--------+
| 1 | Nitin | Teacher | 25000 | 2025-04-23 | UP | 9999397961 | M |
| 2 | Mohit | Teacher | 22000 | 2023-04-23 | MP | 1236547890 | M |
+------+-------+-------------+--------+------------+-------+------------+--------+
2 rows in set (0.00 sec)

mysql> select * from employee where state not in ('up','mp');

mysql> select distinct(designation) from employee;


+-------------+
| designation |
+-------------+
| Teacher |
+-------------+
1 row in set (0.01 sec) Gives unique entry (no duplicate values)

Like Clause- used for pattern matching.


%----------multiple character
_--------------single character

mysql> select * from employee where name like "n%";


+------+-------+-------------+--------+------------+-------+------------+--------+
| code | name | designation | salary | doj | state | mobile | gender |
+------+-------+-------------+--------+------------+-------+------------+--------+
| 1 | Nitin | Teacher | 25000 | 2025-04-23 | UP | 9999397961 | M |
+------+-------+-------------+--------+------------+-------+------------+--------+

mysql> select * from employee where name like "nb%";


Empty set (0.00 sec)

mysql> select * from employee where name like "%ti%";


+------+-------+-------------+--------+------------+-------+------------+--------+
| code | name | designation | salary | doj | state | mobile | gender |
+------+-------+-------------+--------+------------+-------+------------+--------+
| 1 | Nitin | Teacher | 25000 | 2025-04-23 | UP | 9999397961 | M |
+------+-------+-------------+--------+------------+-------+------------+--------+
1 row in set (0.00 sec)

mysql> select * from employee where name like "____"; (4 _)


Empty set (0.00 sec)

mysql> select * from employee where name like "_____"; (5_)


+------+-------+-------------+--------+------------+-------+------------+--------+
| code | name | designation | salary | doj | state | mobile | gender |
+------+-------+-------------+--------+------------+-------+------------+--------+
| 1 | Nitin | Teacher | 25000 | 2025-04-23 | UP | 9999397961 | M |
| 2 | Mohit | Teacher | 22000 | 2023-04-23 | MP | 1236547890 | M |
+------+-------+-------------+--------+------------+-------+------------+--------+
2 rows in set (0.00 sec)

mysql> select * from employee where name like "_n%";


Empty set (0.00 sec)

mysql> select * from employee where name like "_i%";


+------+-------+-------------+--------+------------+-------+------------+--------+
| code | name | designation | salary | doj | state | mobile | gender |
+------+-------+-------------+--------+------------+-------+------------+--------+
| 1 | Nitin | Teacher | 25000 | 2025-04-23 | UP | 9999397961 | M |
+------+-------+-------------+--------+------------+-------+------------+--------+
1 row in set (0.00 sec)
mysql> select * from employee where name not like "_i%"; do yourself

mysql> select code as employ_code, name as employ_name from employee;


+-------------+-------------+
| employ_code | employ_name |
+-------------+-------------+
| 1 | Nitin |
| 2 | Mohit |
+-------------+-------------+
2 rows in set (0.00 sec)

mysql> select code, name, salary*1.05 from employee;


+------+-------+-------------+
| code | name | salary*1.05 |
+------+-------+-------------+
| 1 | Nitin | 26250.00 |
| 2 | Mohit | 23100.00 |
+------+-------+-------------+
2 rows in set (0.00 sec)

mysql> update employee set salary="35000";


Query OK, 2 rows affected (0.04 sec)
Rows matched: 2 Changed: 2 Warnings: 0

mysql> select * from employee;


+------+-------+-------------+--------+------------+-------+------------+--------+
| code | name | designation | salary | doj | state | mobile | gender |
+------+-------+-------------+--------+------------+-------+------------+--------+
| 1 | Nitin | Teacher | 35000 | 2025-04-23 | UP | 9999397961 | M |
| 2 | Mohit | Teacher | 35000 | 2023-04-23 | MP | 1236547890 | M |
+------+-------+-------------+--------+------------+-------+------------+--------+
2 rows in set (0.00 sec)

mysql> update employee set salary="55000" where code=1;


Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> select * from employee;


+------+-------+-------------+--------+------------+-------+------------+--------+
| code | name | designation | salary | doj | state | mobile | gender |
+------+-------+-------------+--------+------------+-------+------------+--------+
| 1 | Nitin | Teacher | 55000 | 2025-04-23 | UP | 9999397961 | M |
| 2 | Mohit | Teacher | 35000 | 2023-04-23 | MP | 1236547890 | M |
+------+-------+-------------+--------+------------+-------+------------+--------+
2 rows in set (0.00 sec)

mysql> insert into employee values(3, "rohit", "Peon", "10600", "2024-05-03", "Mumbai",
"8888888888", "M");
Query OK, 1 row affected (0.01 sec)

mysql> select * from employee;


+------+-------+-------------+--------+------------+--------+------------+--------+
| code | name | designation | salary | doj | state | mobile | gender |
+------+-------+-------------+--------+------------+--------+------------+--------+
| 1 | Nitin | Teacher | 55000 | 2025-04-23 | UP | 9999397961 | M |
| 2 | Mohit | Teacher | 35000 | 2023-04-23 | MP | 1236547890 | M |
| 3 | rohit | Peon | 10600 | 2024-05-03 | Mumbai | 8888888888 | M |
+------+-------+-------------+--------+------------+--------+------------+--------+
3 rows in set (0.00 sec)

mysql> delete from employee where code=1;


Query OK, 1 row affected (0.01 sec)

mysql> select * from employee;


+------+-------+-------------+--------+------------+--------+------------+--------+
| code | name | designation | salary | doj | state | mobile | gender |
+------+-------+-------------+--------+------------+--------+------------+--------+
| 2 | Mohit | Teacher | 35000 | 2023-04-23 | MP | 1236547890 | M |
| 3 | rohit | Peon | 10600 | 2024-05-03 | Mumbai | 8888888888 | M |
+------+-------+-------------+--------+------------+--------+------------+--------+
2 rows in set (0.00 sec)

Drop command------ it deletes all data along with structure of the table.
Syntax- drop table employee;

mysql> insert into employee(code, name, designation) values(104, "ranapratap", "principal");


Query OK, 1 row affected (0.01 sec)

mysql> select * from employee;


+------+------------+-------------+--------+------------+--------+------------+--------+
| code | name | designation | salary | doj | state | mobile | gender |
+------+------------+-------------+--------+------------+--------+------------+--------+
| 2 | Mohit | Teacher | 35000 | 2023-04-23 | MP | 1236547890 | M |
| 3 | rohit | Peon | 10600 | 2024-05-03 | Mumbai | 8888888888 | M |
| 104 | ranapratap | principal | NULL | NULL | NULL | NULL |M |
+------+------------+-------------+--------+------------+--------+------------+--------+
3 rows in set (0.00 sec)

mysql> select * from employee where salary is null;


+------+------------+-------------+--------+------+-------+--------+--------+
| code | name | designation | salary | doj | state | mobile | gender |
+------+------------+-------------+--------+------+-------+--------+--------+
| 104 | ranapratap | principal | NULL | NULL | NULL | NULL | M |
+------+------------+-------------+--------+------+-------+--------+--------+
1 row in set (0.00 sec)

mysql> select * from employee limit 2;


+-------------+-------+-------------+--------+------------+--------+------------+--------+
| employ_code | name | designation | salary | doj | state | mobile | gender |
+-------------+-------+-------------+--------+------------+--------+------------+--------+
| 2 | Mohit | Teacher | 35000 | 2023-04-23 | MP | 1236547890 | M |
| 3 | rohit | Peon | 10600 | 2024-05-03 | Mumbai | 8888888888 | M |
+-------------+-------+-------------+--------+------------+--------+------------+--------+
2 rows in set (0.00 sec)

mysql> select min(salary) as minimum_salary from employee;


+----------------+
| minimum_salary |
+----------------+
| 10600 |
+----------------+
1 row in set (0.01 sec).

mysql> select max(salary) as maximum_salary from employee;


+----------------+
| maximum_salary |
+----------------+
| 35000 |
+----------------+
1 row in set (0.00 sec)

mysql> select count(state) from employee;


+--------------+
| count(state) |
+--------------+
| 2|
+--------------+
1 row in set (0.00 sec)
Note: NULL values are not counted.

mysql> select avg(salary) from employee;


+-------------+
| avg(salary) |
+-------------+
| 22800.0000 |
+-------------+
1 row in set (0.00 sec)
Note: NULL values are ignored.

mysql> select sum(salary) from employee;


+-------------+
| sum(salary) |
+-------------+
| 45600 |
+-------------+
Note: NULL values are ignored.

Alter Command- It changes table structure. (ADD, Modify, Rename, Drop).

mysql> alter table employee rename column code to employ_code;


Query OK, 0 rows affected (0.14 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> desc employee;


+-------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------+------+-----+---------+-------+
| employ_code | int | NO | PRI | NULL | |
| name | varchar(30) | NO | | NULL | |
| designation | varchar(30) | NO | | NULL | |
| salary | decimal(10,0) | YES | | NULL | |
| doj | date | YES | | NULL | |
| state | varchar(30) | YES | | NULL | |
| mobile | char(10) | YES | UNI | NULL | |
| gender | char(1) | YES | | M | |
+-------------+---------------+------+-----+---------+-------+
8 rows in set (0.01 sec)

mysql> alter table employee modify state char(30);


Query OK, 3 rows affected (0.17 sec)
Records: 3 Duplicates: 0 Warnings: 0

mysql> desc employee;


+-------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------+------+-----+---------+-------+
| employ_code | int | NO | PRI | NULL | |
| name | varchar(30) | NO | | NULL | |
| designation | varchar(30) | NO | | NULL | |
| salary | decimal(10,0) | YES | | NULL | |
| doj | date | YES | | NULL | |
| state | char(30) | YES | | NULL | |
| mobile | char(10) | YES | UNI | NULL | |
| gender | char(1) | YES | | M | |
+-------------+---------------+------+-----+---------+-------+
8 rows in set (0.01 sec)

mysql> alter table employee add aadhar_card varchar(30);


Query OK, 0 rows affected (0.03 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> desc employee;


+-------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------+------+-----+---------+-------+
| employ_code | int | NO | PRI | NULL | |
| name | varchar(30) | NO | | NULL | |
| designation | varchar(30) | NO | | NULL | |
| salary | decimal(10,0) | YES | | NULL | |
| doj | date | YES | | NULL | |
| state | char(30) | YES | | NULL | |
| mobile | char(10) | YES | UNI | NULL | |
| gender | char(1) | YES | | M | |
| aadhar_card | varchar(30) | YES | | NULL | |
+-------------+---------------+------+-----+---------+-------+
9 rows in set (0.00 sec)

mysql> alter table employee drop aadhar_card;


Query OK, 0 rows affected (0.03 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> desc employee;


+-------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------+------+-----+---------+-------+
| employ_code | int | NO | PRI | NULL | |
| name | varchar(30) | NO | | NULL | |
| designation | varchar(30) | NO | | NULL | |
| salary | decimal(10,0) | YES | | NULL | |
| doj | date | YES | | NULL | |
| state | char(30) | YES | | NULL | |
| mobile | char(10) | YES | UNI | NULL | |
| gender | char(1) | YES | | M | |
+-------------+---------------+------+-----+---------+-------+
8 rows in set (0.00 sec)

mysql> alter table employee add Constraint unique(doj);


Query OK, 0 rows affected (0.06 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> desc employee;


+-------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------+------+-----+---------+-------+
| employ_code | int | NO | PRI | NULL | |
| name | varchar(30) | NO | | NULL | |
| designation | varchar(30) | NO | | NULL | |
| salary | decimal(10,0) | YES | | NULL | |
| doj | date | YES | UNI | NULL | |
| state | char(30) | YES | | NULL | |
| mobile | char(10) | YES | UNI | NULL | |
| gender | char(1) | YES | | M | |
+-------------+---------------+------+-----+---------+-------+
8 rows in set (0.00 sec)

mysql> alter table employee drop constraint doj;


Query OK, 0 rows affected (0.02 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> desc employee;


+-------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------+------+-----+---------+-------+
| employ_code | int | NO | PRI | NULL | |
| name | varchar(30) | NO | | NULL | |
| designation | varchar(30) | NO | | NULL | |
| salary | decimal(10,0) | YES | | NULL | |
| doj | date | YES | | NULL | |
| state | char(30) | YES | | NULL | |
| mobile | char(10) | YES | UNI | NULL | |
| gender | char(1) | YES | | M | |
+-------------+---------------+------+-----+---------+-------+
8 rows in set (0.00 sec)

mysql> alter table employee rename to employ;

mysql> create table if not exists employee(code integer primary key);


Query OK, 0 rows affected, 1 warning (0.01 sec)

mysql> create table if not exists cs_12.employeee(code integer primary key);


Query OK, 0 rows affected (0.06 sec)

mysql> show tables;


+-----------------+
| Tables_in_cs_12 |
+-----------------+
| employee |
| employeee |
| student |
+-----------------+
3 rows in set (0.00 sec)
mysql> select code, name from xyz;

mysql> select * from employee where salary is null;


+-------------+------------+-------------+--------+------+-------+--------+--------+
| employ_code | name | designation | salary | doj | state | mobile | gender |
+-------------+------------+-------------+--------+------+-------+--------+--------+
| 104 | ranapratap | principal | NULL | NULL | NULL | 454584 | M |
+-------------+------------+-------------+--------+------+-------+--------+--------+
1 row in set (0.00 sec)

Interface With Python and SQL


Before integrating we must create path in environment variables so that it will connect to cmd
command prompt.
1st Steps is- Copy these paths to environment variables.
• C:\Users\DELL\AppData\Local\Programs\Python\Python313
• C:\Users\DELL\AppData\Local\Programs\Python\Python313\Scripts
nd
2 Steps is- Installing PIP in cmd command prompt.
• Install PIP
• Now type pip install mysql-connector-python.
rd
3 Steps is- Creating connecting command in python.

Import [Link] as z
conn=[Link](
... host='localhost',
... user='root',
... password=’**********')

OR- We can create MySQL connector function in python.


def mysql_connector():
... import [Link] as z
... conn=[Link](
... host='localhost',
... user='root',
... password='*********')

Cur=[Link]()
[Link](‘create database if not exists cs_13’)
[Link]()

Showing Database-
[Link]('show databases')
>>> for i in cur:
... print(i)
('cs_12',)
('cs_13',)
('information_schema',)
('mysql',)
('performance_schema',)
('sys',)

Showing Table-if exists-


conn=[Link](
... host='localhost',
... user='root',
... password='xxxxxxxxxx',
... database='cs_12'
... )
>>> cur=[Link]()
>>> [Link]("SHOW TABLES")
>>> for i in cur:
... print(i)
...
('employee',)
('employeee',)
('student',)
('zzz',)

import [Link] as z
conn=[Link](
host='localhost',
user='root',
password='Nitin@90')
cur=[Link]()
[Link]("create database if not exists naya_cs")
[Link]("use naya_cs")
[Link]('create table if not exists new(code integer primary key,name varchar(20)NOT
NULL,salary varchar(20))')
[Link]()
while True:
option=int(input("1 for insert data\n2 for select data\n3 for update data\n4 for delete
data\n5 for display all data\n6 for exit\nEnter your choice"))
if option==1:
code=int(input("enter the code"))
name=input("Enter your name")
salary=input("enter the salary")
[Link]("insert into new values({},'{}','{}')".format(code,name,salary))
[Link]()
elif option==2:
code=int(input("enter the code you want to search in data"))
[Link]("select * from new where code={}".format(code))
data=[Link]()
if [Link]==0:
print("No data found with given code")
else:
print(data)
elif option==3:
code=int(input("enter code of which you want to change values"))
salary=input("enter new updated salary")
[Link]("update new set salary='{}' where code={}".format(salary,code))
data=[Link]()
[Link]()
if [Link]==0:
print("code not found")
else:
print("data updated done")
elif option==4:
in_code=int(input("enter code of which you want to delete"))
[Link]("delete from new where code={}".format(in_code))
data=[Link]()
[Link]()
if [Link]==0:
print("code not found")
else:
print("data is deleted done")
elif option==5:
[Link]("select * from new")
data=[Link]()
if [Link]==0:
print("no data in the table")
else:
for i in data:
print(i)
elif option==6:
break
else:
print("Enter correct input as per option")
What is Computer Network?
“A computer Network is group of connected devices such as Computer, Laptop, Printers, and Scanners,
Mobiles devices, which can communicate with each other and share hardware and software resources.”

Advantages of Computer Network | Uses of Computer Network

• Resource Sharing: Computer Network allows sharing of resources such as-


• Hardware Resources: Printer, Scanner, Photocopier, CD Drive etc.
• Software Resources: ERPs, Open-Source Software etc.
• Information Sharing: File Sharing like documents, sheets, reports etc.
• Increase Storage Capacity: Usually, Server of Computer Network have large storage capacity. Total
Storage capacity of each node of Computer Network also increases storage capacity.
• Cost Efficient: Computer Networks are cost effective as we can share one resource to many.
• Collective User Interaction (Multi User Environment): Computer Network allows many users to work
together simultaneously in a project and as a result a lot of time and effort is saved.
• Improved Communication and Information availability: Due to WAN (Internet) people across different
location can instantly get and share any information at any point of time.
Evolution of Networking

Types of Computer Network


• Local Area Network
• Metropolitan Area Network
• Wide Area Network
• Personal Area Network
Local Area Network
A Local Area Network is a collection of interconnected Computers and its associated devices that are located in
a close proximity.

Characteristics of LAN
• LAN Occupies small area not more than 1-5kms.
• Usually operated or owned by single person
• Speed of data transfer is high as compare to other networks.
• Easy Installation and Maintenance
Metropolitan Area Network
A Metropolitan Area Network is a collection of interconnected Computers and its associated devices that are
located at one Geographic location such as multiple office building in a city.

Characteristics of MAN
• MAN Occupies area between 5 to 50 kilometres.
• Usually operated or owned by consortium of people or an organization provides services.
• It often acts as high-speed network.
• MAN may be public.
• Examples- Municipal Offices network, Police Station network etc.
Wide Area Network
A Wide Area Network is a collection of interconnected Computers and its associated devices that are located
at different Geographic location such as different cities, states or countries. It is a large computer network such
as two or more LANs.
Characteristics of WAN
• WAN covers very long-distance area.
• Usually operated or owned by national or multinational organizations.
• Comparatively low speed network to LAN and MAN.
• Most often WAN is public.
• Examples- National Banks, Railways, INTERNET etc.
Personal Area Network
A Personal Area Network is collection of various interconnected devices such as computers, mobile devices,
fax machines and printers available closely to an individual user.

Characteristics of PAN
• Mostly it uses Wi-Fi connectivity.
• Usually operated or owned by individuals.
• It covers distance of maximum 10-30mtr.
• Usually, PAN is private.
Network Topologies
Network Topology defines the layout or structure of a Computer Network that defines the pattern of all
devices connected to each other.

Types of Topologies-
There are 5 basic Network Topologies:
• Star
• Bus or Linear
• Ring (Circular)
• Tree
• Mesh
Star Topology
It is one of the most used topologies. In a star topology, nodes are not connected to each other, instead are
connected to a central device called hub or switch. Information sent by a computer is received by hub/switch,
which than determines which node that data needs to send.

Advantages of Star Topology


• It is less expensive.
• Easy to install and update
• Easy troubleshooting
• Robust network
• Easy to add new node
Disadvantages of Star Topology
• If central device (hub/switch) fails, entire network goes down.
• Performance of entire network depends upon central device.
• Needs long cable to connect each node to central device.
Bus (linear) Topology
It is one of the simplest topologies used for network. In bus topology, all the nodes are connected to each
other through a single cable generally called ‘backbone’.
Information transmitted by a node reach to all the nodes connected to network, but information is processed
or taken only by that node which address is matched with address contained within information.

Advantages of Bus (linear) Topology


• It is very simple to design and install.
• less caballing is required as compared to other topologies.
• Best suited for small network (LAN).
• Very cost effective.
• easily expandable.
Disadvantages of Bus (linear) Topology
• Not suitable for large network.
• If cable (backbone) is failed, entire network goes down.
• though its design is simple, it is difficult to diagnose the fault.
• data loss is high
• slow network
Ring (Circular) Topology
In Ring or Circular topology all connected nodes form a circular path. Each node is connected to its two
neighbouring nodes.
In this topology Information sent by a node transmits from one node to another node until it reaches to
destination node. Usually, data is transmitted in half duplex mode in this topology but it can be duplex mode.

Advantages of Ring (Circular) Topology


• No need of Server control for data transmission.
• Data collision rate is very low as data travels unidirectionally.
• Easy maintenance and troubleshooting
• High Speed Communication Network.
• Each node has equal access to resources
Disadvantages of Ring (Circular) Topology
• Failure of any node may cause entire network down.
• Less secured network
• Slower than star topology
• Expensive network as it uses expensive components to establish the network.
Tree Topology
It is popularly called Star-Bus Topology which is not so commonly used. Devices at lower level are connected to
devices at next higher level, which resembles a tree like structure. At higher levels of the tree, often point-to-
point or point-to-multipoint connections are used.
It creates Parent-child hierarchy as there can be only one connection between two nodes and two nodes can
have only one mutual connection.

Advantages of Tree Topology


• It is most suitable for large networks.
• Failure of any node does not affect network communication.
• It is Flexible network because new node can be added easily without interrupting whole network.
• Large community for support.
• It provides highly secured network.
Disadvantages of Tree Topology
• It depends upon central cable (backbone), which if fails may stop working of entire network.
• Higher level node failure may affect next level node performance.
• More expensive and complex network.
• Tough maintenance due to large no of components and cables.
Mesh Topology
In Mesh topology, all the nodes are connected to every other node individually. Each node is capable to send
and receive information to and from another node. Generally, Mesh topology does not implement any central
Server/Switch/Hub.
The connections in Mesh topology can be Wired or Wireless.

Advantages of Mesh Topology


• It can manage high amount of traffic easily.
• Robust Network as failure of any node does not affect entire network communication.
• New node can be added easily without interrupting network communication.
• Scalable Network as there is no central Server/Hub/Switch/Router. Each node can act as router.
• It provides high security and privacy.
Disadvantages of Mesh Topology
• Complex network as each node is connected to every other node and hence needed many
connections.
• Consumes more power as each node is treated as router and a result it is active for all time.
• Difficult Installation and Maintenance due to its complexity.
• Expensive Network.
Networking Devices
• Hub
• Switch
• Router
• Gateway
• Repeater
• Ethernet Card
• Modem
Hub
• A hub is hardware networking device that connects multiple nodes in a network and send and receive
data from all the connected nodes.
• A hub contains multiple ports that are used to connect multiple nodes.
• A hub is best suitable device for creating small home network (LAN).
• A hub transmits data in half duplex mode.
• A hub primarily broadcasted messages. It means that the data received by hub is sent to all the
computers connected with it.
• A hub is considered to be dumb network device. It means that it is not able to filter message and send
to selected destination port
• A hub is passive device. It is not equipped with any network software.

Switch
• A switch is a hardware networking device that connects multiple nodes, receives information from all
nodes, and sends it only to the selected node.
• A switch has multiple ports to connect with multiple nodes.
• A switch is called intelligent hub as it analyses and receives data and send it to intended node.
• A switch transmits data in duplex mode.
• A switch uses MAC Address to send data to selected node.
• A switch is active device. It is equipped with network software.

Router
• A router is a hardware networking device that connects multiple physical networks that follows
different protocols.
• A router is responsible for receiving, analysing and moving incoming data packets to another network.
• A router ensures that packets are travelling the most efficient paths to their destinations based on data
properties.
• A router is best suitable for WAN (Internet).
• Link failure between routers does not stop network. If a link fails between two routers, the sending
router determines an alternate route to keep traffic moving.

Gateway
• A gateway is a node considered as the entrance point to other networks, so that different networks can
communicate with each other.
• It connects different network follows different protocols and different properties.
• Gateway can be any software, hardware, or combination of both.
• Gateway can act as a proxy server or firewall.
• Generally, Router is used as Gateway device in Computer Network.
Repeater
• Repeater is used to boost strength of a signal being transmitted on a network.
• Repeater is generally used in long distance network where chances of signal loss is more.
• Repeater copy the weak signals and regenerate it with full strength.
• Repeater are used to connect similar networks.
• Repeaters are cost effective and do not require any processing overhead.

Ethernets Card
• Also known as by many names like- Internal Network Card, Network Adapter, Network Interface Card
(NIC) or LAN Card.
• It establishes a physical connection between Computer and a Network.
• It acts as an interface between Computer and a Network where it converts electrical signals received
from a network to digital signal that computer understood.
• Now a days it is inbuilt in motherboard of Computer, laptop. We can also mount it separately in
motherboard in case of failure of pre-installed card.

Modem
• Modem refers to Modulator Demodulator.
• It converts Internet Signals (Analog) into digital signals (computer signals) and vice versa.
• To connect with Internet Modem plays the most important role.
• Modem is also of two types
• Internal- which is pre-installed in computer motherboard.
• external- which is external device can be connected to computer.
• converting analog signals to digital signal is called demodulation.
• converting digital signals to analog signal is called modulation.

RJ45
• RJ45, also called Registered Jack-45is an eight-pin connector that is used exclusively with Ethernet
cables for networking.
• It is a small plastic plug that fits into jack given in Ethernet card present in CPU
Wifi Card
• A Wi-Fi card is used to connect your computer to a particular Wi-Fi network.
• It is connected in either USB port or card slot present in motherboard of Computer.
• It can work as both a receiver or transmitter.

Internet and Web Services


What is Internet?
“Interconnected Network”
Internet is independent global network system of countless computers and electronic devices scattered
around the globe connected to each other wirelessly or wirely with the help of various devices such as
satellite, routers, wires, and modems, for sharing information and communicating with each other.
World Wide Web
World Wide Web popularly called ‘Web’ is a leading information sharing service of the Internet, which was
developed by Tim Berners Lee in 1989 to give user access to wide range of documents that are connected to
each other by hyperlink and written in HTML.
• Content of HTML documents can be any text, graphics, audio, or video.
• Every HTML Document is can be accessed by its unique address known as URL
• To read HTML Documents Web Browser is used.
• HTTP is used to transfer documents from Server to Client.
Difference between Internet and WWW

Internet WWW

Internet is primarily hardware based WWW is primarily software based

Internet is networking infrastructure that connects WWW is collection of information that can be access
devices together through Internet

Internet uses TCP/IP for communication WWW uses HTTP/HTTPS for communication

HTML (Hypertext Markup Language)


• HTML or Hypertext Markup Language is basically used to design and format a web page.
• HTML were developed by Tim Berner Lee in 1991
• HTML contains different tags putted inside <> used in designing web page.
• Ideally it is a formatting language not a programming language.
Website
A website is collection of web pages which can be interlinked with each other, hosted on a web server, and
written using HTML.
URL
A URL stands for Uniform Resource Locator also referred to as web address is a unique identifier used to
specify unique address of a website. For example, [Link]
Components of URL:
• Protocol
• Name or Address of Server
• Location of File on Server

Domain Names
• Domain name is referred as the name given to a website hosted in computer server, so that it can be
accessed over the Internet.
• Domain names also called hostnames is given against IP address of computer server hosting website.
Web Server
Web Server: A web server is a computer used to store and respond to web related request. It handles HTTP
request and delivers web pages.
• Web Server is used for Web hosting or hosting for website or web application.
• Web Server can also support FTP and SMTP.
• A Web Server may consist of Hardware and Software both.
• Web Server hardware is basically a computer which stores Web Server software and content related to
website such as text, images, html and CSS code, script code, audio/video files etc.
• Web Server software are programs that accept http request from web browser and respond those
requests.
Web Hosting
Web hosting is a service that provide resources such as CPU, RAM, Storage, connection, and necessary services
to store, manage and serve a website or application in Internet and make it part of www. Once a website or
application is hosted, it can be accessed from any computer connected to Internet.
Web Browser
A Web browser is an application software which enable us to view information available in Internet. It displays
information retrieved from web server in HTML format.
Examples-
• Google Chrome
• Mozilla Firefox
• Internet Explorer
• Opera

Common questions

Powered by AI

User-defined functions in Python encapsulate code for reuse, enhancing readability and manageability by breaking problems into modular, reusable components. They promote DRY (Don't Repeat Yourself) principles, reducing errors and improving maintenance ease. Functions can be easily tested and debugged independently, fostering robust development practices. However, if improperly implemented—such as by creating overly complex functions, not handling exceptions, or failing to adhere to clear naming conventions—functions can reduce code clarity and increase technical debt . A balanced approach to design ensures usability without sacrificing simplicity or functionality, emphasizing clear, purposeful interfaces and cohesive behavior.

Loops and conditionals in Python provide the foundation for constructing control flows that can effectively handle errors and maintain concise code. Python's try-except blocks can be integrated within loops to catch and manage exceptions without halting execution, thus supporting dynamic error handling. Conditional structures like if-else can assess execution paths or validate loop iterations, catering to the program’s logic needs. Python’s unique for-else structure also aids in control flow by executing the 'else' branch only if the loop completes normally, thereby allowing for checks like absence conditions and validation continuity. Leveraging these structures supports cleaner code by minimizing boilerplate and focusing directly on logic handling, making Pythonic code more readable and maintainable . Efficient use of these constructs is crucial for writing robust, secure applications.

Bubble sort is an O(n^2) algorithm most effective for educational purposes or when dealing with small datasets, owing to its simple implementation but inefficiency with larger data. Python's list comprehension, by contrast, is an idiomatic, succinct way to filter and transform data within a list. It is more efficient for applicable operations as it exploits Python's iteration protocol and is optimized for readability and compactness. While bubble sort transforms a data set by sorting it, list comprehension allows for inline operations like filtering or applying functions, taking advantage of Python's expressive syntax . Use cases for bubble sort are limited in practical applications, whereas list comprehensions are extensively used for data manipulation and transformation.

In Python, the IF-Else statement is used for making a simple decision based on a condition; if the condition is true, one block of code is executed, otherwise another block of code runs. For example, checking if a price is greater than 1000 to decide on a purchase. Nested-IF-Else allows for more complex decision-making where further conditions can be checked within an IF or an ELSE clause. This is helpful when you need to make decisions based on more than one condition, such as determining an appropriate response based on a range of prices: prohibitively high for prices over 5000, manageable for prices less than 2000, and a default action otherwise . Practical scenarios for basic IF-Else might include simple binary decision points, whereas Nested-IF-Else is useful in situations involving tiered decision-making, like setting the priority of tasks based on multiple criteria.

Maintaining and updating database records with SQL involves using commands like 'INSERT', 'UPDATE', and 'DELETE'. 'INSERT' adds new records, 'UPDATE' modifies existing ones, and 'DELETE' removes them. Maintenance is crucial for ensuring data accuracy and relevance over time. The 'UPDATE' command allows changes to specific rows where conditions are met, while 'ALTER TABLE' can adjust the structure. Using these commands properly ensures databases remain organized, minimizing redundancy and enhancing query performance . Regular updates reflecting real-world data adjustments maintain the application’s functionality and effectiveness.

Fixed length strings ('char') in SQL can enhance performance because the database can predictably allocate space, leading to faster processing. However, this can lead to inefficiencies, as spaces remain occupied even if not needed by the data. Variable length strings ('varchar'), on the other hand, adjust their storage based on data needs, which saves space but incurs a processing cost due to the necessity to manage dynamic sizes. This impacts database design significantly; opting for fixed length strings helps in scenarios with consistent data sizes and performance critical operations while variable length strings are more suitable for fields with diverse and unpredictable data lengths . The choice between them depends on balancing between speed and space efficiency.

In Python, a 'for-else' loop allows the 'else' block to execute if the loop completes without a 'break'. The 'break' statement can be used to exit the loop prematurely, preventing the 'else' from executing. Conversely, the 'continue' statement skips the current iteration but allows the loop to continue. Using for-else with 'break' can efficiently handle scenarios where you want to check a condition across the loop and execute additional code if no 'break' occurs, such as searching for an item in a list and handling it if not found. This pattern is advantageous when the normal iterator conclusion affects subsequent logic, thus differing from traditional loops that may need additional flag variables or wrap-around logic to achieve the same outcomes . This can result in cleaner, more expressive code for specific conditions.

In SQL, constraints like 'primary key' and 'unique' are foundational elements that enforce rules on data types to maintain integrity. A 'primary key' uniquely identifies each row, ensuring that no duplicates exist and each entry can be easily referenced. The 'unique' constraint similarly prevents duplicate values in a column, enforcing data uniqueness without requiring it to be the primary key. These constraints guarantee data validity and uniqueness, protect against corruption, and support efficient indexing, which enhances query performance. By defining these rules at the database level, constraints help ensure consistent data quality, which is crucial in complex data environments . They provide a robust structure that supports application logic and enhances system reliability.

Altering an existing SQL table structure can involve adding, deleting, renaming columns, or changing their data types with commands like 'ALTER TABLE'. Modifications can affect the database's structure significantly: changing a column's data type might require data conversion, adding constraints (e.g., primary keys) influences data integrity and indexing, and renaming columns can impact application code that interacts with the database. These operations must be carefully planned and executed to maintain the integrity and performance of the database; unprepared changes might lead to data loss or inconsistent states. Ensuring data integrity involves thorough testing and possibly data migration to conform to new structure rules . Often, modifications are part of a larger database optimization or refactoring effort.

Stacks operate on a Last-In-First-Out (LIFO) principle, meaning the last element added is the first one removed. Basic operations include 'Push', adding an element to the top, and 'Pop', removing the top element. This contrasts with lists, which allow insertion and deletion at any position, making them more flexible for non-linear access patterns. In a stack implemented as an array or linked list, 'Push' adds an element at the end (or beginning in some implementations), and 'Pop' removes the element from the top (or the corresponding position). Lists, being versatile, do not enforce LIFO order and instead offer index-based access and manipulation . Operations in a stack are generally more linear and predictable due to their inherent structure, which suits specific algorithmic tasks like expression evaluation or tracking function calls.

You might also like