Python Programming Basics and Concepts
Python Programming Basics and Concepts
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
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’)
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)
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")
""" 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')
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
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
Another example-
def test8(**dict):
... return dict
test8(a='nitin', b= 'cousre', c='python')
o/p {'a': 'nitin', 'b': 'cousre', 'c': 'python'}
Example- l=[23,43,233,44]
Def sq(x):
Return x**2
Map(sq, l)
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])
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']
File size-
import os
>>> [Link]("[Link]")
28
To remove file
[Link]("[Link]")
Rename a file-
[Link]("[Link]", "[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="")
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.
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
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'
a=5
>>> b=3
>>> c=3
>>> a/(b-c)
>>> try:
... a/(b-c)
... except:
... print("error aa gya h")
...
error aa gya h
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")
Algorithms are a way of working with data in a computer and solving problems like sorting,
searching, etc.
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).
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")
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.
Students Teacher
Computer Nitin
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
DDL- Data Definition Language- The commands that deals with defining database. Related to
structure of table.
E.g. Create, Alter, Drop etc.
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.
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.
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
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.
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.
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)
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 not between 15000 and 23000;
mysql> insert into employee values(3, "rohit", "Peon", "10600", "2024-05-03", "Mumbai",
"8888888888", "M");
Query OK, 1 row affected (0.01 sec)
Drop command------ it deletes all data along with structure of the table.
Syntax- drop table employee;
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',)
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.”
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.
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 WWW
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
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
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.