โœ… Copied!
Free Resource

Python & AI
Quick Reference

Your go-to cheat sheet for Python, Pandas, Scikit-learn and Streamlit. Click any code snippet to copy it instantly.

๐Ÿ”คVariables & Data Types
name = "Biswarup"
age = 30
pi = 3.14
is_active = True
๐Ÿ“‹Lists
lst = [1, 2, 3, 4]
lst.append(5)    # add item
lst.remove(1)    # remove item
len(lst)          # length
lst[0]            # first item
lst[-1]           # last item
๐Ÿ“–Dictionaries
d = {"name": "AI", "age": 2}
d["city"] = "Durgapur"
print(d.keys())
print(d.values())
d.get("name", "N/A")
๐Ÿ”„Loops
for i in range(5):
    print(i)

for item in lst:
    print(item)

squares = [x**2 for x in range(10)]
โš™๏ธFunctions
def greet(name, age=18):
    return f"Hi {name}, you are {age}"

greet("Rahul", 22)

# Lambda
square = lambda x: x ** 2
๐Ÿ“File Handling
# Read a file
with open("data.txt", "r") as f:
    content = f.read()

# Write a file
with open("out.txt", "w") as f:
    f.write("Hello!")
๐Ÿ“ฅLoad & Inspect
import pandas as pd
df = pd.read_csv("data.csv")
df.head()         # first 5 rows
df.shape          # (rows, cols)
df.info()          # data types
df.describe()      # statistics
๐ŸงนCleaning
df.isnull().sum()       # find nulls
df.dropna()              # drop rows
df.fillna(0)            # fill nulls
df.drop_duplicates()    # rm dupes
df["col"].astype(int)    # change type
๐Ÿ”Select & Filter
df["col"]                      # one col
df[["c1", "c2"]]              # multi col
df[df["age"] > 25]            # filter
df.iloc[0]                    # row by index
df.loc[df["city"]=="Dgp"]    # by label
๐Ÿ“ŠGroupby & Aggregation
df.groupby("city")["salary"].mean()
df.groupby("dept").agg({"sal": "sum"})
df.value_counts("category")
df.sort_values("score", ascending=False)
โœ๏ธAdd & Transform
df["new_col"] = df["a"] + df["b"]
df["upper"] = df["name"].str.upper()
df["grade"] = df["score"].apply(
    lambda x: "A" if x>90 else "B")
๐Ÿ’พExport
df.to_csv("out.csv", index=False)
df.to_excel("out.xlsx")
df.to_json("out.json")
df.to_html("table.html")
๐Ÿ”ขCreate Arrays
import numpy as np
a = np.array([1,2,3])
z = np.zeros((3,4))    # 3x4 zeros
o = np.ones((2,2))    # 2x2 ones
r = np.arange(0,10,2)# [0,2,4,6,8]
rnd = np.random.rand(3,3)
๐Ÿ“Shape & Reshape
a.shape       # dimensions
a.reshape(2,3)# change shape
a.flatten()   # 1D array
a.T           # transpose
a.dtype       # data type
โž•Math Operations
np.mean(a)
np.std(a)
np.max(a), np.min(a)
np.sum(a, axis=0)
a + b, a * b   # element-wise
np.dot(a, b)   # matrix mult
โœ‚๏ธTrain-Test Split
from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = \
  train_test_split(X, y, test_size=0.2, random_state=42)
๐Ÿค–Train a Model
from sklearn.ensemble import RandomForestClassifier

model = RandomForestClassifier(n_estimators=100)
model.fit(X_train, y_train)
preds = model.predict(X_test)
๐Ÿ“Evaluate Model
from sklearn.metrics import accuracy_score, classification_report

accuracy_score(y_test, preds)
print(classification_report(y_test, preds))
โš™๏ธPreprocessing
from sklearn.preprocessing import StandardScaler, LabelEncoder

sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
๐Ÿ’พSave & Load Model
import pickle

# Save
with open("model.pkl", "wb") as f:
    pickle.dump(model, f)

# Load
with open("model.pkl", "rb") as f:
    model = pickle.load(f)
๐Ÿ–Š๏ธText Elements
import streamlit as st

st.title("My App")
st.header("Section")
st.subheader("Sub")
st.write("Any text or data")
st.markdown("**bold** _italic_")
๐ŸŽ›๏ธInput Widgets
name = st.text_input("Your name")
age = st.slider("Age", 18, 60)
opt = st.selectbox("Choose", ["A","B"])
btn = st.button("Predict")
file = st.file_uploader("Upload CSV")
๐Ÿš€ML Model Deployment
import pickle
model = pickle.load(open("model.pkl","rb"))

val = st.slider("Glucose", 0, 200)
if st.button("Predict"):
  result = model.predict([[val]])
  st.success(f"Result: {result[0]}")
๐Ÿ—๏ธBuild a Model
import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense, Dropout

model = Sequential([
  Dense(64, activation="relu", input_shape=(8,)),
  Dropout(0.3),
  Dense(32, activation="relu"),
  Dense(1, activation="sigmoid")
])
๐Ÿ‹๏ธCompile & Train
model.compile(
  optimizer="adam",
  loss="binary_crossentropy",
  metrics=["accuracy"]
)
model.fit(X_train, y_train, epochs=50, batch_size=32)
๐Ÿ“Evaluate & Save
loss, acc = model.evaluate(X_test, y_test)
print(f"Accuracy: {acc*100:.1f}%")

model.save("model.h5")
loaded = tf.keras.models.load_model("model.h5")

๐ŸŽ“ Learn All This With Real Projects

These aren't just snippets โ€” in our course you use every one of these in real, deployed AI applications.

Python Quick Reference

Essential Python syntax โ€” variables, lists, dictionaries, loops, functions and file handling. Click any code block to copy it instantly.

Pandas and NumPy Reference

The most-used Pandas DataFrame operations and NumPy array functions. Load, clean, filter, group and export data with one-click copy.

Machine Learning and Deployment Code

Scikit-learn model training pipeline, TensorFlow Keras model building and Streamlit deployment snippets โ€” ready to paste into your projects.