0% found this document useful (0 votes)
55 views

Micro Cheat Sheet

The document provides a comprehensive overview of Python programming concepts, including functions, exception handling, file operations, and data structures like stacks. It also covers basic SQL commands for managing databases, including creating tables, inserting data, and querying information. Additionally, it touches on networking concepts and their topologies, highlighting the roles of different network devices.

Uploaded by

aamir190921
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)
55 views

Micro Cheat Sheet

The document provides a comprehensive overview of Python programming concepts, including functions, exception handling, file operations, and data structures like stacks. It also covers basic SQL commands for managing databases, including creating tables, inserting data, and querying information. Additionally, it touches on networking concepts and their topologies, highlighting the roles of different network devices.

Uploaded by

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

YouTube: Ni n Paliwal YouTube: Ni n Paliwal

4. Func on Returning Values 4. Mul ple Excep ons


Cheatsheet 1: Python Cheatsheet 2:  Handle mul ple excep ons in one
# Example
block.
Func ons def square(x): Excep on Handling in try:
return x * x
# Code that may raise mul ple excep ons
1. Types of Func ons result = square(4) Python except (ValueError, TypeError):
Type Descrip on Example print(result) # Output: 16
print("Caught a ValueError or TypeError")
Predefined 1. Introduc on to Excep on Handling
len(), print(), 5. Flow of Execu on
Built-in func ons in  Excep on: An error detected during 5. Raising Excep ons
type() 1. The func on is defined but not
Python execu on (e.g., ZeroDivisionError,  Use raise to trigger an excep on
executed when encountered.
Func ons FileNotFoundError). manually.
User- 2. Func on is executed only when called.
created by the def greet():  Why Handle Excep ons? To prevent raise ValueError("This is a custom error
defined 3. Parameters are assigned to arguments
user program crashes and handle errors message.")
at the me of the call.
gracefully.
Func ons 4. Execu on starts from the first line of
Module math.sqrt(), 6. Using else Clause
defined in the func on.
Func ons random.randint() 2. Handling Excep ons  Executes if no excep on occurs.
libraries/modules
Basic Syntax try:
6. Scope of Variables
try: num = int(input("Enter a number: "))
2. Crea ng a Func on # Code that may raise an excep on except ValueError:
Type Descrip on Example
# Syntax except Excep onType: print("Invalid input!")
def func on_name(parameters): Declared inside a Declared
# Code to handle the excep on else:
# Func on body Local func on, accessible within def
finally: print("Valid input!", num)
return value only within func():
# (Op onal) Code that executes no ma er
# Example Declared outside all Declared what 7. Custom Excep ons
def add(a, b): Global func ons, accessible outside any Example  Define user-defined excep ons by
return a + b everywhere func on try: inheri ng from Excep on.
print(add(3, 5)) # Output: 8 Example: num = int(input("Enter a number: ")) class CustomError(Excep on):
x = 10 # Global print(10 / num) pass
3. Parameters and Arguments def func(): except ZeroDivisionError: try:
Descrip o x = 5 # Local print("Cannot divide by zero!") raise CustomError("Something went
Type Example
n print(x) # Output: 5 except ValueError: wrong!")
Posi ona Matched func() print("Invalid input! Please enter a except CustomError as e:
add(3, 5) print(x) # Output: 10 number.") print(e)
l by posi on
finally:
Matched
Keyword add(a=3, b=5) print("Execu on complete.")
by name
Default 3. Common Excep ons
def
value if no Excep on Type Descrip on
Default greet(name="Guest")
argument
: ZeroDivisionError Division by zero
is provided
ValueError Invalid value (e.g., int("abc"))
Arbitrary
arguments FileNotFoundError File not found
Variable-
using *args def add(*nums): IndexError Index out of range
length
or
KeyError Key not found in a dic onary
**kwargs
Opera on on incompa ble
TypeError
types

YouTube: Ni n Paliwal YouTube: Ni n Paliwal

5. Wri ng/Appending to a Text File Reading a CSV File


Cheatsheet 3: File Descrip o
Cheatsheet 4: File import csv
Method Example
Handling (Text Files) n
Writes a
Handling (Binary and with open("data.csv", "r") as file:
reader = csv.reader(file)
1. File Types write()
single
string to
file.write("Hello,
World!\n")
CSV Files) for row in reader:
Type Descrip on the file print(row)
Stores data in human-readable text 1. Binary File Opera ons Wri ng to a CSV File
Text Writes a
format Key Points import csv
writelines list of file.writelines(["Line1\
 Stores data in binary format (non-
Stores data in a non-readable binary () strings to n", "Line2\n"])
Binary human-readable). # Wri ng rows to a CSV file
format the file
 Use the pickle module for binary file with open("data.csv", "w", newline="") as file:
opera ons. writer = csv.writer(file)
2. File Modes 6. File Pointer Methods File Modes writer.writerow(["Name", "Age", "City"])
Mode Descrip on Method Descrip on Example Mode Descrip on writer.writerows([
r Read-only mode (default) Returns current ["Alice", 30, "New York"],
pos = rb Read binary mode
w Write mode (creates/overwrites file) tell() posi on of the file ["Bob", 25, "Los Angeles"]
file.tell() wb Write binary mode
pointer ])
Append mode (adds to file without
a Moves file pointer ab Append binary mode Working with Dic onary-based CSV
overwri ng) file.seek(0)
seek(offset) to a specific rb+ Read and write binary mode import csv
r+ Read and write mode (start of file)
posi on wb+ Write and read binary mode
w+ Write and read mode # Wri ng CSV with dic onary
a+ Append and read mode ab+ Append and read binary mode with open("data.csv", "w", newline="") as file:
7. Example: Complete Workflow
Example: Wri ng and Reading Binary Files fieldnames = ["Name", "Age", "City"]
# Wri ng to a file
3. Basic Opera ons on Text Files import pickle writer = csv.DictWriter(file,
with open("example.txt", "w") as file:
Opening a File fieldnames=fieldnames)
file.write("Hello, World!\n")
file = open("example.txt", "r") # Wri ng to a binary file
Closing a File with open("data.bin", "wb") as file: writer.writeheader()
# Reading from the file
file.close() data = {"name": "John", "age": 25} writer.writerow({"Name": "Alice", "Age": 30,
with open("example.txt", "r") as file:
Using with Clause pickle.dump(data, file) "City": "New York"})
print(file.read())
 Automa cally closes the file a er # Reading from a binary file writer.writerow({"Name": "Bob", "Age": 25,
usage. with open("data.bin", "rb") as file: "City": "Los Angeles"})
# Appending to the file
with open("example.txt", "r") as file: data = pickle.load(file)
with open("example.txt", "a") as file:
data = file.read() print(data) # Output: {'name': 'John', 'age': # Reading CSV with dic onary
file.write("Appending more data!\n")
25} with open("data.csv", "r") as file:
4. Reading from a Text File reader = csv.DictReader(file)
2. CSV File Opera ons for row in reader:
Method Descrip on Example
Key Points print(row)
Reads the en re data =  Stores tabular data in a text file
read()
file content file.read() format (comma-separated values).
Reads one line at line =  Use the csv module for reading and
readline()
a me file.readline() wri ng CSV files.
Reads all lines as lines = File Modes
readlines()
a list of strings file.readlines() Mode Descrip on
r Read CSV file
w Write CSV file (overwrites)
a Append to CSV file
YouTube: Ni n Paliwal YouTube: Ni n Paliwal

return self.stack[-1]
Cheatsheet 5: Python Cheatsheet 6: SQL
Sor ng Results (ORDER BY Clause)
else: SELECT * FROM Students ORDER BY Marks DESC;
return "Stack is empty"
Data Structures Basics and Queries 5. Aggregate Func ons
def is_empty(self): Func on Descrip on Example
(Stacks) return len(self.stack) == 0 1. SQL Overview
MAX()
Returns the SELECT MAX(Marks)
 Structured Query Language (SQL): Used highest value FROM Students;
1. Introduc on to Stacks def size(self): to manage and query rela onal Returns the SELECT MIN(Marks)
databases. MIN()
 Defini on: A stack is a linear data return len(self.stack) lowest value FROM Students;
 Key SQL Categories:
structure following the LIFO principle Returns the SELECT AVG(Marks)
o DDL: Data Defini on Language AVG()
(Last In, First Out). # Example Usage average value FROM Students;
(e.g., CREATE, DROP, ALTER)
 Applica ons: s = Stack() Returns the sum SELECT SUM(Marks)
o DML: Data Manipula on SUM()
o Undo opera ons s.push(10) of values FROM Students;
Language (e.g., SELECT, INSERT,
o Backtracking (e.g., browser s.push(20) UPDATE, DELETE) Returns the SELECT COUNT(*)
COUNT()
history) print(s.pop()) # Output: 20 number of rows FROM Students;
o Expression evalua on (e.g., print(s.peek()) # Output: 10 2. Common SQL Commands
pos ix, infix) Command Descrip on 6. Joining Tables
4. Opera ons on Stack (Push and Pop) Example: Inner Join
CREATE Creates a new table or database
SELECT Students.Name, Courses.CourseName
2. Stack Opera ons Push Opera on INSERT Adds new data to a table FROM Students
Opera on Descrip on 1. Add the item to the end of the list. SELECT Retrieves data from a table INNER JOIN Courses
Add an item to the top of the stack = [] ON Students.StudentID = Courses.StudentID;
UPDATE Modifies exis ng data in a table
push(item) stack.append(5) # Push 5 to stack
stack DELETE Removes data from a table Other Joins
Pop Opera on Type Descrip on
pop() Remove and return the top item DROP Deletes a table or database
1. Remove the last item added to the
View the top item without ALTER Modifies the structure of a table Returns matching rows from both
list. INNER JOIN
peek() tables
removing it item = stack.pop() # Pop from stack
3. Crea ng and Managing Tables Returns all rows from the le
is_empty() Check if the stack is empty LEFT JOIN
Create Table table
Return the number of items in Returns all rows from the right
size() CREATE TABLE Students (
the stack RIGHT JOIN
StudentID INT PRIMARY KEY, table
Name VARCHAR(50), FULL OUTER
Returns all rows from both tables
3. Implemen ng Stack Using a List Age INT, JOIN
Code Example Marks FLOAT
class Stack: ); 7. Inser ng, Upda ng, and Dele ng Data
def __init__(self): Modify Table (ALTER) Insert Data
 Add a column: INSERT INTO Students (StudentID, Name, Age,
self.stack = []
ALTER TABLE Students ADD Address Marks)
VARCHAR(100); VALUES (1, 'Alice', 20, 85.5);
def push(self, item):
 Drop a column: Update Data
self.stack.append(item) ALTER TABLE Students DROP COLUMN Address; UPDATE Students
Delete Table SET Marks = 90
def pop(self): DROP TABLE Students; WHERE StudentID = 1;
if not self.is_empty(): Delete Data
return self.stack.pop() 4. Querying Data (SELECT) DELETE FROM Students WHERE StudentID = 1;
else: Basic Syntax
return "Stack is empty" SELECT column1, column2 FROM TableName;
Example
SELECT Name, Marks FROM Students;
def peek(self):
Filtering Results (WHERE Clause)
if not self.is_empty():
SELECT * FROM Students WHERE Age > 18;

YouTube: Ni n Paliwal YouTube: Ni n Paliwal

6. host="localhost",
Cheatsheet 7: 7. user="root", Cheatsheet 8: Switch
Connects devices in a LAN and uses MAC
addresses to forward data.
8. password="yourpassword", Broadcasts data to all connected devices in a
Advanced SQL and 9.
10. )
database="school"
Networking Concepts Hub
network.
Gateway Connects networks with different protocols.
Python-SQL
11.
cursor = conn.cursor() 1. Key Networking Concepts
12. Execute Queries: Term Defini on 5. Network Topologies

Connec vity o Create a Table:


o cursor.execute("""
Computer A system of interconnected devices Topology Structure
Single cable
Advantages
Simple and
Disadvantages
Network that can share resources and data.
o CREATE TABLE Students ( Failure in cable
Transfer of data between devices Bus connects all cost-
1. Advanced SQL Commands o StudentID INT PRIMARY KEY, Data affects network.
using transmission media and devices. effec ve.
Group Data (GROUP BY) o Name VARCHAR(50), Communica on
 Purpose: Group rows sharing a property and protocols. Devices Easy to Hub failure
o Age INT,
Unique iden fier assigned to a Star connected to add/remove disconnects
perform aggregate calcula ons. o Marks FLOAT IP Address a central hub. devices. network.
SELECT Age, COUNT(*) )""") device on a network.
FROM Students o Insert Data: Maximum data transfer rate of a Hierarchical
Scalable and
GROUP BY Age; o cursor.execute(""" Bandwidth network (measured in Mbps, Gbps, Tree star-bus Complex setup.
structured.
Filter Groups (HAVING) o INSERT INTO Students (StudentID, etc.). structure.
 Purpose: Apply condi ons on aggregated data. Name, Age, Marks)
SELECT Age, COUNT(*) o VALUES (1, 'Alice', 20, 85.5) 2. Evolu on of Networking 6. Protocols
FROM Students o """) Protocol Func on
Phase Descrip on
GROUP BY Age conn.commit()
First network (1969); founda on for modern Transfers web pages. HTTPS adds
HAVING COUNT(*) > 2; o Fetch Data: ARPANET HTTP/HTTPS
internet. encryp on.
Aliasing o cursor.execute("SELECT * FROM
Students;") Expanded academic networking capabili es FTP Transfers files.
 Purpose: Rename columns or tables for clarity. NSFNET
SELECT Name AS StudentName, Marks AS Score o for row in cursor.fetchall(): in the 1980s. SMTP Sends emails.
FROM Students; print(row) Global network for communica on, Core protocol suite for internet
13. Close Connec on: Internet TCP/IP
Pa ern Matching (LIKE) introduced in the 1990s. communica on.
Pa ern Matches conn.close()
POP3 Retrieves emails from server.
%a Ends with "a" 3. Transmission Media Enables voice communica on over IP
4. Handling Parameters in SQL Queries VoIP
Wired Media networks.
a% Starts with "a"  Use placeholders for safer queries.
Type Descrip on Example
%a% Contains "a" sql = "INSERT INTO Students (StudentID, Name, Age,
Marks) VALUES (%s, %s, %s, %s)" Twisted Pairs of insulated copper 7. Web Concepts
_a% Second le er is "a" Telephone lines
values = (2, 'Bob', 19, 75.0) Pair Cable wires twisted together. Term Defini on
SELECT * FROM Students WHERE Name LIKE 'A%';
cursor.execute(sql, values) Co-axial Central conductor Cable TV Collec on of web pages hosted on
NULL Handling WWW
conn.commit() Cable surrounded by insula on. connec ons servers.
SELECT * FROM Students WHERE Marks IS NULL;
SELECT * FROM Students WHERE Marks IS NOT NULL; Fiber-Op c Uses light for high-speed Internet Markup language for structuring web
5. Common Errors and Solu ons Cable data transmission. backbones HTML
content.
2. Joins and Advanced Queries Error Reason Solu on Wireless Media XML Markup language for data representa on.
Natural Join Verify Type Descrip on Example
Incorrect host or Domain
 Automa cally matches columns with the same Connec onError
creden als
connec on
Long-range Name
Human-readable address of a website.
name. parameters Radio Waves FM Radio
communica on. URL Full address of a resource on the internet.
SELECT * FROM Students NATURAL JOIN Courses; Syntax error in SQL Check SQL
ProgrammingError Line-of-sight Satellite Hosts websites and handles HTTP
Subqueries query syntax Microwaves
communica on. networks Web Server
 Query inside another query. requests.
Viola on of
SELECT Name FROM Students Validate data Infrared Short-range Remote Web Service to make websites accessible over
IntegrityError primary/foreign
WHERE Marks > (SELECT AVG(Marks) FROM Students); integrity Waves communica on. controls Hos ng the internet.
key
Database not Ensure 4. Network Devices
3. Python and SQL Connec vity
Opera onalError found or database exists
Steps to Connect Python with MySQL Device Func on
inaccessible and is running
1. Install MySQL Connector: Converts analog signals to digital and vice
pip install mysql-connector-python Modem
versa for internet access.
2. Import Connector and Connect to Database:
Connects mul ple networks and directs data
3. import mysql.connector Router
packets.
4.
5. conn = mysql.connector.connect(
YouTube: Ni n Paliwal

Clauses: WHERE, GROUP BY, HAVING,


Cheatsheet Summary: 
ORDER BY.
Joins: Combine rows from tables:
Class 12 Computer 
o Natural Join: Matches
columns with the same name.
Science o Subqueries: Nested queries.

1. Python Func ons 5. Python-SQL Connec vity


 Defini on: Reusable blocks of code.  Steps:
 Types: Built-in, User-defined. 1. Install and import
 Key Points: mysql.connector.
o Posi onal vs Default 2. Connect to DB using
Parameters. connect().
o global vs local scope. 3. Execute queries using
o Syntax: cursor.execute().
o def func_name(params): 4. Fetch results using fetchone()
o # Func on body or fetchall().
return value 5. Close connec on using
conn.close().
2. Excep on Handling
 Purpose: Handle run me errors. 6. Networking Concepts
 Syntax:  Media:
 try: Type Examples
 # Risky code
Wired Fiber-op c, Coaxial
 except Excep onType:
 # Handle error Wireless Radio, Infrared
 finally:  Topologies: Star, Bus, Tree.
# Cleanup (op onal)  Devices: Router, Switch, Hub.
 Protocols:
3. File Handling Protocol Purpose
 Text Files: Read/Write using read(), HTTP/HTTPS Web communica on
write(), with open().
FTP File transfer
 Binary Files: Use pickle for
serializa on. SMTP Email sending
 CSV Files: Use csv.reader and
csv.writer. Final Tip
 Modes: Focus on commonly asked areas:
Mode Descrip on  SQL Queries.
 Python Func ons and Excep on
r Read
Handling.
w Write  File Opera ons.
a Append  Networking Protocols and Topologies.

4. SQL Basics
 DDL: CREATE, DROP, ALTER.
 DML: SELECT, INSERT, UPDATE,
DELETE.

You might also like