Python & SQL Cheat Sheet (One-
Day Revision)
1. Getting Started with Python
Interpreted, dynamically typed language.
Variables: No need to declare type (x = 5).
Basic I/O:
Data Types: int, float, str, bool, list, tuple, dict, set.
Type Conversion:
2. Python Programming Fundamentals
Operators:
OperatorMeaning+Addition-Subtraction*Multiplication/
Division%Modulus//Floor Division**Exponentiation
Comparison Operators: ==, !=, >, <, >=, <=.
Logical Operators: and, or, not.
Membership Operators: in, not in.
3. Conditional and Looping Constructs
Conditional Statements
x = 10
if x > 5:
print("Greater than 5")
elif x == 5:
print("Equal to 5")
else:
print("Less than 5")
Loops
Loops in Python
1. While Loop (Runs until a condition is False)
python
CopyEdit
x=5
while x > 0:
print("Counting down:", x)
x -= 1 # Decrease x by 1
1.
Explanation:
2.
The loop runs as long as the condition (x > 0) is True.
o
o
Each iteration, x decreases by 1, and when x = 0, the
loop stops.
1.
2. For Loop (Runs a fixed number of times)
2.
python
CopyEdit
for i in range(5):
print("Iteration:", i)
1.
Explanation:
2.
range(5) generates values 0, 1, 2, 3, 4.
o
o
The loop executes once for each value in the range.
1.
3. For Loop with Lists
2.
python
CopyEdit
fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits:
print("Fruit:", fruit)
1.
Explanation:
2.
Loops through each item in the list and prints it.
1.
4. Nested Loops (Loop inside a loop)
2.
python
CopyEdit
for i in range(3):
for j in range(2):
print(f"Outer loop {i}, Inner loop {j}")
1.
Explanation:
2.
The inner loop runs completely for each outer loop
iteration.
o
o
Output:
1.
5. Loop Control Statements
2.
break → Stops the loop immediately.
o
o
continue → Skips the current iteration and moves to
the next.
o
o
pass → Does nothing, acts as a placeholder.
python
CopyEdit
for i in range(5):
if i == 3:
break # Stops loop when i is 3
print(i)
for i in range(5):
if i == 2:
continue # Skips when i is 2
print(i)
for i in range(5):
pass # Placeholder, loop does nothing
4. Lists in Python
Lists in Python
A list is a collection of items stored in a single variable. It can
contain integers, floats, strings, or even other lists. Lists are
mutable (can be changed after creation).
1. Creating a List
fruits = ["Apple", "Banana", "Cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "Hello", 3.14, True]
empty_list = []
Lists can have different data types
Empty lists can be created using [] or list()
2. Accessing List Elements
fruits = ["Apple", "Banana", "Cherry"]
print(fruits[0]) # Apple
print(fruits[1]) # Banana
print(fruits[-1]) # Cherry (Negative index accesses from end)
Indexing starts from 0
Negative indexing allows access from the end (-1 for last
item, -2 for second last, etc.)
3. Slicing a List
numbers = [10, 20, 30, 40, 50, 60]
print(numbers[1:4]) # [20, 30, 40]
print(numbers[:3]) # [10, 20, 30] (From start to index 3)
print(numbers[3:]) # [40, 50, 60] (From index 3 to end)
print(numbers[::2]) # [10, 30, 50] (Every second element)
print(numbers[::-1]) # [60, 50, 40, 30, 20, 10] (Reversed list)
4. Modifying Lists
Changing Elements
fruits = ["Apple", "Banana", "Cherry"]
fruits[1] = "Mango" # Changes Banana to Mango
print(fruits) # ['Apple', 'Mango', 'Cherry']
5. Adding Elements to a List
Using append() (Adds at the end)
fruits.append("Orange")
print(fruits) # ['Apple', 'Mango', 'Cherry', 'Orange']
Using insert() (Adds at a specific position)
fruits.insert(1, "Grapes") # Adds 'Grapes' at index 1
print(fruits) # ['Apple', 'Grapes', 'Mango', 'Cherry', 'Orange']
Using extend() (Merges two lists)
fruits.extend(["Pineapple", "Watermelon"])
print(fruits) # ['Apple', 'Grapes', 'Mango', 'Cherry', 'Orange',
'Pineapple', 'Watermelon']
6. Removing Elements from a List
fruits.pop(2) # Removes 'Cherry'
print(fruits) # ['Apple', 'Grapes', 'Orange', 'Pineapple', 'Watermelon']
last_item = fruits.pop() # Removes last item
print(last_item) # Watermelon
Using remove() (Removes first occurrence of a value)
fruits.remove("Mango")
print(fruits) # ['Apple', 'Grapes', 'Cherry', 'Orange', 'Pineapple',
'Watermelon']
Using pop() (Removes element at a given index, default
is last)
Using del (Deletes specific index or entire list)
del fruits[1] # Removes 'Grapes'
print(fruits) # ['Apple', 'Orange', 'Pineapple']
del fruits # Deletes entire list
Using clear() (Empties the list)
fruits.clear()
print(fruits) # []
7. Looping Through Lists
Using for Loop
fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits:
print(fruit)
Using while Loop
i=0
while i < len(fruits):
print(fruits[i])
i += 1
Using List Comprehension
uppercase_fruits = [fruit.upper() for fruit in fruits]
print(uppercase_fruits) # ['APPLE', 'BANANA', 'CHERRY']
8. Checking if an Item Exists
fruits = ["Apple", "Banana", "Cherry"]
if "Apple" in fruits:
print("Yes, Apple is in the list")
9. Sorting & Reversing a List
Using sort()
numbers = [5, 2, 9, 1, 5, 6]
numbers.sort()
print(numbers) # [1, 2, 5, 5, 6, 9]
Using sorted() (Returns a sorted copy)
sorted_numbers = sorted(numbers, reverse=True)
print(sorted_numbers) # [9, 6, 5, 5, 2, 1]
Reversing a List
numbers.reverse()
print(numbers) # [6, 5, 5, 2, 1, 9]
10. Copying a List
copy_fruits = fruits.copy()
# OR
copy_fruits = list(fruits)
# OR
copy_fruits = fruits[:]
11. List Methods Summary
Method Description
append(x
Adds x to the end of the list
)
insert(i,
Inserts x at index i
x)
remove( Removes the first occurrence of
x) x
Removes and returns item at
pop(i)
index i (default: last)
clear() Empties the list
index(x) Returns the index of x
Returns the count of x in the
count(x)
list
Sorts the list in ascending
sort()
order
reverse() Reverses the order of elements
Returns a shallow copy of the
copy()
list
12. List Comprehension (Shortcut for
Creating Lists)
squares = [x**2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers) # [0, 2, 4, 6, 8]
Dictionary in Python
A dictionary in Python is an unordered, mutable collection of
key-value pairs. It is used to store data in a structured way, like a
real-world dictionary where words (keys) have meanings (values).
1. Creating a Dictionary
python
CopyEdit
student = {
"name": "Dhairya",
"age": 17,
"class": "11th",
"subjects": ["Math", "Physics", "Chemistry"]
}
empty_dict = {} # Empty dictionary
Keys must be unique and immutable (strings, numbers,
tuples).
Values can be any data type (strings, lists, dictionaries, etc.).
2. Accessing Dictionary Values
python
CopyEdit
print(student["name"]) # Dhairya
print(student["subjects"]) # ['Math', 'Physics', 'Chemistry']
Using .get() (Avoids KeyError)
python
CopyEdit
print(student.get("age")) # 17
print(student.get("marks", "Not Available")) # Default value if key is
missing
3. Adding & Updating Values
python
CopyEdit
student["age"] = 18 # Update existing value
student["school"] = "XYZ High School" # Add new key-value pair
print(student)
4. Removing Items
Using pop() (Removes key and returns value)
python
CopyEdit
age = student.pop("age")
print(age) # 18
print(student)
Using del (Deletes key or entire dictionary)
python
CopyEdit
del student["class"] # Deletes a specific key
del student # Deletes entire dictionary
Using popitem() (Removes the last inserted item)
python
CopyEdit
student.popitem()
print(student)
Using clear() (Empties the dictionary)
python
CopyEdit
student.clear()
print(student) # {}
5. Looping Through a Dictionary
Looping Through Keys
python
CopyEdit
for key in student:
print(key) # name, age, subjects, school
Looping Through Values
python
CopyEdit
for value in student.values():
print(value) # Dhairya, 18, ['Math', 'Physics', 'Chemistry'], 'XYZ High
School'
Looping Through Key-Value Pairs
python
CopyEdit
for key, value in student.items():
print(key, ":", value)
6. Checking if a Key Exists
python
CopyEdit
if "name" in student:
print("Name exists in dictionary")
7. Dictionary Methods Summary
Method Description
dict.keys() Returns all keys
dict.values() Returns all values
Returns all key-
dict.items()
value pairs
Returns value of
dict.get(key,
key, or default if key
default)
not found
Removes and
dict.pop(key) returns value of the
key
Removes and
returns the last
dict.popitem()
inserted key-value
pair
Empties the
dict.clear()
dictionary
dict.update(other_di Merges another
ct) dictionary
8. Dictionary Comprehension (Shortcut
for Creating Dictionaries)
python
CopyEdit
squares = {x: x**2 for x in range(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
SQL (Structured
Query Language)
DDL (Data Definition Language)
CREATE TABLE Students (
RollNo INT PRIMARY KEY,
Name VARCHAR(50),
Marks INT
);
DML (Data Manipulation Language)
INSERT INTO Students (RollNo, Name, Marks) VALUES (1, 'Dhairya',
95);
UPDATE Students SET Marks = 98 WHERE RollNo = 1;
DELETE FROM Students WHERE RollNo = 1;
DQL (Data Query Language)
SELECT * FROM Students;
SELECT Name FROM Students WHERE Marks > 90 ORDER BY Marks
DESC;
Aggregate Functions
SELECT COUNT(*), AVG(Marks), MAX(Marks) FROM Students;
Joins
SELECT Students.Name, Marks.Subject, Marks.Score
FROM Students
INNER JOIN Marks ON Students.RollNo = Marks.RollNo;
Emerging Trends
1. Artificial Intelligence (AI) & Machine Learning (ML)
AI: Machines simulating human intelligence.
ML: AI systems that learn from data (e.g., ChatGPT,
recommendation systems).
Applications: Self-driving cars, facial recognition, chatbots,
fraud detection.
2. Internet of Things (IoT)
Network of interconnected devices that collect & exchange
data (e.g., smart homes, smart cities, wearables).
Uses: Home automation, industrial automation, healthcare
monitoring.
3. Blockchain Technology
Decentralized & secure digital ledger (used in
cryptocurrency, supply chain, smart contracts).
Features: Transparency, security, immutability.
4. Cloud Computing
Delivery of computing services (storage, databases, servers)
over the internet.
Types: IaaS, PaaS, SaaS
Examples: AWS, Google Cloud, Microsoft Azure.
5. Big Data & Data Analytics
Big Data: Large-scale data sets (structured & unstructured).
Data Analytics: Extracting insights from data (e.g., business
trends, AI training, personalized recommendations).
6. Cybersecurity & Ethical Hacking
Protecting systems from cyber threats (hacking, malware,
data breaches).
Ethical hacking: Finding vulnerabilities before hackers
exploit them.
7. 5G & Next-Gen Networks
Faster & more reliable wireless communication.
Uses: IoT, real-time gaming, smart cities, self-driving cars.
8. Virtual Reality (VR) & Augmented Reality (AR)
VR: Fully immersive digital environment (e.g., gaming,
training).
AR: Enhancing real-world environment with digital overlays
(e.g., Pokémon GO, AR glasses).
9. Quantum Computing
Uses quantum mechanics for super-fast problem-solving (e.g.,
cryptography, AI, scientific simulations).
10. Edge Computing
Processing data closer to the source instead of a centralized
cloud.
Benefits: Faster response times, less bandwidth usage (used
in IoT, autonomous vehicles).