0% found this document useful (0 votes)
4 views11 pages

Python Phase2 Master Edition

Uploaded by

pllayerr2.0
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)
4 views11 pages

Python Phase2 Master Edition

Uploaded by

pllayerr2.0
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

Python Phase 2: Core Mechanics

The Master Edition: Live Code & Execution Outputs

1. Data Structures (Organizing Data)

How it works: Variables hold one item, but Data Structures hold entire collections. Lists
can be changed. Tuples are permanently locked. Dictionaries map "Keys" to "Values" (like a
real dictionary). Sets only keep unique items and destroy duplicates.

Example 1: List (Free Fire Loadout)

# Lists use square brackets [] and can be edited


loadout = ["M1887", "Desert Eagle"]
[Link]("Gloo Wall") # Adds to the end
print(loadout)

CONSOLE OUTPUT:

['M1887', 'Desert Eagle', 'Gloo Wall']

Example 2: Dictionary (ThinkPad Specs)

# Dictionaries use curly braces {} with key:value pairs


specs = {"brand": "Lenovo ThinkPad", "ram": 16, "cpu": "i5 8th Gen"}
print("Installed RAM:", specs["ram"], "GB")

CONSOLE OUTPUT:

Installed RAM: 16 GB

Example 3: Tuple (College Lab Timings)

# Tuples use parentheses () and cannot be altered


reporting_time = ("6:00 AM", "1:30 PM")
print("TTI Takatpur morning shift starts at:", reporting_time[0])

CONSOLE OUTPUT:

TTI Takatpur morning shift starts at: 6:00 AM


Example 4: Set (Anime Watchlist)

# Sets use {} but automatically remove duplicates


watched = {"Naruto", "Bleach", "Naruto"} # Accidentally added Naruto twice
print("Unique shows watched:", watched)

CONSOLE OUTPUT:

Unique shows watched: {'Naruto', 'Bleach'}

Example 5: Mixed Structures (Video Project)

# A dictionary containing a list


project = {
"app": "CapCut",
"layers": ["Audio.mp3", "Gameplay.mp4", "Text_Overlay"]
}
print("Top layer:", project["layers"][2])

CONSOLE OUTPUT:

Top layer: Text_Overlay


2. Error Handling (Try / Except)

How it works: If your code encounters a fatal error (like trying to open a file that doesn't
exist), the whole program crashes. A try/except block acts like a surge protector, catching
the error safely and keeping the program alive.

Example 1: Zero Division (K/D Ratio)

kills = 12
deaths = 0
try:
kd_ratio = kills / deaths
except ZeroDivisionError:
print("Error: Cannot divide by zero! Setting K/D to Perfect.")

CONSOLE OUTPUT:

Error: Cannot divide by zero! Setting K/D to Perfect.

Example 2: Missing Files (Alight Motion)

try:
file = open("lyrical_edit_project.xml", "r")
except FileNotFoundError:
print("Project file missing. Did you move it?")

CONSOLE OUTPUT:

Project file missing. Did you move it?

Example 3: Value Errors (Hardware Upgrades)

try:
# Trying to turn letters into a math number
target_ram = int("Sixteen")
except ValueError:
print("Invalid format! Please type '16' as a number.")

CONSOLE OUTPUT:

Invalid format! Please type '16' as a number.


Example 4: Key Errors (Dictionaries)

specs = {"ram": 16, "cpu": "i5"}


try:
print(specs["gpu"]) # GPU doesn't exist in our dictionary
except KeyError:
print("No Dedicated GPU found in system specs.")

CONSOLE OUTPUT:

No Dedicated GPU found in system specs.

Example 5: Catch-All Exceptions (Networking)

try:
# Simulating a sudden network drop
raise Exception("Connection Timeout")
except Exception as error_message:
print("Network Error Detected:", error_message)

CONSOLE OUTPUT:

Network Error Detected: Connection Timeout


3. File Handling (Reading & Writing)

How it works: Variables are erased when the program closes. File handling lets you
permanently write data to your hard drive (like text files or JSON databases) and read it back
later.

Example 1: Writing a File ('w' mode)

# 'w' creates the file or overwrites it completely


with open("router_config.txt", "w") as file:
[Link]("Primary DNS: [Link]")
print("Config saved successfully.")

CONSOLE OUTPUT:

Config saved successfully.

Example 2: Reading a File ('r' mode)

# 'r' reads the text inside


with open("router_config.txt", "r") as file:
data = [Link]()
print("Loaded Data:", data)

CONSOLE OUTPUT:

Loaded Data: Primary DNS: [Link]

Example 3: Appending a File ('a' mode)

# 'a' adds to the bottom without deleting what is already there


with open("server_log.txt", "a") as file:
[Link]("User Shiva logged in at 6:00 AM
")
print("Log updated.")

CONSOLE OUTPUT:

Log updated.
Example 4: Writing JSON (Saving Settings)

import json
settings = {"dpi": 510, "fire_button_size": 45}
with open("realme_settings.json", "w") as file:
[Link](settings, file)
print("Settings saved securely.")

CONSOLE OUTPUT:

Settings saved securely.

Example 5: Reading JSON (Loading Settings)

import json
with open("realme_settings.json", "r") as file:
loaded_settings = [Link](file)
print("Current DPI is:", loaded_settings["dpi"])

CONSOLE OUTPUT:

Current DPI is: 510


4. Modules & Packages (Importing)

How it works: Why reinvent the wheel? Modules are collections of code that other
programmers already wrote. By using the import command, you instantly grant your
program new powers (like complex math, RNG, or accessing the operating system).

Example 1: The 'math' Module

import math
damage = 45.8
# ceil() automatically rounds numbers UP to the nearest integer
print("Damage rounded up:", [Link](damage))

CONSOLE OUTPUT:

Damage rounded up: 46

Example 2: The 'random' Module

import random
loot_crate = ["AWM", "Groza", "M1887", "Level 3 Vest"]
# choice() picks one item entirely at random
print("You unboxed:", [Link](loot_crate))

CONSOLE OUTPUT:

You unboxed: Groza


(Output will change every time you run it)

Example 3: The 'datetime' Module

import datetime
# Gets the exact current time from your computer
now = [Link]()
print("Lab report generated at:", [Link]("%Y-%m-%d %H:%M"))

CONSOLE OUTPUT:

Lab report generated at: 2026-05-24 20:58


Example 4: The 'os' Module

import os
# Checks if a file physically exists on the hard drive
exists = [Link]("router_config.txt")
print("Does the config file exist?", exists)

CONSOLE OUTPUT:

Does the config file exist? True

Example 5: The 'time' Module

import time
print("Applying Medkit...")
[Link](1) # Pauses the code execution for 1 second
print("HP Restored!")

CONSOLE OUTPUT:

Applying Medkit...
HP Restored!
5. Object-Oriented Programming (Classes)

How it works: OOP lets you model code after the real world. A class is a blueprint. An
object is the actual item built from that blueprint. A class contains attributes (variables)
and methods (functions) that belong to it.

Example 1: Player Class

class Player:
def __init__(self, name):
[Link] = name
[Link] = 200

def take_damage(self, amount):


[Link] -= amount
print(f"{[Link]} took {amount} damage! HP: {[Link]}")

shiva = Player("Shiva") # Building the object


shiva.take_damage(50)

CONSOLE OUTPUT:

Shiva took 50 damage! HP: 150

Example 2: Laptop Class

class Laptop:
def __init__(self, model, ram):
[Link] = model
[Link] = ram

def upgrade_ram(self, extra_gb):


[Link] += extra_gb
print(f"{[Link]} upgraded! Now has {[Link]}GB RAM.")

my_pc = Laptop("ThinkPad L480", 8)


my_pc.upgrade_ram(8)

CONSOLE OUTPUT:

ThinkPad L480 upgraded! Now has 16GB RAM.


Example 3: Network Node Class

class Node:
def __init__(self, ip):
[Link] = ip
[Link] = "Offline"

def power_on(self):
[Link] = "Online"
print(f"Node {[Link]} is now {[Link]}.")

server = Node("[Link]")
server.power_on()

CONSOLE OUTPUT:

Node [Link] is now Online.

Example 4: Anime Character Class

class Ninja:
def __init__(self, name, jutsu):
[Link] = name
[Link] = jutsu

def attack(self):
print(f"{[Link]} uses {[Link]}!")

naruto = Ninja("Naruto", "Rasengan")


[Link]()

CONSOLE OUTPUT:

Naruto uses Rasengan!


Example 5: Video Editor Class

class Project:
def __init__(self, title):
[Link] = title

def render(self, resolution):


print(f"Exporting '{[Link]}' in {resolution}...")

lyrical_video = Project("Anime_AMV_Final")
lyrical_video.render("1080p")

CONSOLE OUTPUT:

Exporting 'Anime_AMV_Final' in 1080p...

You might also like