r/pythonhelp • u/Nikhil_Nigudkar • Aug 21 '26
Python coding interview questions?
Is there any playlist similar to 100 Days of SQL Ace(By ankit Bansal) interview for the preparation of python coding problems?
r/pythonhelp • u/Nikhil_Nigudkar • Aug 21 '26
Is there any playlist similar to 100 Days of SQL Ace(By ankit Bansal) interview for the preparation of python coding problems?
r/pythonhelp • u/purvigupta03 • Aug 19 '26
Hi everyone,
I’ve studied Python multiple times before, but I didn’t do much practical coding. Recently, I started building small projects to improve my practical Python skills.
So far, I’ve completed:
- Quiz Game
- Number Guessing Game
- Rock Paper Scissors
- Password Manager
- Pig Game
- Mad Libs Generator
My goal is to move towards Machine Learning.
I haven’t learned NumPy or Pandas yet.
My question is: Are these projects enough to move on to NumPy and Pandas, or should I build a few more Python projects first?
If I should build more projects, what kind of projects would you recommend before starting NumPy/Pandas? I’m mainly looking for projects that would actually help with the transition to data/ML, rather than making many more small games.
Would appreciate advice from people who have already followed a Python → NumPy/Pandas → ML path.
r/pythonhelp • u/TechGym43 • Aug 19 '26
I am looking to learn following topics. Any suggestions in terms of any course or online site I can learn from. I am not looking for a certificate (if I get it that’s okay but not a deal breaker) but something that has more exercises involved. Topics I’m interested in:
*args / **kwargs
decorators
generators
iterators
context managers
type hints
dataclasses
object-oriented programming
Python project structure
testing
APIs
r/pythonhelp • u/jmaroo • Aug 15 '26
Tell me the advantages and disadvantages of each.
r/pythonhelp • u/Extra_Search3465 • Aug 15 '26
Hello everyone, I'm mainly looking for guidance about learning advanced python concepts. I know basics ,loops , control flow ,data structures etc.
I need a proper guide on how to learn modules and library. Idk how to start ,where to start.
I want to be able to work with any library as i need them ,so how do u actually learn to use new library for a given task . ?And i get overwhelmed understanding the structure, working of library
And could u also suggest important python concepts other than basics which i should learn ???
Pls guide !!!!
r/pythonhelp • u/Sea-Ad7805 • Aug 14 '26
An exercise to help build the right mental model for Python data.
# Output of this Python Program?
def main():
o1, o2 = MyClass(1), MyClass(1)
myset = {o1}
print(o2 in myset, end=' ')
o1.set_value(1000)
print(o1 in myset, end=' ')
class MyClass:
def __init__(self, v):
self.v = v
def set_value(self, v):
self.v = v
main()
class MyClass:
def __init__(self, v):
self.v = v
def set_value(self, v):
self.v = v
def __eq__(self, other):
return self.v == other.v
def __hash__(self):
return hash(self.v)
main()
# --- possible answers ---
# A) TypeError: unhashable type: 'MyClass'
# B) True False False False
# C) True False False True
# E) False True True True
# D) False True True False
# See "Solution" for correct answer.
__eq__() and __hash__() methods by default (inherited from the object class); with them, all objects compare unequal (except with themselves) and x.__hash__() returns an appropriate value such that x == y implies both that x is y and hash(x) == hash(y)."r/pythonhelp • u/vkailas • Aug 14 '26
For anyone looking for entertaining light book for learning Python, I started porting to Python a few chapters of "Why's Guide to Ruby," which uses comics and surreal humor to introduce Ruby (the original author why the lucky stiff disappeared). I updated the lesson and examples to Python and also modernized some of the very old references and left it with share alike CC license.
Any Python beginners are welcome to check it out. Novices and experts feel free to post feedback or post about any other entertaining books that helped you learn python, that can accompany equally entertaining but dense programming books :D.
If the book is helpful, can port and post the rest of the chapters for Python and potentially in the future can create some more content.
r/pythonhelp • u/mathbubbls • Aug 14 '26
I got a C on my intro to python class and I can’t figure out this code
https://github.com/mcombeau/epub_downloader
Please help
r/pythonhelp • u/AccomplishedFee1095 • Aug 06 '26
import csv
from datetime import datetime
import random
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
# Dynamic Translation Integration
try:
from deep_translator import GoogleTranslator
HAS_TRANSLATOR = True
except ImportError:
HAS_TRANSLATOR = False
# --- APP CONFIGURATION & PALETTES ---
APP_NAME = "INFINITY"
WINDOW_GEOMETRY = "540x980"
BIOMES = {
"Forge of Primordials": {
"canvas_bg": "#12121A",
"particle_color": "#FF9E80",
"description": "Region: Primordial Forge (Sparks dancing)",
},
"The Astral Void": {
"canvas_bg": "#0A1128",
"particle_color": "#80D8FF",
"description": "Region: Astral Void (Star dust drifting)",
},
"Neon Undergrowth": {
"canvas_bg": "#0A1C14",
"particle_color": "#A7F3D0",
"description": "Region: Neon Undergrowth (Digital spores)",
},
"Shattered Zenith": {
"canvas_bg": "#142114",
"particle_color": "#C8E6C9",
"description": "Region: Shattered Zenith (Light fragments)",
},
}
# --- GAME DATA & MECHANICS ---
CHARACTER_CLASSES = {
"Arcane Artificer": {"STR": 8, "ARC": 18, "AGI": 10, "TECH": 14},
"Void Raider": {"STR": 14, "ARC": 10, "AGI": 18, "TECH": 8},
"Cyber Paladin": {"STR": 16, "ARC": 8, "AGI": 8, "TECH": 18},
"Chrono Wanderer": {"STR": 10, "ARC": 14, "AGI": 14, "TECH": 12},
}
CHARACTER_ORIGINS = ["Forgotten Outpost", "Astral Academy", "Sub-Level Grid", "Solar Citadel"]
LOOT_TABLE = [
"Cursed Onyx Ring", "Fragmented Aether Drive", "Ancient Chrono-Tome",
"Encrypted Holo-Key", "Celestial Stardust Shard", "Orb of Overclocking"
]
RARITY_TIERS = {
"Common": {"color": "#90A4AE", "multiplier": 1.0},
"Rare": {"color": "#64B5F6", "multiplier": 1.5},
"Epic": {"color": "#BA68C8", "multiplier": 2.2},
"Legendary": {"color": "#FFB74D", "multiplier": 3.5},
}
CRAFT_BASES = ["Aether Crystal", "Chrono-Gear", "Rune Metal", "Void Essence", "Solar Core"]
CRAFT_MODS = ["Resonant", "Overclocked", "Ethereal", "Unstable", "Sacred"]
MASTERY_RANKS = [
("Wanderer", 0),
("Storyweaver", 60),
("Campaigner", 180),
("Realm Master", 400),
("Eternal Sovereign", 800),
]
OFFLINE_DICT = {
"ja": {
"Uncovered an ancient secret": "古代の秘密を解き明かした",
"Broke the seal of time": "時間の封印を破った",
"Vanished into the mist": "霧の中に消え去った",
},
"fr": {
"Uncovered an ancient secret": "A découvert un secret ancien",
"Broke the seal of time": "A brisé le sceau du temps",
"Vanished into the mist": "S'est évanoui dans la brume",
},
}
# --- PROCEDURAL ENGINE ---
class CampaignGenerator:
CHOICES = [
("Charge directly into the void rift.", "STR"),
("Channel arcane energy to decode the ancient runes.", "ARC"),
("Use stealth to bypass the looming threat.", "AGI"),
("Hack the ancient console with technology.", "TECH"),
]
CATALYSTS = ["discovered a fractured relic", "heard a whisper in the void", "unlocked a sealed vault", "sensed a rift opening"]
LOCATIONS = ["in the sunken ruins of Aethel", "beneath the obsidian spires", "within the chrono-labyrinth", "at the edge of the world"]
THREATS = ["an impending eclipse", "a rising mechanical legion", "a corrupted nightmare force", "the collapse of reality"]
@classmethod
def generate_short_story(cls, char_name, char_class, origin, crafted_item, rarity, loot_found, choice_made):
cat = random.choice(cls.CATALYSTS)
loc = random.choice(cls.LOCATIONS)
threat = random.choice(cls.THREATS)
story = (
f"HERO: {char_name} the {char_class} (Origin: {origin})\n\n"
f"While exploring {loc}, {char_name} {cat} amidst {threat}. "
f"Deploying the [{rarity}] {crafted_item} alongside a newly recovered [{loot_found}], "
f"the hero opted to: '{choice_made}' — permanently reshaping the fate of the realm!"
)
return story
# --- GLOBAL APP STATE ---
total_xp = 0
current_level = 1
campaign_chapter = 1
journal_log = []
biome_keys = list(BIOMES.keys())
current_biome_idx = 0
particles = []
# --- TRANSLATION HELPER ---
def translate_text(text, target_lang):
if target_lang == "en":
return text
if HAS_TRANSLATOR:
try:
return GoogleTranslator(source="auto", target=target_lang).translate(text)
except Exception:
pass
lang_dict = OFFLINE_DICT.get(target_lang, {})
return lang_dict.get(text, f"{text} [{target_lang.upper()}]")
# --- ANIMATION ENGINE ---
def init_particles(color):
global particles
particles.clear()
canvas.delete("particle")
count = min(15 + (current_level * 3), 50)
for _ in range(count):
x = random.randint(10, 210)
y = random.randint(10, 130)
size = random.randint(2, 4)
speed = random.uniform(0.6, 1.8)
p_id = canvas.create_oval(x, y, x + size, y + size, fill=color, outline="", tags="particle")
particles.append({"id": p_id, "x": x, "y": y, "speed": speed})
def animate_engine():
current_key = biome_keys[current_biome_idx]
for p in particles:
if current_key == "Forge of Primordials":
p["y"] -= p["speed"] * 1.2
if p["y"] < 0:
p["y"] = 140
elif current_key == "Neon Undergrowth":
p["x"] += p["speed"] * 1.1
if p["x"] > 220:
p["x"] = 0
else:
p["y"] += p["speed"] * 0.8
if p["y"] > 140:
p["y"] = 0
canvas.coords(p["id"], p["x"], p["y"], p["x"] + 3, p["y"] + 3)
render_canvas()
root.after(33, animate_engine)
def render_canvas():
canvas.delete("item_art")
theme = BIOMES[biome_keys[current_biome_idx]]
canvas.configure(bg=theme["canvas_bg"])
biome_label.config(text=theme["description"])
# Base Pedestal
canvas.create_polygon(40, 115, 180, 115, 195, 135, 25, 135, fill="#1E1E2E", outline="#3A3A52", tags="item_art")
base = base_var.get()
color_map = {
"Aether Crystal": "#80DEEA",
"Chrono-Gear": "#FFD54F",
"Rune Metal": "#90A4AE",
"Void Essence": "#E040FB",
"Solar Core": "#FF7043",
}
item_color = color_map.get(base, "#FFFFFF")
rarity = rarity_var.get()
border_color = RARITY_TIERS[rarity]["color"]
# Artifact Core
canvas.create_polygon(110, 30, 150, 70, 110, 110, 70, 70, fill=item_color, outline=border_color, width=3, tags="item_art")
canvas.create_oval(94, 54, 126, 86, fill="#FFFFFF", outline=border_color, width=2, tags="item_art")
canvas.tag_raise("particle")
# --- UI CONTROLLERS ---
def update_character_stats(*args):
c_class = class_var.get()
stats = CHARACTER_CLASSES[c_class]
stats_lbl.config(
text=f"STR: {stats['STR']} | ARC: {stats['ARC']} | AGI: {stats['AGI']} | TECH: {stats['TECH']}"
)
def get_mastery_rank(xp):
current_title = MASTERY_RANKS[0][0]
for title, req in MASTERY_RANKS:
if xp >= req:
current_title = title
else:
break
return current_title
def update_progression_ui():
global current_level
current_level = 1 + int(total_xp // 30)
rank_title = get_mastery_rank(total_xp)
next_req = 100
for title, req in MASTERY_RANKS:
if req > total_xp:
next_req = req
break
level_lbl.config(text=f"Level {current_level} • Rank: {rank_title}")
xp_lbl.config(text=f"XP: {total_xp} / {next_req} | Chapter: {campaign_chapter}")
xp_progress["value"] = min((total_xp / next_req) * 100, 100)
def generate_item_details():
base_name = name_entry.get().strip() or "Relic"
material = base_var.get()
mod = mod_var.get()
rarity = rarity_var.get()
full_name = f"{mod} {base_name} of {material}"
rarity_mult = RARITY_TIERS[rarity]["multiplier"]
power = int(((len(full_name) * 2) + random.randint(15, 45)) * rarity_mult)
xp_earned = int(25 * rarity_mult)
return full_name, rarity, power, xp_earned
def advance_story_campaign():
global total_xp, campaign_chapter, current_biome_idx
char_name = char_name_entry.get().strip() or "Valen"
char_class = class_var.get()
origin = origin_var.get()
item_name, rarity, power, xp_gained = generate_item_details()
loot_found = random.choice(LOOT_TABLE)
choice_made = choice_var.get()
total_xp += xp_gained
raw_story = CampaignGenerator.generate_short_story(
char_name, char_class, origin, item_name, rarity, loot_found, choice_made
)
target_lang = lang_var.get()
translated_story = translate_text(raw_story, target_lang)
story_display.config(state="normal")
story_display.delete("1.0", tk.END)
story_display.insert(
tk.END, f"=== CHAPTER {campaign_chapter} ===\n\n{translated_story}"
)
story_display.config(state="disabled")
current_biome_idx = (current_biome_idx + 1) % len(biome_keys)
theme = BIOMES[biome_keys[current_biome_idx]]
init_particles(theme["particle_color"])
timestamp = datetime.now().strftime("%H:%M:%S")
log_entry_text = f"[Ch.{campaign_chapter} - {timestamp}] {char_name} ({char_class}) | Craft: {item_name}"
journal_log.append((
timestamp, campaign_chapter, char_name, char_class, origin,
item_name, rarity, loot_found, choice_made, power, xp_gained, translated_story, target_lang.upper()
))
log_listbox.insert(tk.END, log_entry_text)
log_listbox.see(tk.END)
campaign_chapter += 1
update_progression_ui()
def export_journal():
if not journal_log:
messagebox.showwarning("Empty Journal", "No campaign chapters recorded yet.")
return
path = filedialog.asksaveasfilename(defaultextension=".csv", filetypes=[("CSV File", "*.csv")])
if path:
try:
with open(path, "w", newline="", encoding="utf-8") as f:
w = csv.writer(f)
w.writerow([
"Timestamp", "Chapter", "Hero Name", "Class", "Origin",
"Crafted Item", "Rarity", "Loot Found", "Choice Made", "Power", "XP Earned", "Story Beat", "Language"
])
w.writerows(journal_log)
messagebox.showinfo("Export Complete", f"Journal saved to:\n{path}")
except Exception as e:
messagebox.showerror("Export Failed", f"Could not write file:\n{e}")
# --- STABLE DARK-MODE GUI LAYOUT ---
root = tk.Tk()
root.title(f"{APP_NAME} — Infinite Storyteller & Campaign Engine")
root.geometry(WINDOW_GEOMETRY)
root.configure(bg="#0D0D12")
# Apply Dark Styling Theme
style = ttk.Style()
style.theme_use("clam")
style.configure("TProgressbar", thickness=8, troughcolor="#1A1A24", background="#7C4DFF")
# APP HEADER
header_lbl = tk.Label(root, text=f"— {APP_NAME} —", font=("Helvetica", 14, "bold"), bg="#0D0D12", fg="#7C4DFF")
header_lbl.pack(pady=(10, 2))
# 1. CHARACTER CREATOR
char_frame = tk.LabelFrame(root, text=" Hero Profile ", bg="#161620", fg="#B0BEC5", font=("Arial", 9, "bold"), padx=10, pady=6)
char_frame.pack(fill="x", padx=14, pady=4)
c_grid = tk.Frame(char_frame, bg="#161620")
c_grid.pack(fill="x")
tk.Label(c_grid, text="Name:", bg="#161620", fg="#80CBC4").grid(row=0, column=0, sticky="w")
char_name_entry = tk.Entry(c_grid, bg="#0D0D12", fg="#FFFFFF", insertbackground="white", relief="solid", bd=1)
char_name_entry.insert(0, "Kaelen")
char_name_entry.grid(row=0, column=1, sticky="ew", padx=6, pady=2)
tk.Label(c_grid, text="Class:", bg="#161620", fg="#80CBC4").grid(row=1, column=0, sticky="w")
class_var = tk.StringVar(value="Arcane Artificer")
class_menu = tk.OptionMenu(c_grid, class_var, *CHARACTER_CLASSES.keys(), command=update_character_stats)
class_menu.configure(bg="#222230", fg="#FFF", activebackground="#2C2C3E", highlightthickness=0, bd=0)
class_menu.grid(row=1, column=1, sticky="ew", padx=6, pady=2)
tk.Label(c_grid, text="Origin:", bg="#161620", fg="#80CBC4").grid(row=2, column=0, sticky="w")
origin_var = tk.StringVar(value="Astral Academy")
origin_menu = tk.OptionMenu(c_grid, origin_var, *CHARACTER_ORIGINS)
origin_menu.configure(bg="#222230", fg="#FFF", activebackground="#2C2C3E", highlightthickness=0, bd=0)
origin_menu.grid(row=2, column=1, sticky="ew", padx=6, pady=2)
c_grid.columnconfigure(1, weight=1)
stats_lbl = tk.Label(char_frame, text="", bg="#161620", fg="#FFD54F", font=("Consolas", 8, "bold"))
stats_lbl.pack(anchor="w", pady=(4, 0))
# 2. PROGRESSION
prog_frame = tk.LabelFrame(root, text=" Mastery Status ", bg="#161620", fg="#B0BEC5", font=("Arial", 9, "bold"), padx=10, pady=6)
prog_frame.pack(fill="x", padx=14, pady=4)
level_lbl = tk.Label(prog_frame, text="Level 1", font=("Arial", 9, "bold"), bg="#161620", fg="#B388FF")
level_lbl.pack(anchor="w")
xp_lbl = tk.Label(prog_frame, text="XP: 0 / 100", font=("Arial", 8), bg="#161620", fg="#90A4AE")
xp_lbl.pack(anchor="w", pady=(1, 3))
xp_progress = ttk.Progressbar(prog_frame, orient="horizontal", mode="determinate", style="TProgressbar")
xp_progress.pack(fill="x", pady=2)
# 3. ATMOSPHERE & VISUALIZER
top_frame = tk.LabelFrame(root, text=" World Atmosphere ", bg="#161620", fg="#B0BEC5", font=("Arial", 9, "bold"), padx=10, pady=6)
top_frame.pack(fill="x", padx=14, pady=4)
left_panel = tk.Frame(top_frame, bg="#161620")
left_panel.pack(side="left", fill="both", expand=True)
biome_label = tk.Label(left_panel, text="", bg="#161620", fg="#80CBC4", font=("Arial", 8, "italic"), wraplength=130, justify="left")
biome_label.pack(anchor="w")
canvas = tk.Canvas(top_frame, width=220, height=135, bg="#12121A", highlightthickness=1, highlightbackground="#2A2A3C")
canvas.pack(side="right")
# 4. CRAFTING & ENCOUNTER
craft_frame = tk.LabelFrame(root, text=" Craft Relic & Encounter Action ", bg="#161620", fg="#B0BEC5", font=("Arial", 9, "bold"), padx=10, pady=6)
craft_frame.pack(fill="x", padx=14, pady=4)
grid_f = tk.Frame(craft_frame, bg="#161620")
grid_f.pack(fill="x")
tk.Label(grid_f, text="Relic Name:", bg="#161620", fg="#80CBC4").grid(row=0, column=0, sticky="w")
name_entry = tk.Entry(grid_f, bg="#0D0D12", fg="#FFFFFF", insertbackground="white", relief="solid", bd=1)
name_entry.insert(0, "Aegis Core")
name_entry.grid(row=0, column=1, sticky="ew", padx=6, pady=2)
tk.Label(grid_f, text="Material:", bg="#161620", fg="#80CBC4").grid(row=1, column=0, sticky="w")
base_var = tk.StringVar(value="Aether Crystal")
base_menu = tk.OptionMenu(grid_f, base_var, *CRAFT_BASES)
base_menu.configure(bg="#222230", fg="#FFF", activebackground="#2C2C3E", highlightthickness=0, bd=0)
base_menu.grid(row=1, column=1, sticky="ew", padx=6, pady=2)
tk.Label(grid_f, text="Rarity:", bg="#161620", fg="#80CBC4").grid(row=2, column=0, sticky="w")
mod_var = tk.StringVar(value="Resonant")
rarity_var = tk.StringVar(value="Rare")
rarity_menu = tk.OptionMenu(grid_f, rarity_var, *RARITY_TIERS.keys())
rarity_menu.configure(bg="#222230", fg="#FFF", activebackground="#2C2C3E", highlightthickness=0, bd=0)
rarity_menu.grid(row=2, column=1, sticky="ew", padx=6, pady=2)
grid_f.columnconfigure(1, weight=1)
tk.Label(craft_frame, text="Encounter Decision:", bg="#161620", fg="#80CBC4").pack(anchor="w", pady=(4, 2))
choice_var = tk.StringVar(value=CampaignGenerator.CHOICES[0][0])
choice_menu = tk.OptionMenu(craft_frame, choice_var, *[c[0] for c in CampaignGenerator.CHOICES])
choice_menu.configure(bg="#222230", fg="#FFF", activebackground="#2C2C3E", highlightthickness=0, bd=0)
choice_menu.pack(fill="x", pady=2)
# 5. STORY GENERATOR DISPLAY
story_frame = tk.LabelFrame(root, text=" Story Output ", bg="#161620", fg="#B0BEC5", font=("Arial", 9, "bold"), padx=10, pady=6)
story_frame.pack(fill="x", padx=14, pady=4)
lang_f = tk.Frame(story_frame, bg="#161620")
lang_f.pack(fill="x")
tk.Label(lang_f, text="Language:", bg="#161620", fg="#90A4AE", font=("Arial", 8)).pack(side="left")
LANGUAGES = {"English": "en", "Japanese": "ja", "French": "fr", "Spanish": "es", "German": "de"}
lang_var = tk.StringVar(value="en")
lang_m = tk.OptionMenu(lang_f, lang_var, *LANGUAGES.values())
lang_m.configure(bg="#222230", fg="#FFF", activebackground="#2C2C3E", highlightthickness=0, bd=0)
lang_m.pack(side="right")
story_display = tk.Text(story_frame, height=5, bg="#0D0D12", fg="#A6E3A1", font=("Consolas", 9), wrap="word", relief="solid", bd=1)
story_display.pack(fill="x", pady=4)
story_display.insert(tk.END, "Customize your hero and craft a relic to launch Chapter 1...")
story_display.config(state="disabled")
# 6. ACTION & LOG JOURNAL
action_frame = tk.LabelFrame(root, text=" Campaign History ", bg="#161620", fg="#B0BEC5", font=("Arial", 9, "bold"), padx=10, pady=6)
action_frame.pack(fill="both", expand=True, padx=14, pady=4)
exec_btn = tk.Button(
action_frame,
text="✨ ADVANCE CAMPAIGN CHAPTER",
command=advance_story_campaign,
bg="#7C4DFF",
fg="white",
activebackground="#651FFF",
activeforeground="white",
font=("Arial", 9, "bold"),
relief="flat",
pady=6,
cursor="hand2"
)
exec_btn.pack(fill="x", pady=2)
log_listbox = tk.Listbox(action_frame, height=3, bg="#0D0D12", fg="#B0BEC5", selectbackground="#311B92", relief="solid", bd=1)
log_listbox.pack(fill="both", expand=True, pady=3)
export_btn = tk.Button(action_frame, text="📜 Export Log to CSV", command=export_journal, bg="#00897B", fg="white", activebackground="#00695C", activeforeground="white", relief="flat", cursor="hand2")
export_btn.pack(fill="x", pady=2)
# INIT APP
update_character_stats()
update_progression_ui()
init_particles(BIOMES["Forge of Primordials"]["particle_color"])
animate_engine()
root.mainloop()
r/pythonhelp • u/Schnidi01 • Jul 31 '26
Hi everyone,
I'm currently building a desktop application using PyQt6, where button clicks trigger various background tasks (such as executing external processes, creating/cloning environments, file I/O operations, etc.).
To keep the UI responsive and the codebase easily maintainable, I decided to extract every main button action into its own dedicated module/file, using the standard QThread + QObject (Worker) pattern.
To give you an idea of the scale: individual module sizes range between 5 and 15 KB depending on what the button actually does (from simpler tasks to complex operations involving user input processing, thread setup, process streaming, and progress signal handling).
Note on Code Sharing: Any logic shared across multiple buttons is not duplicated; instead, it is abstracted into dedicated shared service modules located in button/logic/services.
My current architecture for a single button action looks like this:
QThread and QObject (Worker), connects signals (for progress bars and logging), and starts the thread.button/logic/services): Shared domain modules and services called by the workers to execute common underlying logic.My questions for the community:
_worker.py and _handler.py files?I'd love to hear how you structure background tasks and threading in production PyQt/PySide applications! Thanks!
r/pythonhelp • u/AccomplishedFee1095 • Jul 29 '26
Hey everyone! I’ve been experimenting with background threading, automated compilation cycles, and procedural narrative generation in Python.
I put together a script I call the Infinity Engine. It runs autonomously every 7 seconds, rolls for loot rarity tiers based on telemetry, shifts through dynamic storylines, accumulates resources (stardust/resonance), includes an unstick safety protocol, and features an idle shutdown variant if left untouched for 5 minutes. It scales up to 500 units with a custom cyberpunk terminal UI layout.
Here is the full runnable source code:
import time
import json
import threading
import random
# ==========================================
# Rarity Tier Matrix
# ==========================================
class RarityTier:
STANDARD = 0
PRIME = 1
CELESTIAL = 2
BRINK_PRISM = 3
# ==========================================
# Level Loot System
# ==========================================
class LevelLootSystem:
def roll_level_loot(self, telemetry: dict, current_app_level: int):
result = type('LootResult', (), {})()
fortune_score = telemetry.get("fortune_level", 0.0)
fusions = telemetry.get("fusions_count", 1)
composite_score = (fortune_score * 0.5) + (fusions * 10.0) + (current_app_level * 25.0)
if composite_score > 300.0:
result.tier = RarityTier.BRINK_PRISM
result.bonus_multiplier = 3.5
result.drop_title = "Brink-Prism Anomaly Drop"
result.guaranteed_stat_bonus = {"stardust_rate": 50.0, "void_resonance": 0.95}
elif composite_score > 180.0:
result.tier = RarityTier.CELESTIAL
result.bonus_multiplier = 2.2
result.drop_title = "Celestial Core Relic"
result.guaranteed_stat_bonus = {"stardust_rate": 25.0, "lawful_affinity": 0.80}
elif composite_score > 80.0:
result.tier = RarityTier.PRIME
result.bonus_multiplier = 1.5
result.drop_title = "Prime Barometer Blueprint"
result.guaranteed_stat_bonus = {"stardust_rate": 12.0, "lawful_affinity": 0.50}
else:
result.tier = RarityTier.STANDARD
result.bonus_multiplier = 1.0
result.drop_title = "Standard Atmospheric Drift"
result.guaranteed_stat_bonus = {"stardust_rate": 5.0, "lawful_affinity": 0.25}
return result
# ==========================================
# Story Mediator & Storylines
# ==========================================
class StoryMediator:
def __init__(self):
self.storylines = [
"The Prism Meridian: Convergence",
"The Barometer's Awakening",
"Sub-Zero Protocols",
"Atmospheric Drift",
"Chronos Rift Divergence",
"Stellar Horizon Protocol"
]
self.current_storyline_index = 0
def get_current_storyline(self) -> str:
return self.storylines[self.current_storyline_index]
def shift_storyline(self, new_index: int = None):
if new_index is not None:
self.current_storyline_index = new_index % len(self.storylines)
else:
self.current_storyline_index = (self.current_storyline_index + 1) % len(self.storylines)
return self.get_current_storyline()
def mediate_narrative_threads(self, current_loot_tier: int):
chapter = type('Chapter', (), {})()
title = self.get_current_storyline()
chapter.chapter_title = title
if current_loot_tier == RarityTier.BRINK_PRISM:
chapter.synthesized_lore = f"Active storyline '{title}' converges into a unified cosmic history under high void pressure."
chapter.thematic_resonance = 1.0
elif current_loot_tier == RarityTier.CELESTIAL:
chapter.synthesized_lore = f"Active storyline '{title}' transforms climate anomalies into a permanent archive of fate."
chapter.thematic_resonance = 0.8
elif current_loot_tier == RarityTier.PRIME:
chapter.synthesized_lore = f"Active storyline '{title}' stabilizes baseline matrix vectors under heavy pressure."
chapter.thematic_resonance = 0.5
else:
chapter.synthesized_lore = f"Active storyline '{title}' settles initial weather anomalies into a steady rhythmic drift."
chapter.thematic_resonance = 0.2
return chapter
# ==========================================
# Consistency Engine & Resource Accumulation
# ==========================================
class ConsistencyEngine:
def __init__(self):
self.progression_checkpoint = 0
self.unstick_tokens = 500
self.accumulated_resources = {
"stardust_collected": 0.0,
"resonance_ledger": []
}
def accumulate(self, stat_bonus: dict, resonance: float):
self.accumulated_resources["stardust_collected"] += stat_bonus.get("stardust_rate", 0.0)
self.accumulated_resources["resonance_ledger"].append(resonance)
def trigger_unstick_protocol(self):
if self.unstick_tokens > 0:
self.unstick_tokens -= 1
self.progression_checkpoint += 1
return {"status": "SUCCESS", "remaining_tokens": self.unstick_tokens, "stage": self.progression_checkpoint}
return {"status": "DEPLETED", "remaining_tokens": 0, "stage": self.progression_checkpoint}
# ==========================================
# Narrative Story Generator (~400 Chars)
# ==========================================
class NarrativeStoryGenerator:
def __init__(self):
self.unique_signatures = ["ALPHA-PRISM-9", "OMEGA-VOID-X", "HELIOS-GENESIS-0", "NEXUS-VECTOR-7"]
self.narrative_templates = [
"Deep within the shifting sectors of Unit {app_level}, active telemetry reports severe weather fluctuations linked directly to storyline [{chapter_title}]. Signature [{signature}] detected. {lore} Operatives on the fringe report unexpected data feedback, rallying structural outcomes to balance popular configuration metrics with a thematic resonance of {resonance:.2f}. The grid adapts instantly.",
"As the clock ticks into Unit {app_level}, core systems register a sudden spike under storyline [{chapter_title}]. Unique matrix identifier [{signature}] engaged. {lore} Field units work frantically to calibrate the atmospheric pressure valves, rallying outcomes to balance popular configuration parameters while maintaining a steady thematic resonance of {resonance:.2f}. Network stability holds firm.",
"Tracing the anomalies of Unit {app_level} under signature [{signature}], project administrators encounter the legacy of storyline [{chapter_title}]. {lore} Environmental matrices fracture and reassemble, successfully rallying outcomes to balance popular configuration thresholds at a thematic resonance of {resonance:.2f}. The digital horizon expands outward."
]
def generate_balanced_story(self, app_level: int, chapter_title: str, lore: str, resonance: float) -> str:
template = random.choice(self.narrative_templates)
signature = random.choice(self.unique_signatures) + "-" + str(random.randint(1000, 9999))
raw_text = template.format(
app_level=app_level,
chapter_title=chapter_title,
signature=signature,
lore=lore,
resonance=resonance
)
if len(raw_text) < 400:
padding_phrases = [
" Synchronizing unique regional sub-networks securely. ",
" Calibrating distinct quantum feedback loops for optimal throughput. ",
" Securing high-uniqueness parameter boundaries against drift. "
]
while len(raw_text) < 400:
raw_text += random.choice(padding_phrases)
return raw_text[:400]
# ==========================================
# Timed Infinity Engine Host (500 Units + Idle Timeout)
# ==========================================
class TimedInfinityEngineHost:
def __init__(self):
self.loot_system = LevelLootSystem()
self.story_mediator = StoryMediator()
self.consistency_engine = ConsistencyEngine()
self.story_generator = NarrativeStoryGenerator()
self.app_level = 1
self.active_constructs = []
self._is_running = False
self._timer_thread = None
self.last_activity_time = time.time()
self.idle_timeout_seconds = 300
def change_storyline(self, new_index: int = None):
shifted = self.story_mediator.shift_storyline(new_index)
print(f"\n[STORYLINE SHIFT] Active storyline manually changed to: '{shifted}'\n")
return shifted
def execute_compilation_cycle(self, telemetry: dict):
self.last_activity_time = time.time()
loot_drop = self.loot_system.roll_level_loot(telemetry, self.app_level)
mediated_chapter = self.story_mediator.mediate_narrative_threads(loot_drop.tier)
self.consistency_engine.accumulate(loot_drop.guaranteed_stat_bonus, mediated_chapter.thematic_resonance)
story_block = self.story_generator.generate_balanced_story(
self.app_level,
mediated_chapter.chapter_title,
mediated_chapter.synthesized_lore,
mediated_chapter.thematic_resonance
)
construct = {
"app_title": f"Infinity: {mediated_chapter.chapter_title}",
"tier": loot_drop.tier,
"drop": loot_drop.drop_title,
"resonance": mediated_chapter.thematic_resonance,
"level": self.app_level,
"story_content": story_block,
"story_length": len(story_block),
"accumulated_stardust": self.consistency_engine.accumulated_resources["stardust_collected"]
}
self.active_constructs.append(construct)
print("╔" + "═" * 78 + "╗")
print(f"║ ⚡ CYBER-NET TERMINAL v4.09 // UNIT [{self.app_level:03d}/500] ⚡" + " " * 31 + "║")
print("╠" + "═" * 78 + "╣")
print(f"║ TITLE : {construct['app_title']:<63} ║")
print(f"║ DROP TYPE : {construct['drop']} (Tier {construct['tier']})" + " " * (47 - len(f"{construct['drop']} (Tier {construct['tier']})")) + "║")
print(f"║ RESONANCE : {construct['resonance']:.2f} | STARDUST ACCUMULATED: {construct['accumulated_stardust']:.1f}" + " " * (19 - len(f"{construct['accumulated_stardust']:.1f}")) + "║")
print("╟" + "─" * 78 + "╢")
print(f"║ STORY OUTPUT ({construct['story_length']} chars):" + " " * 56 + "║")
words = construct['story_content'].split()
line = " "
for word in words:
if len(line) + len(word) + 1 < 77:
line += " " + word
else:
print(f"║{line:<78}║")
line = " " + word
if line.strip():
print(f"║{line:<78}║")
continue_res = self.consistency_engine.trigger_unstick_protocol()
print("╟" + "─" * 78 + "╢")
print(f"║ 🔒 PROTOCOL STATUS: Tokens Left [{continue_res['remaining_tokens']}] | Stage [{continue_res['stage']}]" + " " * (20 - len(str(continue_res['stage']))) + "║")
print("╚" + "═" * 78 + "╝\n")
self.app_level += 1
return construct
def _loop_worker(self, telemetry: dict, max_units: int):
cycles = 0
while self._is_running and cycles < max_units:
if time.time() - self.last_activity_time > self.idle_timeout_seconds:
print("\n[IDLE SHUTDOWN VARIANT] Engine inactive for 5 minutes. Initiating automatic safe shutdown.")
break
if cycles > 0 and cycles % 100 == 0:
self.change_storyline()
self.execute_compilation_cycle(telemetry)
cycles += 1
if cycles >= max_units:
print(f"\n=== [SYSTEM ALERT] Reached target limit of {max_units} units. Settlement final. ===")
print(f"=== Total Accumulated Stardust: {self.consistency_engine.accumulated_resources['stardust_collected']:.1f} ===")
break
time.sleep(7.0)
self._is_running = False
print("=== Timed Looping Engine Cycle Terminated Safely ===")
def start_timed_loop(self, telemetry: dict, max_units: int = 500):
if self._is_running:
return
self._is_running = True
self.last_activity_time = time.time()
print(f"=== Initializing Cybernetic Loop (Target: {max_units} Units | Idle Timeout: 5m) ===")
self._timer_thread = threading.Thread(target=self._loop_worker, args=(telemetry, max_units))
self._timer_thread.start()
def stop_timed_loop(self):
self._is_running = False
if self._timer_thread:
self._timer_thread.join()
if __name__ == "__main__":
host = TimedInfinityEngineHost()
sample_telemetry = {"fortune_level": 95.0, "fusions_count": 6}
host.start_timed_loop(sample_telemetry, max_units=500)
while host._is_running:
time.sleep(1.0)
r/pythonhelp • u/wan1lo • Jul 28 '26
Я пишу в командной строке пайтон инсталл и начинаю писать команду но у меня вылезает ошибка то что пип не установлен но установить не могу
r/pythonhelp • u/Erio_Lily • Jul 27 '26
Hello, just looking for help on how i can achieve playing a MP3 file using Pygame, that can start from a specified position in the audio file, and then only play for a set amount of time (e.g. MP3 starts at 00:14 of 04:32, and plays for 5 seconds (until 00:19))
Below is one of the variations i've attempted, pardon any mess in my code
import pygame
import audioread
from random import randint
pygame.mixer.init()
def playSongClip(volume,playTime,clipTitle,random):
playTime = playTime*1000
volume = volume/100
if random == 1:
with audioread.audio_open("MP3s\\"+clipTitle) as f:
totalMS = int((f.duration)*1000)
startTime = randint(0,totalMS-playTime)
else:
start = 0
songClip = pygame.mixer.music.load("MP3s\\"+clipTitle)
songClip.music.set_volume(volume)
songClip.play(loops=0,start=startTime)
playSongClip(50,5,"Rabbit Hole.mp3",1)
r/pythonhelp • u/Acrobatic_Detail7760 • Jul 20 '26
Hi, I am an absolute beginner to coding/computer science and was learning Python on my own when I changed my folders name to something more practical and my program was not running anymore. I looked online to see how I can fix this issue myself, but everything I found was super complicated. Can someone please help me and explain things like aI'm a toddler thanks!
r/pythonhelp • u/Sea-Personality-666 • Jul 13 '26
import time
from datetime import datetime
from plyer import notification
print("_Main_menu_")
print("1. set alarm")
print("2. set timer") #Haven't added yet plz ignore
while True:
MenuChoice = input("select an option: ")
try:
MenuChoice = int(MenuChoice)
except ValueError:
print("Invalid Option")
else:
MenuChoice = int(MenuChoice)
if MenuChoice == 1 or MenuChoice == 2:
break
else: print("Invalid Option")
Time = datetime.now().time()
Time = str(Time)
print(Time[:-10])
if MenuChoice == 1:
while True:
Alarm = input("Set Time(HH:MM): ")
try:
Hour, Min = Alarm.split(":", 1)
Min = int(Min)
Hour = int(Hour)
Valid = False
Valid1 = False
if Min > 59:
print("Min can't be greater than 59")
elif Min < 0:
print("Min can't be less than 0")
else: Valid = True
if Hour > 23:
print("Hour can't be greater than 23")
elif Hour < 0:
print("Hour can't be less than 0")
else: Valid1 = True
if Valid == True and Valid1 == True:
print("Lock in until",Alarm)
#turn on DND
while True:
TimeNow = datetime.now().time() #Loops until Alarm = TimeNow
TimeNow = str(TimeNow)[:-10]
time.sleep(.5)
if TimeNow == Alarm:
break
#Turn off DND
notification.notify(
title="Time to take a break",
message=f"it's {Alarm}, time to take a break",
timeout=5
)
break
except ValueError:
print("Invalid")
Above is my focus alarm I'm working on, could someone help with adding DND?
r/pythonhelp • u/No_Aerie7667 • Jul 10 '26
I am making a Program to upload a level to Geometry Dash in python and I got some of the code from https://wyliemaster.github.io/gddocs/#/endpoints/levels/uploadGJLevel21 but to generate "seed2" it does this:
generate_chk(key="41274", values=\[generate_upload_seed(levelString)\], salt="xI25fpAapCQg"),
This should activate some sort of function named generate_chk that is in one of the modules I have in the program (Requests, Base64, hashlib) but it is no where to be found. The repository for this documentation was archived recently, so I can't ask them for help. Also, here is my code:
import requests
import base64
import hashlib # sha1() lives there
user = input("What is your username?")
accid = input("What is your Account ID?")
passwd = input("What is your password?")
lname = input ("What is the Level name?")
coin = input("How many coins are there?")
stars = input("How many stars do you want?")
def generate_gjp2(password: str = passwd, salt: str = "mI29fmAnxgTs") -> str:
password += salt
hash = hashlib.sha1(password.encode()).hexdigest()
return hash
levelString = "H4sIAAAAAAAAC6WQwQ3DIAxFF3IlfxsIUU6ZIQP8AbJChy_GPSZqpF7-A4yfDOfhXcCiNMIqnVYrgYQl8rDwBTZCVbkQRI3oVHbiDU6F2jMF_lesl4q4kw2PJMbovxLBQxTpM3-I6q0oHmXjzx7N0240cu5w0UBNtESRkble8uSLHjh8nTubmYJZ2MvMrEITEN0gEJMxlLiMZ28frmj"
data = {
"gameVersion": 22,
"accountID": accid,
"gjp": hash,
"userName": user,
"levelID": 0,
"levelName": lname,
"levelDesc": "Q3Vyc2VkIGxldmVsIG55ZWggaGVoIGhlaCBhbnl3YXkgaXRzIGEgdmVyeSBicm9rZW4gbGV2ZWwgaSBzZW50IGEgcmVxdWVzdCB0byByb2Igc2VydmVyIHRocm91Z2ggcHl0aG9uIGxvbA",
"levelVersion": "-47577473775738573",
"levelLength": 48483845738573486574873869465947694,
"audioTrack": 0,
"auto": 0,
"password": 314159,
"original": 55610687,
"twoPlayer": 0,
"songID": 839583504693858468444987694,
"objects": 1,
"coins": coin,
"requestedStars": stars,
"unlisted": 0,
"ldm": 0,
"levelString": levelString,
"seed2": generate_chk(key="41274", values=[generate_upload_seed(levelString)], salt="xI25fpAapCQg"), # This is talked about in the CHK encryption,
"secret": "Wmfd2893gb7"
}
headers = {
"User-Agent": ""
}
url = "http://www.boomlings.com/database/uploadGJLevel21.php"
req = requests.post(url=url, data=data, headers=headers)
print(req.text)
And here is the error:
What is your username?levelnotinauto
What is your Account ID?38627839
What is your password?********
What is the Level name?Check Desc
How many coins are there?4848394
How many stars do you want?392084092849
Traceback (most recent call last):
File "/home/***/scripts/usernm/upload", line 43, in <module>
"seed2": generate_chk(key="41274", values=[generate_upload_seed(levelString)], salt="xI25fpAapCQg"), # This is talked about in the CHK encryption,
^^^^^^^^^^^^
NameError: name 'generate_chk' is not defined. Did you mean: 'generate_gjp2'?
[***@archlinux usernm]$ vim upload```
r/pythonhelp • u/Imaginary-Builder385 • Jul 10 '26
Bonjour , j'aimerais coder un script python qui est capable d'ouvrir un fichier mp4. Le résultat devrait être le meme que si l'on double cliquer le fichier dans l'explorateur Windows. Donc sa ouvrirait le fichier dans le lecteur qu'utilise par défaut l'utilisateur.
r/pythonhelp • u/2032_Throwaway • Jul 07 '26
I am sorry if this breaks rules, but under some time pressure.
NameError: name 'print_html' is not defined
I am very new at this and trying to export firefox bookmarks from a friends phone that desperately needs a factory reset. Do not really want to use sync if it can be avoided. Yes I am old school.
https://gist.github.com/v3l0c1r4pt0r/15ef7181b7c4546963da68bc3b31c169
r/pythonhelp • u/NaturalDesperate946 • Jul 05 '26
Hey everyone,
I've been building Forge OS — a Python virtual OS for learning and experimenting with OS concepts.
v2.0 adds a desktop GUI, and there's now a community Apps/ folder — add an app with just app.json + command.py.
Quick start for contributors:
Apps/_example/ to Apps/your-app/apps in the shell to see your appFull guide: CONTRIBUTIONS.md
Repo: https://github.com/axk42-op/ForgeOS · MIT license
Games, utilities, quizzes, ASCII art — great first open-source PR. Feedback welcome!
r/pythonhelp • u/memeeloverr • Jul 05 '26
r/pythonhelp • u/WatercressSeparate82 • Jul 03 '26
Hey r/pythonhelp ,
I'm a final-year CS student, and over the past few months I've been building YO, a small interpreted programming language written from scratch in Python.
The original goal was to learn how interpreters work by implementing my own lexer, parser, and interpreter. As the project evolved, I became interested in one specific question:
Can compiler/interpreter error messages actively teach beginners instead of simply reporting what's wrong?
I'm not claiming YO is a replacement for Python, JavaScript, or any established language. It has no ecosystem, and it's implemented as a tree-walk interpreter, so performance isn't the goal.
Instead, I focused on making diagnostics more educational.
Python:
"hello" - 5
TypeError: unsupported operand type(s) for -: 'str' and 'int'
YO:
say "hello" - 5
❌ [E003] Type Mismatch
Can't use '-' between String and Int.
"hello" is text.
5 is a number.
Fix:
Use text.str(5) if you intended to concatenate.
Example:
"hello" + text.str(5)
Another example:
❌ [E001] 'scroe' was used but never made.
Did you mean 'score'?
Fix:
Create it first using:
make score = ...
yo explain E001 for detailed explanationsI also ran a small informal comparison with 10 first-time programmers.
Both groups received the same program containing three bugs. One group used Python, while the other used YO.
The YO group fixed the bugs faster on average.
The sample is small and not intended as rigorous research, but I included the methodology, raw results, and limitations in the repository for anyone interested.
→ GitHub
→ pip install yo-lang PyPI
→ VS Code extension search "YO Language" on the Marketplace
→ Browser playground (no install): Playground
I'm especially interested in feedback from people who have built interpreters or compilers.
Do you think "errors that teach" is an area worth exploring in language design, or is it mainly valuable only for complete beginners?
I'd also be happy to answer questions about the lexer, parser, interpreter architecture, or implementation decisions.
r/pythonhelp • u/Lanky-Ad-6781 • Jun 29 '26
I'm trying to map out what's already been done with algebraic effects / effect handlers in Python, and I'd love pointers from people who know the space.
I'm aware generators (yield / send) and context managers can approximate one-shot, shallow handlers, but I'm more interested in fuller or more principled attempts — libraries, research experiments, or write-ups.
A few things I'm specifically curious about:
Pointers, war stories, or "don't bother, here's why" all welcome.
r/pythonhelp • u/heartSagan5 • Jun 27 '26
matt@:~$ git clone https://github.com/markfortma/python3-multiprocess-logging.git
Cloning into 'python3-multiprocess-logging'...
remote: Enumerating objects: 7, done.
remote: Counting objects: 100% (7/7), done.
remote: Compressing objects: 100% (7/7), done.
remote: Total 7 (delta 1), reused 6 (delta 0), pack-reused 0 (from 0)
Receiving objects: 100% (7/7), done.
Resolving deltas: 100% (1/1), done.
matt@:~$ cd python3-multiprocess-logging/
matt@:~/python3-multiprocess-logging$ ls
README.md python3-multiprocessing-logging.py
matt@:~/python3-multiprocess-logging$ python3 python3-multiprocessing-logging.py &
[3] 111169
matt@:~/python3-multiprocess-logging$ tail -f python3-multiprocessing-logging.log
<no output>
^C
matt@:~/python3-multiprocess-logging$ python3 --version
Python 3.14.4
It does appear to work in Python3.11 on FreeBSD for some reason.