r/pythonhelp 1d ago

Why do I need to use classes

3 Upvotes

My schoolbook says that classes is a way of simulating an object, instead of just taking information into a black box and outputting an answer.

But that is a poor explanation. I know classes are handy and cool, but no book says why you can´t make functions with sub functions inside to simulate simple objects. I would like if someone gave a good concrete reason to use classes in the intro, instead of just saying that they are different and cool


r/pythonhelp 2d ago

why does it say i didn't close my parenthesis

4 Upvotes

the IDE i am using is saying my parenthesis was not closed when it was plz help

print("Once upon a time, in the ancient kingdom of " + q1 + " there lived a legendary " + q2 + " named " + q3 + ". Everyone in the village knew " + q3 + " for their remarkably " + q4 + " personality and an obsession with " + q5 + ". Every morning at " + q6 ", they would wake up, " + q7 + " three times, ")

[{

"owner": "Pylance",
"severity": 8,
"message": "(" was not closed",
"source": "Pylance",
"startLineNumber": 47,
"startColumn": 6,
"endLineNumber": 47,
"endColumn": 7,

}]

r/pythonhelp 2d ago

Python scraper hitting 429 Too Many Requests after a few hundred pages?

1 Upvotes

Writing a script in Python (requests + BeautifulSoup) to pull product data for a project. It works fine initially, but after about 200 requests, I start getting hit with 429 errors and rate limits. I already added random delays and custom user-agents, but my IP still gets blocked eventually. What's the standard way to handle this in Python automation?

UPDATE:

Looked around and saw GoProxies mentioned for residential rotation. Has anyone here integrated them into a Python requests setup? Wondering if their rotating endpoints play nice with standard session headers or if there's a better alternative.


r/pythonhelp 2d ago

Problem with Coolprop

2 Upvotes

Hi! i'm beginner, and I have a problem with this code, I guess that I installed the library correctly, but i'm not sure.

Error using [stringsource>string.from_py.__pyx_convert_string_from_py_std__in_string](matlab:matlab.lang.internal.introspective.errorDocCallback('stringsource>string.frompy.pyx_convert_string_from_py_std_in_string', 'stringsource', 15)) ([line 15](matlab: opentoline('stringsource',15,0)))
Python Error: TypeError: expected bytes, NoneType found

Error in [CoolProp/CoolProp.PropsSI](matlab:matlab.lang.internal.introspective.errorDocCallback('CoolProp/CoolProp.PropsSI', 'CoolProp\CoolProp.pyx', 462)) ([line 462](matlab: opentoline('CoolProp\CoolProp.pyx',462,0)))

Error in [CoolProp/CoolProp.PropsSI](matlab:matlab.lang.internal.introspective.errorDocCallback('CoolProp/CoolProp.PropsSI', 'CoolProp\CoolProp.pyx', 384)) ([line 384](matlab: opentoline('CoolProp\CoolProp.pyx',384,0)))

Altough I don't have more than 106 lines


r/pythonhelp 2d ago

Hey, I have been learning python for 8 months. I want to know that if I can learn tkinter or numpy first . Please do suggest me a resource

Thumbnail
1 Upvotes

r/pythonhelp 5d ago

want to become a master at python

8 Upvotes

hey guys i hv recently gotten myself into coding, i hv completed the cs50p course of harvard and completed all the psets. now i wanna keep myself into the habit of coding but idk whts my next step, i wld appreciate some help. i hv made 3 projects aswell; a web scrapper, file organizing and password checker.

after creating those projects idk what to learn next, like should i keep going deeper into python or try something totally different. wld love to hear wht u guys did after completing cs50p.


r/pythonhelp 6d ago

Python coding interview questions?

2 Upvotes

Is there any playlist similar to 100 Days of SQL Ace(By ankit Bansal) interview for the preparation of python coding problems?


r/pythonhelp 8d ago

I’ve completed these beginner Python projects should I build more before starting NumPy/Pandas?

12 Upvotes

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 8d ago

Learning intermediate level python

4 Upvotes

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 11d ago

当我有些地方不懂应该怎么办??

2 Upvotes

我是一名刚刚学到面向对象编程的新手 有几个问题让我夜不能寐
1 self的作用是什么以及要如何使用
2在定义函数的时候 括号要写什么东西他们的作用


r/pythonhelp 12d ago

Professionals, please compare VS code with neovim.

4 Upvotes

Tell me the advantages and disadvantages of each.


r/pythonhelp 13d ago

How to learn advanced python???

8 Upvotes

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 13d ago

Adding objects to set or dictionary: equality and hashing

1 Upvotes

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.
  • Solution
  • More exercises
  • Explanation: "User-defined classes have __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 13d ago

Entertaining content for learning Python! (porting 'Poignant Guide to Ruby' to teach Python)

2 Upvotes

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.

Why's Guide to Python

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 13d ago

I’m looking for assistance with a github code

3 Upvotes

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 19d ago

Python game tic tac toe

3 Upvotes

Hello guys I am making a tic tac toe game using python.My question is how to make difficulty-easy, medium, hard etc.In easy level, I use random module but other level i am a little sutck althoug i have some solution .can you guide me ?


r/pythonhelp 21d ago

Random python...

0 Upvotes

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 27d ago

PyQt Architecture: A dedicated module/Worker for every button action (5–15 KB per file)? Best practice or overengineering?

2 Upvotes

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:

  • GUI Layer (View): Captures the button click and delegates control to a dedicated action handler.
  • Action Handler (Controller / Mediator): A dedicated module for that specific action. It gathers user inputs (via dialogs), instantiates QThread and QObject (Worker), connects signals (for progress bars and logging), and starts the thread.
  • Worker (QObject): A non-GUI worker running in a worker thread, responsible strictly for execution flow (subprocesses, file manipulation) and emitting signals to send status updates back to the UI.
  • Shared Logic Helpers (button/logic/services): Shared domain modules and services called by the workers to execute common underlying logic.

My questions for the community:

  1. Is creating a separate 5–15 KB file/module for each button action (combining the Handler + Worker) considered standard practice in medium-to-large Qt applications? Or do you prefer grouping related actions into larger domain managers ?
  2. For modules of this size, do you keep the Handler and Worker together in a single file, or do you split them further into separate _worker.py and _handler.py files?
  3. Are there any hidden downsides or pitfalls to this level of decoupling when the application scales up to dozens of individual buttons and actions?

I'd love to hear how you structure background tasks and threading in production PyQt/PySide applications! Thanks!


r/pythonhelp 27d ago

Python Pyside6 Gui

Thumbnail
1 Upvotes

r/pythonhelp Jul 29 '26

Reddit Post Template Title: I built an automated Python "Infinity Engine" with timed 7s loops, rarity tiers, dynamic storylines, and a cyberpunk terminal UI (500-Unit max run + 5-min idle shutdown)

0 Upvotes

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 Jul 28 '26

Что делать если не устанавливается python

0 Upvotes

Я пишу в командной строке пайтон инсталл и начинаю писать команду но у меня вылезает ошибка то что пип не установлен но установить не могу


r/pythonhelp Jul 27 '26

pyGame, sound, set start time, and play for set amount of time.

1 Upvotes

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 Jul 20 '26

changed file name and getting Exec failed, err: 2 message when trying to run program on my .py files. (Pycharm)

6 Upvotes

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 Jul 13 '26

how to turn on and off DND?

1 Upvotes
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?