← Back to Hub

📦 Variables & Data Types

Variable Declaration

# Variables name and store value references first_name = "Peter Parker" # String age = 22 # Integer height = 1.78 # Float is_hero = True # Boolean

Detecting Data Types

print(type(first_name)) # Output: <class 'str'> print(type(age)) # Output: <class 'int'>

Type Conversion (Casting)

val_str = "100" val_int = int(val_str) # Convert to integer: 100 val_float = float(val_str) # Convert to float: 100.0

🖥️ Output & Formatting

String Concatenation

print("Hello " + "World") # Adds strings: "Hello World" # Print multiple args with spacing print("Name:", "Peter", "Age:", 22)

Formatted Strings (F-strings)

name = "Peter" salary = 50000 print(f"Name is {name}, salary is {salary}")

Escape Sequences

print("Line 1\nLine 2") # \n = Newline print("Item 1\tItem 2") # \t = Tab spaces

⚡ Math & User Input

Getting Input

name = input("Enter name: ") # Remember: input() always returns a String! age = int(input("Enter age: "))

Arithmetic Operators

add = 5 + 4 # 9 div = 5 / 4 # 1.25 (Float division) fdiv = 5 // 4 # 1 (Floor division) expo = 5 ** 2 # 25 (5 to power 2) mod = 5 % 4 # 1 (Modulo: remainder)

Shorthand Assign

count = 10 count += 5 # Same as count = count + 5

🚦 Decisions & Conditions

Comparisons

x == y # True if x equals y x != y # True if x is not equal to y x > y # Greater than x <= y # Less than or equal to

Logical Connectors

cond_and = (x > 5) and (y < 10) cond_or = (x == 5) or (y == 10) cond_not = not (x > 5)

Branching Structure

marks = 75 if marks >= 80: print("A Grade") elif marks >= 60: print("B Grade") else: print("C Grade")

🔄 Loops & Iteration

For Loop & Range

# Loop from 0 to 4 for i in range(5): print(i) # Loop with custom step: range(start, stop, step) for i in range(10, 50, 10): print(i) # 10, 20, 30, 40

While Loop

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

Loop Controls

for i in range(10): if i == 5: break # Terminate loop if i % 2 == 0: continue # Skip to next iteration

📋 Lists (Arrays)

Creation & Indexes

fruits = ["apple", "banana", "cherry"] print(fruits[0]) # "apple" print(len(fruits)) # Length: 3

Mutating Lists

fruits.append("orange") # Adds to end fruits.insert(0, "mango") # Inserts at index 0 last = fruits.pop() # Removes and returns last fruits.remove("banana") # Removes first matching

Sorting & Searching

fruits.sort() # Alphabetical sort pos = fruits.index("cherry") # Finds index of occ = fruits.count("apple") # Occurrences of

🗂️ Tuples & Dictionaries

Tuples (Immutable)

# Cannot change values after declaration coords = (10.5, 20.3) x, y = coords # Tuple unpacking

Dictionaries (Key-Value)

student = { "name": "Peter", "age": 22, "course": "Python" } print(student["name"]) # "Peter" student["age"] = 23 # Mutate value student["email"] = "p@p.com" # Add new key-value

Iterating Dictionary

for key, val in student.items(): print(f"{key}: {val}")

🛠️ Functions & Scope

Defining Functions

def add_values(val1, val2): return val1 + val2 total = add_values(60, 60) # returns 120

Variable Scope

g_val = 100 # Global variable def print_scope(): l_val = 50 # Local variable print(l_val) # Works print(g_val) # Works # print(l_val) -> Error (l_val not defined outside)

📁 Modules & File I/O

Standard Modules

import random import datetime import math import time import statistics rand_num = random.randint(1, 10) # Random integer ceil_val = math.ceil(4.2) # Returns 5 current = datetime.datetime.now() # Date & Time formatted_date = current.strftime("%B %d, %Y") time.sleep(2) # Pause execution for 2 seconds mean_val = statistics.mean([2, 4])# Returns 3.0 (average)

Text File Handling

# Write mode (overwrites) with open("test.txt", "w") as file: file.write("First line\n") # Append mode with open("test.txt", "a") as file: file.write("Second line\n") # Read mode with open("test.txt", "r") as file: content = file.read()

🛢️ MySQL Databases

Database Connector

import mysql.connector # Connect to database mydb = mysql.connector.connect( host="localhost", user="root", password="password", database="school_db" # Optional if creating first ) mycursor = mydb.cursor()

Queries & Operations

# Creating table mycursor.execute("CREATE TABLE students (name VARCHAR(50), age INT)") # Inserting (requires committing transaction!) sql = "INSERT INTO students (name, age) VALUES (%s, %s)" val = ("Peter Parker", 22) mycursor.execute(sql, val) mydb.commit() # Save changes! # Selecting mycursor.execute("SELECT * FROM students") records = mycursor.fetchall() for row in records: print(row)