0% found this document useful (0 votes)
2 views34 pages

HTML,Css,Js,Rjs,Py,Mysql Study Guide (1)

This study guide provides a comprehensive overview of six core web technologies: HTML, CSS, JavaScript, React, Python, and MySQL, with clear explanations and practical examples. Each chapter covers fundamental concepts, syntax, and best practices for building web applications. The guide is designed for easy understanding and is suitable for beginners.

Uploaded by

iam.sabhari
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)
2 views34 pages

HTML,Css,Js,Rjs,Py,Mysql Study Guide (1)

This study guide provides a comprehensive overview of six core web technologies: HTML, CSS, JavaScript, React, Python, and MySQL, with clear explanations and practical examples. Each chapter covers fundamental concepts, syntax, and best practices for building web applications. The guide is designed for easy understanding and is suitable for beginners.

Uploaded by

iam.sabhari
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

nt Complete Study Guide

HTML CSS JavaScript React Python MySQL

What you will learn: This guide covers all 6 core web technologies with clear explanations, code
examples, reference tables, and helpful tips. Written in simple English for easy understanding.
Table of Contents

Ch 1 HTML — Structure of the Web Page 3

Ch 2 CSS — Styling and Layouts Page 13

Ch 3 JavaScript — Programming the Web Page 23

Ch 4 React — Building UI Components Page 33

Ch 5 Python — General Purpose Programming Page 43

Ch 6 MySQL — Database Management Page 53


HTML

1.1 What is HTML?


HTML stands for HyperText Markup Language. It is the standard language used to create and structure
content on the web. Every webpage you visit starts with HTML. HTML uses tags to mark up text, images,
links, tables and more. The browser reads these tags and displays content properly.
Note: HTML is NOT a programming language. It is a markup language — it describes structure, not logic.

1.2 Basic Page Structure


Every HTML file follows this standard structure:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My First Page</title>
</head>
<body>
<h1>Hello World!</h1>
<p>This is my first webpage.</p>
</body>
</html>

• <!DOCTYPE html> — Tells browser this is an HTML5 document


• <head> — Contains metadata (not visible on page)
• <title> — Text shown on the browser tab
• <body> — Everything visible on the webpage goes here

1.3 Headings, Paragraphs & Text Formatting


<h1>Main Title</h1> <!-- Biggest -->
<h2>Section Heading</h2>
<h3>Sub Section</h3>
<h6>Smallest Heading</h6>

<p>This is a paragraph.</p>
<b>Bold text</b> <strong>Strong bold</strong>
<i>Italic</i> <em>Emphasized italic</em>
<u>Underline</u> <s>Strikethrough</s>
<mark>Highlighted</mark> <small>Small text</small>
<br> <!-- Line break -->
<hr> <!-- Horizontal line -->
Tip: Use only ONE h1 per page. It is important for SEO (Search Engine Optimization).

1.4 Links
<!-- Link to another site -->
<a href="[Link] Google</a>

<!-- Open in new tab -->


<a href="[Link] target="_blank">New Tab</a>

<!-- Link to another page on same site -->


<a href="[Link]">About Us</a>

<!-- Email link -->


<a href="[Link] Me</a>

1.5 Images
<img src="[Link]" alt="Description" width="300" height="200">

<!-- From internet -->


<img src="[Link] alt="Online image">

• src — Path or URL of the image


• alt — Description text (shown if image fails, good for accessibility)
• width / height — Size in pixels

1.6 Lists
<!-- Unordered list (bullet points) -->
<ul>
<li>Apple</li>
<li>Banana</li>
<li>Mango</li>
</ul>

<!-- Ordered list (numbered) -->


<ol>
<li>Wake up</li>
<li>Brush teeth</li>
<li>Have breakfast</li>
</ol>

1.7 Tables
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
</thead>
<tbody>
<tr>
<td>Arjun</td>
<td>22</td>
<td>Chennai</td>
</tr>
<tr>
<td>Priya</td>
<td>24</td>
<td>Bangalore</td>
</tr>
</tbody>
</table>

• <th> — Table header cell (bold by default)


• <td> — Table data cell
• <tr> — Table row

1.8 Forms
<form action="/submit" method="POST">
<label>Name:</label>
<input type="text" name="name" placeholder="Your name">

<input type="email" name="email" placeholder="Email">


<input type="password" name="pwd" placeholder="Password">

<input type="radio" name="gender" value="male"> Male


<input type="radio" name="gender" value="female"> Female

<input type="checkbox" name="agree"> I agree to terms

<select name="city">
<option value="chennai">Chennai</option>
<option value="mumbai">Mumbai</option>
</select>

<textarea name="msg" rows="4"></textarea>

<button type="submit">Submit</button>
</form>

1.9 Semantic HTML


Semantic tags give meaning to your HTML — they tell the browser and developers what each section does.

Tag Purpose / Use

<header> Top section of page (logo, navigation)


<nav> Navigation links

<main> Main content area

<section> A grouped section of content

<article> Independent content (blog post, news)

<aside> Sidebar or supplementary content

<footer> Bottom section (copyright, links)

<figure> Image with caption

1.10 HTML Attributes Reference


Attribute Used In Description

href <a> Link destination URL

src <img>, <script> File path or URL

alt <img> Alternative text for image

class Any element CSS class name (can repeat)

id Any element Unique identifier (no repeat)

style Any element Inline CSS styles

type <input> Input type: text, email, password, checkbox...

placeholder <input> Hint text inside input field

required <input> Makes field mandatory in forms

disabled <input> Disables the input element

Tip: Always close your HTML tags. Unclosed tags can break your page layout.
CSS

2.1 What is CSS?


CSS stands for Cascading Style Sheets. It controls how HTML elements look — colors, fonts, spacing,
layout, animations and more. Without CSS, every webpage would look like plain black text on white
background.
Tip: Remember: HTML = Structure, CSS = Style, JavaScript = Behavior.

2.2 Three Ways to Add CSS


<!-- 1. Inline (directly on element) -->
<p style="color:red; font-size:18px;">Red text</p>

<!-- 2. Internal (inside <style> in <head>) -->


<style>
p { color: blue; }
</style>

<!-- 3. External (recommended — separate .css file) -->


<link rel="stylesheet" href="[Link]">

Note: Always prefer External CSS. It keeps code clean and easy to maintain.

2.3 CSS Selectors


Selector Example What it targets

Element p{} All <p> tags on the page

Class .box { } Elements with class='box'

ID #title { } Element with id='title'

Universal *{} Every single element

Descendant div p { } All <p> tags inside <div>

Direct Child div > p { } Only direct <p> children of <div>

Hover Pseudo a:hover { } When mouse is hovering over <a>

Multiple h1, h2 { } Both h1 and h2 at the same time

2.4 Colors, Backgrounds & Fonts


/* Color types */
color: red; /* Named color */
color: #FF5733; /* Hex color */
color: rgb(255, 87, 51); /* RGB */
color: rgba(255,87,51,0.5); /* RGB with opacity */

/* Background */
background-color: #f0f0f0;
background-image: url('[Link]');
background-size: cover;
background-position: center;

/* Fonts */
font-family: 'Arial', sans-serif;
font-size: 16px;
font-weight: bold; /* or: 100 - 900 */
font-style: italic;
text-align: center; /* left | right | center | justify */
text-decoration: underline;
line-height: 1.6;
letter-spacing: 2px;
text-transform: uppercase;

2.5 The Box Model


Every HTML element is a box. The CSS Box Model defines how space is calculated:
div {
width: 300px;
height: 150px;
padding: 20px; /* Space INSIDE the border */
border: 2px solid black;
margin: 30px; /* Space OUTSIDE the border */
}

/* Shorthand: top right bottom left */


padding: 10px 20px 10px 20px;
margin: 0 auto; /* Centers block element horizontally */

/* Best practice */
* { box-sizing: border-box; }

Note: box-sizing: border-box makes width include padding and border — prevents layout surprises.

2.6 Display Values


Value Behavior

block Takes full width, starts on new line (div, p, h1)

inline Only takes needed width, stays on same line (span, a)

inline-block Like inline but you can set width and height
none Hides element completely, removes from layout

flex Enables Flexbox layout on the container

grid Enables CSS Grid layout on the container

2.7 Flexbox
Flexbox makes it simple to align and distribute items in a row or column.
.container {
display: flex;
flex-direction: row; /* row | column */
justify-content: center; /* Main axis alignment */
align-items: center; /* Cross axis alignment */
flex-wrap: wrap; /* Wrap to next line */
gap: 16px;
}

.item {
flex: 1; /* Grow to fill equal space */
}

justify-content Effect

flex-start Items packed at the start

flex-end Items packed at the end

center Items centered

space-between Equal gaps between items, none at edges

space-around Equal space around each item

space-evenly Equal space between all items including edges

2.8 CSS Grid


.container {
display: grid;
grid-template-columns: 1fr 2fr 1fr; /* 3 columns */
gap: 20px;
}

/* Item spanning multiple columns */


.item { grid-column: span 2; }

/* Named grid areas */


.container {
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }

2.9 Positioning
Position Behavior

static Default. Normal document flow.

relative Offset from its normal position, keeps its space.

absolute Removed from flow, positioned relative to nearest positioned parent.

fixed Fixed on screen — stays even when you scroll.

sticky Normal flow until scroll threshold, then becomes fixed.

2.10 Responsive Design — Media Queries


/* Mobile first (default styles) */
.container { width: 100%; padding: 10px; }

/* Tablet (768px and up) */


@media (min-width: 768px) {
.container { width: 720px; }
}

/* Desktop (1024px and up) */


@media (min-width: 1024px) {
.container { width: 960px; }
}

/* Dark mode */
@media (prefers-color-scheme: dark) {
body { background: #000; color: #fff; }
}

2.11 Transitions & Animations


/* Smooth hover transition */
button {
background: blue;
transition: background 0.3s ease, transform 0.2s;
}
button:hover {
background: darkblue;
transform: scale(1.05);
}

/* Keyframe animation */
@keyframes fadeIn {
from { opacity: 0; transform: translateY(-10px); }
to { opacity: 1; transform: translateY(0); }
}
.box { animation: fadeIn 0.5s ease forwards; }

Tip: Use transitions for hover effects and keyframe animations for entrance/loading effects.
JavaScript

3.1 What is JavaScript?


JavaScript (JS) is a programming language that makes webpages interactive. It runs inside the browser.
With JS you can respond to clicks, validate forms, show/hide elements, fetch data from servers, and much
more.
Note: JavaScript and Java are completely different languages — they just have similar names.

3.2 Variables & Data Types


// Three ways to declare variables
var name = "Arjun"; // Old way — avoid using
let age = 22; // Use when value will change
const PI = 3.14; // Use when value never changes

// Data Types
let text = "Hello"; // String
let number = 42; // Number
let decimal = 3.14; // Number (float)
let isTrue = true; // Boolean (true/false)
let nothing = null; // Null (intentionally empty)
let undef; // Undefined (no value assigned)
let obj = { name:"Arjun" };// Object
let arr = [1, 2, 3]; // Array

Tip: Use const by default. Only use let when you need to reassign. Avoid var.

3.3 Operators
Type Operators Example

Arithmetic + - * / % ** 5 + 3 = 8 | 10 % 3 = 1 | 2**3 = 8

Assignment = += -= *= /= x += 5 means x = x + 5

Comparison == === != !== > < >= <= 5 === '5' is false (strict equality)

Logical && || ! true && false = false | !true = false

Ternary condition ? a : b age >= 18 ? 'Adult' : 'Minor'

3.4 Conditionals
let score = 80;

// if - else if - else
if (score >= 90) {
[Link]("Grade A");
} else if (score >= 75) {
[Link]("Grade B");
} else {
[Link]("Try again");
}

// Switch statement
let day = "Monday";
switch(day) {
case "Monday": [Link]("Start of week"); break;
case "Friday": [Link]("Weekend soon!"); break;
default: [Link]("Another day");
}

// Ternary (short if-else)


let status = score >= 50 ? "Pass" : "Fail";

3.5 Loops
// for loop
for (let i = 0; i < 5; i++) {
[Link](i); // 0, 1, 2, 3, 4
}

// while loop
let count = 0;
while (count < 3) {
[Link](count);
count++;
}

// for...of (loop through array values)


let fruits = ["apple", "banana", "mango"];
for (let fruit of fruits) {
[Link](fruit);
}

// for...in (loop through object keys)


let person = { name: "Arjun", age: 22 };
for (let key in person) {
[Link](key, ":", person[key]);
}

// forEach
[Link](fruit => [Link](fruit));

3.6 Functions
// Function declaration
function greet(name) {
return "Hello, " + name + "!";
}
greet("Arjun"); // Hello, Arjun!

// Function expression
const add = function(a, b) { return a + b; };

// Arrow function (ES6 — shorter)


const multiply = (a, b) => a * b;

// Default parameters
function welcome(name = "Guest") {
return "Welcome, " + name;
}
welcome(); // Welcome, Guest
welcome("Arjun"); // Welcome, Arjun

// Rest parameters
function sum(...numbers) {
return [Link]((total, n) => total + n, 0);
}
sum(1, 2, 3, 4); // 10

3.7 Arrays & Methods


let nums = [10, 20, 30, 40, 50];

[Link](60); // Add to end


[Link](); // Remove from end
[Link](5); // Add to start
[Link](); // Remove from start
[Link]; // Get length

// Important methods
[Link](n => n * 2); // [20,40,60,80,100] — transform
[Link](n => n > 20); // [30,40,50] — filter
[Link](n => n > 15); // 20 — first match
[Link](30); // true/false
[Link](40); // 3
[Link](1, 3); // [20,30] — no mutation
[Link]((a, b) => a - b); // ascending sort
[Link]((sum, n) => sum + n, 0); // 150 — sum all
[Link](", "); // "10, 20, 30, 40, 50"

3.8 Objects
let person = {
name: "Arjun",
age: 22,
greet() { return "Hi, I'm " + [Link]; }
};
[Link]; // "Arjun"
person["age"]; // 22
[Link](); // Hi, I'm Arjun

[Link] = "a@b.c"; // Add property


[Link] = 23; // Update property
delete [Link]; // Delete property

// Destructuring
const { name, age } = person;

// Spread operator
const copy = { ...person }; // Copy object
const merged = { ...person, ...obj }; // Merge objects

3.9 DOM Manipulation


The DOM (Document Object Model) lets JavaScript interact with HTML elements on the page.
// Select elements
[Link]("title");
[Link](".box"); // First match
[Link](".item"); // All matches

// Change content and style


let el = [Link]("msg");
[Link] = "New text";
[Link] = "<b>Bold text</b>";
[Link] = "red";
[Link] = "20px";

// CSS classes
[Link]("active");
[Link]("hidden");
[Link]("dark");

// Create and add new elements


let newDiv = [Link]("div");
[Link] = "Created by JS!";
[Link](newDiv);

// Event listeners
[Link]("btn").addEventListener("click", function() {
alert("Button clicked!");
});

3.10 Fetch API — Getting Data


// Using .then() — Promise chain
fetch("[Link]
.then(res => [Link]())
.then(data => [Link](data))
.catch(err => [Link]("Error:", err));

// Using async/await — cleaner way


async function getUsers() {
try {
const res = await fetch("[Link]
const data = await [Link]();
[Link](data);
} catch (err) {
[Link]("Error:", err);
}
}
getUsers();

Tip: Always use try/catch with async/await to handle network failures.


React

4.1 What is React?


React is a JavaScript library made by Facebook for building fast, interactive UIs. It breaks the UI into small,
reusable pieces called components. Instead of reloading the entire page, React updates only what changed
— making apps very fast.

• Component-based architecture
• Virtual DOM for fast updates
• One-way data flow
• Huge ecosystem and community
Note: Know HTML, CSS and JavaScript well before starting React.

4.2 Setup
# Using Vite (fastest and recommended)
npm create vite@latest my-app -- --template react
cd my-app
npm install
npm run dev

# Using Create React App (older method)


npx create-react-app my-app
cd my-app
npm start

4.3 JSX — JavaScript XML


JSX lets you write HTML-like code inside JavaScript. React converts it to real JS.
// JSX looks like HTML but it's inside JS
const element = <h1>Hello World!</h1>;

// Use curly braces {} for JS expressions


const name = "Arjun";
const greeting = <h1>Hello, {name}!</h1>;

// Multi-line JSX
const card = (
<div className="card"> {/* use className not class */}
<h2>Profile</h2>
<p>Age: {22 + 1}</p>
</div>
);
// Rules:
// 1. Use className instead of class
// 2. Use htmlFor instead of for
// 3. Always close self-closing tags: <br /> <img />
// 4. Must return ONE root element

4.4 Components
A component is a JavaScript function that returns JSX. Break your UI into small, reusable components.
// Functional Component
function Welcome(props) {
return <h1>Welcome, {[Link]}!</h1>;
}

// Arrow function component


const Button = ({ label, onClick }) => (
<button onClick={onClick}>{label}</button>
);

// Using components like HTML tags


function App() {
return (
<div>
<Welcome name="Arjun" />
<Button label="Click Me" onClick={() => alert("Hi!")} />
</div>
);
}

export default App;

4.5 Props
Props let you pass data from a parent component to a child. Props are read-only.
// Parent passes data as attributes
function App() {
return <UserCard name="Arjun" age={22} city="Chennai" />;
}

// Child receives and uses props


function UserCard({ name, age, city }) {
return (
<div>
<h2>{name}</h2>
<p>Age: {age} | City: {city}</p>
</div>
);
}

// Default props
function Greeting({ name = "Guest" }) {
return <p>Hello, {name}!</p>;
}

4.6 useState Hook


State is data that belongs to a component and can change. When state changes, React re-renders the
component automatically.
import { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0); // initial value = 0

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>+</button>
<button onClick={() => setCount(count - 1)}>-</button>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);
}

// Toggle example
function Toggle() {
const [isOn, setIsOn] = useState(false);
return (
<button onClick={() => setIsOn(!isOn)}>
{isOn ? "ON" : "OFF"}
</button>
);
}

4.7 useEffect Hook


useEffect runs code as a side effect — when component loads, or when a value changes. Use it to fetch
data, set timers, etc.
import { useState, useEffect } from 'react';

function UserList() {
const [users, setUsers] = useState([]);

// [] means: run once when component first loads


useEffect(() => {
fetch("[Link]
.then(res => [Link]())
.then(data => setUsers(data));
}, []);

return (
<ul>
{[Link](user => (
<li key={[Link]}>{[Link]}</li>
))}
</ul>
);
}

useEffect Pattern When it runs

useEffect(() => { }, []) Once — when component first mounts

useEffect(() => { }, [value]) Every time 'value' changes

useEffect(() => { }) Every re-render (use carefully)

return () => cleanup inside useEffect When component unmounts (cleanup)

4.8 Handling Forms


function LoginForm() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");

const handleSubmit = (e) => {


[Link](); // Prevent page reload
[Link](email, password);
};

return (
<form onSubmit={handleSubmit}>
<input
type="email"
value={email}
onChange={(e) => setEmail([Link])}
placeholder="Email"
/>
<input
type="password"
value={password}
onChange={(e) => setPassword([Link])}
placeholder="Password"
/>
<button type="submit">Login</button>
</form>
);
}

4.9 Lists & Conditional Rendering


// Render a list
const fruits = ["Apple", "Banana", "Mango"];
function FruitList() {
return (
<ul>
{[Link]((fruit, index) => (
<li key={index}>{fruit}</li> // key is required!
))}
</ul>
);
}

// Conditional rendering
function Dashboard({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? <h1>Welcome Back!</h1> : <h1>Please Login</h1>}
{isLoggedIn && <button>Logout</button>}
</div>
);
}

4.10 React Router — Navigation


// npm install react-router-dom
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';

function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">Home</Link> | <Link to="/about">About</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/user/:id" element={<UserPage />} />
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
);
}

// Programmatic navigation
import { useNavigate } from 'react-router-dom';
function Login() {
const navigate = useNavigate();
return <button onClick={() => navigate('/dashboard')}>Login</button>;
}

Tip: Use Link instead of <a href> to avoid full page reload in React apps.
Python

5.1 What is Python?


Python is a high-level, easy-to-read programming language used in web development, data science, AI,
automation, and more. Its clean syntax reads almost like plain English.

• Easy to learn — readable, clean syntax


• Web (Django/Flask), AI/ML, data science
• Huge standard library and community
• Works on Windows, Mac and Linux

5.2 Variables & Data Types


# Python automatically detects the type
name = "Arjun" # str
age = 22 # int
height = 5.9 # float
is_cool = True # bool
nothing = None # NoneType (like null)

# Check type
print(type(name)) # <class 'str'>

# Type conversion
str(42) # "42"
int("100") # 100
float("3.14") # 3.14
bool(0) # False (0, "", [], None are falsy)

# Multiple assignment
x, y, z = 1, 2, 3

5.3 Strings
s = "Hello, World!"

[Link]() # "HELLO, WORLD!"


[Link]() # "hello, world!"
[Link]() # Remove whitespace from both ends
[Link]("Hello","Hi") # "Hi, World!"
[Link](", ") # ["Hello", "World!"]
[Link]("He") # True
len(s) # 13
# f-strings (best way to format strings)
name = "Arjun"
age = 22
print(f"My name is {name} and I am {age} years old.")

# Slicing
s[0] # 'H'
s[0:5] # 'Hello'
s[-1] # '!' (last char)
s[::-1] # Reverse string

5.4 Lists
fruits = ["apple", "banana", "mango"]

fruits[0] # "apple"
fruits[-1] # "mango"
fruits[0:2] # ["apple", "banana"]

[Link]("grape") # Add to end


[Link](1,"kiwi")# Insert at index
[Link]("banana")# Remove by value
[Link]() # Remove last
len(fruits) # Length
"apple" in fruits # True

[Link]() # Sort A-Z


[Link]() # Reverse

# List comprehension — powerful shorthand


nums = [1, 2, 3, 4, 5]
squares = [n**2 for n in nums] # [1,4,9,16,25]
evens = [n for n in nums if n % 2 == 0] # [2, 4]

5.5 Dictionaries
person = { "name": "Arjun", "age": 22, "city": "Chennai" }

person["name"] # "Arjun"
[Link]("email","N/A") # "N/A" (safe, returns default)
person["email"] = "a@b.c" # Add key
person["age"] = 23 # Update
del person["city"] # Delete

# Loop through dict


for key, value in [Link]():
print(f"{key}: {value}")

# Dict comprehension
squares = {n: n**2 for n in range(1, 6)}
# {1:1, 2:4, 3:9, 4:16, 5:25}
5.6 Conditions & Loops
# if - elif - else
score = 75
if score >= 90: print("A")
elif score >= 75: print("B")
elif score >= 60: print("C")
else: print("Fail")

# for loop with range


for i in range(5): # 0,1,2,3,4
print(i)

for i in range(1,10,2): # 1,3,5,7,9 (start, stop, step)


print(i)

# while loop
count = 0
while count < 5:
print(count)
count += 1

# Loop control
for n in range(10):
if n == 3: continue # skip 3
if n == 7: break # stop at 7
print(n)

5.7 Functions
# Basic function
def greet(name):
return f"Hello, {name}!"

greet("Arjun") # Hello, Arjun!

# Default parameter
def welcome(name="Guest"):
return f"Welcome, {name}!"

# Multiple return values


def min_max(nums):
return min(nums), max(nums)

low, high = min_max([3, 1, 9, 2]) # low=1, high=9

# *args (variable positional arguments)


def add_all(*numbers):
return sum(numbers)
add_all(1, 2, 3, 4) # 10

# **kwargs (variable keyword arguments)


def show(**info):
for k, v in [Link]():
print(f"{k}: {v}")

# Lambda (one-line anonymous function)


double = lambda x: x * 2
double(5) # 10

5.8 Object-Oriented Programming (OOP)


class Animal:
kingdom = "Animalia" # Class variable (shared)

def __init__(self, name, sound): # Constructor


[Link] = name # Instance variable
[Link] = sound

def speak(self):
return f"{[Link]} says {[Link]}!"

def __str__(self): # String representation


return f"Animal: {[Link]}"

# Inheritance
class Dog(Animal):
def __init__(self, name):
super().__init__(name, "Woof") # Call parent

def fetch(self, item):


return f"{[Link]} fetched the {item}!"

# Use the class


dog = Dog("Rex")
print([Link]()) # Rex says Woof!
print([Link]("ball")) # Rex fetched the ball!
print([Link]) # Animalia

5.9 File Handling & JSON


# Write to file
with open("[Link]", "w") as f:
[Link]("Hello World\n")

# Read from file


with open("[Link]", "r") as f:
content = [Link]()
# OR: lines = [Link]() (list of lines)

# Append to file
with open("[Link]", "a") as f:
[Link]("New line\n")

# JSON
import json
data = {"name": "Arjun", "age": 22}

# Write JSON
with open("[Link]", "w") as f:
[Link](data, f)

# Read JSON
with open("[Link]", "r") as f:
loaded = [Link](f)

5.10 Error Handling & Key Libraries


# try-except
try:
result = 10 / 0
except ZeroDivisionError:
print("Can't divide by zero!")
except ValueError as e:
print(f"Value error: {e}")
except Exception as e:
print(f"Error: {e}")
finally:
print("This always runs")

# Raise custom error


def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative!")

Library Purpose Install

requests HTTP requests, API calls pip install requests

pandas Data analysis, CSV/Excel files pip install pandas

numpy Math and array operations pip install numpy

flask Lightweight web framework pip install flask

django Full web framework pip install django

matplotlib Charts and graphs pip install matplotlib

datetime Dates and times (built-in) import datetime

os File system operations (built-in) import os


MySQL

6.1 What is MySQL?


MySQL is a Relational Database Management System (RDBMS). It stores data in organized tables with
rows and columns — like a spreadsheet but much more powerful. You use SQL (Structured Query
Language) to create, read, update, and delete data.

• Open source and free


• Used by Facebook, YouTube, Twitter
• Works with PHP, Python, [Link], Java
• ACID compliant — data is safe and consistent

6.2 Key Concepts


Term Meaning

Database A collection of related tables

Table Data organized in rows and columns

Row / Record One entry in a table

Column / Field An attribute like name, age, email

Primary Key Unique ID for each row — no duplicates

Foreign Key A column that links to another table's primary key

Index Speeds up searching on a column

Query A command sent to the database

6.3 Database & Table Operations


-- Create a database
CREATE DATABASE school;

-- Select the database


USE school;

-- Create a table
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(150) UNIQUE,
age INT,
city VARCHAR(50) DEFAULT 'Unknown',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

SHOW TABLES; -- See all tables


DESCRIBE students; -- See table structure
DROP TABLE students; -- Delete table (careful!)
DROP DATABASE school; -- Delete database (very careful!)

6.4 Data Types


Category Type Description

Numbers INT Whole numbers

Numbers BIGINT Very large whole numbers

Numbers DECIMAL(10,2) Exact decimals — good for money

Numbers FLOAT / DOUBLE Decimal numbers (approximate)

Text VARCHAR(n) Variable length text (up to n characters)

Text TEXT Long text (up to 65,535 characters)

Text CHAR(n) Fixed length text

Date/Time DATE YYYY-MM-DD

Date/Time DATETIME YYYY-MM-DD HH:MM:SS

Date/Time TIMESTAMP Auto-updates to current time

Boolean TINYINT(1) 0 = false, 1 = true

6.5 INSERT — Adding Data


-- Insert one row
INSERT INTO students (name, email, age, city)
VALUES ('Arjun', 'arjun@[Link]', 22, 'Chennai');

-- Insert multiple rows


INSERT INTO students (name, email, age, city) VALUES
('Priya', 'priya@[Link]', 24, 'Bangalore'),
('Ravi', 'ravi@[Link]', 21, 'Mumbai'),
('Divya', 'divya@[Link]', 23, 'Hyderabad');

6.6 SELECT — Reading Data


-- Get everything
SELECT * FROM students;
-- Get specific columns
SELECT name, email, city FROM students;

-- WHERE clause — filter rows


SELECT * FROM students WHERE city = 'Chennai';
SELECT * FROM students WHERE age > 21;
SELECT * FROM students WHERE age BETWEEN 20 AND 25;
SELECT * FROM students WHERE name LIKE 'A%'; -- starts with A
SELECT * FROM students WHERE city IN ('Chennai','Mumbai');

-- ORDER BY
SELECT * FROM students ORDER BY name ASC; -- A to Z
SELECT * FROM students ORDER BY age DESC; -- oldest first

-- LIMIT
SELECT * FROM students LIMIT 5; -- first 5 rows
SELECT * FROM students LIMIT 5 OFFSET 10; -- skip 10, show 5

-- Aggregate functions
SELECT COUNT(*) FROM students;
SELECT AVG(age), MAX(age), MIN(age) FROM students;

-- DISTINCT — remove duplicates


SELECT DISTINCT city FROM students;

6.7 UPDATE & DELETE


-- Update rows
UPDATE students SET city = 'Madurai' WHERE id = 1;
UPDATE students SET age = 25, city = 'Pune' WHERE name = 'Ravi';

-- Delete rows
DELETE FROM students WHERE id = 3;
DELETE FROM students WHERE city = 'Mumbai';

-- Delete ALL rows (table stays)


DELETE FROM students;

-- Truncate (faster delete, resets auto_increment)


TRUNCATE TABLE students;

Warning: ALWAYS use WHERE with UPDATE and DELETE. Without it, you change or delete ALL rows!

6.8 JOINs — Combining Tables


JOINs let you combine rows from two tables based on a related column.
-- Sample tables:
-- students: id, name, course_id
-- courses: id, course_name

-- INNER JOIN: only rows that match in BOTH tables


SELECT [Link], c.course_name
FROM students s
INNER JOIN courses c ON s.course_id = [Link];

-- LEFT JOIN: all from students, matching from courses


SELECT [Link], c.course_name
FROM students s
LEFT JOIN courses c ON s.course_id = [Link];
-- Students with no course will show NULL for course_name

-- RIGHT JOIN: all from courses, matching from students


SELECT [Link], c.course_name
FROM students s
RIGHT JOIN courses c ON s.course_id = [Link];

JOIN Type Returns

INNER JOIN Only rows with matches in BOTH tables

LEFT JOIN All rows from left table + matched from right (NULLs for no match)

RIGHT JOIN All rows from right table + matched from left (NULLs for no match)

6.9 GROUP BY & HAVING


-- Count students per city
SELECT city, COUNT(*) AS total
FROM students
GROUP BY city;

-- Average age per city


SELECT city, AVG(age) AS avg_age, COUNT(*) AS count
FROM students
GROUP BY city
ORDER BY count DESC;

-- HAVING: filter group results (like WHERE but for groups)


SELECT city, COUNT(*) AS total
FROM students
GROUP BY city
HAVING total > 2; -- only cities with more than 2 students

-- Full example: WHERE + GROUP BY + HAVING


SELECT city, COUNT(*) AS total
FROM students
WHERE age > 20
GROUP BY city
HAVING total >= 2
ORDER BY total DESC;

6.10 Constraints & Indexes


-- Constraints in CREATE TABLE
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL, -- Cannot be empty
price DECIMAL(10,2) DEFAULT 0.00, -- Default value
email VARCHAR(150) UNIQUE, -- No duplicate emails
category VARCHAR(50) CHECK (category IN ('Electronics','Clothing'))
);

-- Add primary key after creation


ALTER TABLE students ADD PRIMARY KEY (id);

-- Foreign key (links two tables)


CREATE TABLE orders (
order_id INT AUTO_INCREMENT PRIMARY KEY,
student_id INT,
FOREIGN KEY (student_id) REFERENCES students(id)
ON DELETE CASCADE
);

-- Index (speeds up queries on that column)


CREATE INDEX idx_city ON students(city);
CREATE UNIQUE INDEX idx_email ON students(email);

6.11 Subqueries & Useful Functions


-- Subquery: query inside a query
SELECT name FROM students
WHERE age = (SELECT MAX(age) FROM students);

SELECT name FROM students


WHERE city IN (SELECT city FROM top_cities);

-- String functions
SELECT UPPER(name), LOWER(email) FROM students;
SELECT CONCAT(name, ' from ', city) AS info FROM students;
SELECT LENGTH(name) FROM students;
SELECT TRIM(' hello ');

-- Number functions
SELECT ROUND(4.567, 2); -- 4.57
SELECT FLOOR(4.9); -- 4
SELECT CEIL(4.1); -- 5
SELECT MOD(10, 3); -- 1

-- Date functions
SELECT NOW(); -- Current date and time
SELECT CURDATE(); -- Current date only
SELECT YEAR(created_at), MONTH(created_at) FROM students;
SELECT DATEDIFF('2025-12-31', '2025-01-01'); -- days between

6.12 Python + MySQL Connection


# pip install mysql-connector-python
import [Link]

# Connect to MySQL
conn = [Link](
host="localhost",
user="root",
password="yourpassword",
database="school"
)
cursor = [Link]()

# Execute a query
[Link]("SELECT * FROM students")
rows = [Link]()
for row in rows:
print(row)

# Insert with parameters (safe from SQL injection)


sql = "INSERT INTO students (name, age) VALUES (%s, %s)"
[Link](sql, ("Arjun", 22))
[Link]() # Save changes!

[Link]()
[Link]()

Tip: Always use parameterized queries (%s) — never put values directly in the SQL string. This prevents SQL
injection attacks.
Quick Reference Cheat Sheet

HTML — Common Tags


Tag Use

<h1> to <h6> Headings (largest to smallest)

<p> Paragraph

<a href='...'> Link

<img src='...'> Image

<ul> / <ol> / <li> Unordered / Ordered list

<div> Block container

<span> Inline container

<input> <form> <button> Form elements

CSS — Key Properties


Property Common Values

color / background-color red | #fff | rgb(0,0,0)

font-size / font-weight 16px | bold | 700

margin / padding 10px | 10px 20px | auto

display block | inline | flex | grid | none

position static | relative | absolute | fixed

width / height 100px | 50% | auto | 100vh

border 1px solid #ccc

border-radius 8px | 50% (circle)

JavaScript — Quick Syntax


Feature Syntax

Variable const x = 5; | let y = 10;

Arrow Function const fn = (a, b) => a + b;

Array map [Link](item => item * 2)

Array filter [Link](item => item > 5)

Object destructure const { name, age } = person;

Spread const copy = [...arr]; | {...obj}


Async/Await const data = await fetch(url).then(r=>[Link]())

Optional chaining user?.address?.city

React — Key Hooks


Hook Use

useState const [val, setVal] = useState(initial)

useEffect useEffect(() => { }, [deps])

useRef const ref = useRef(null) — access DOM or persist value

useContext const value = useContext(MyContext)

useNavigate const nav = useNavigate(); nav('/path')

Python — Quick Reference


Feature Syntax

List comprehension [x*2 for x in nums if x > 0]

Dict comprehension {k: v for k, v in items()}

Lambda double = lambda x: x * 2

f-string f"Hello, {name}!"

Try/except try: ... except Exception as e: ...

Class class Dog(Animal): def __init__(self, name): ...

With statement with open('[Link]','r') as f: ...

MySQL — Common Queries


Operation Query

Select all SELECT * FROM table;

Filter SELECT * FROM table WHERE col = 'value';

Insert INSERT INTO table (col1, col2) VALUES (v1, v2);

Update UPDATE table SET col = 'val' WHERE id = 1;

Delete DELETE FROM table WHERE id = 1;

Join SELECT * FROM a JOIN b ON [Link] = b.a_id;

Count by group SELECT col, COUNT(*) FROM table GROUP BY col;

You might also like