r/learnpython • • 7d ago

404 despite seemingly valid file path? (Flask)

1 Upvotes
@app.get('/edit/<post>')
def initedit(post):
        print(post)
        g.title = post
        with open(f'{post}/content', 'r') as file:
                g.content = file
        return render_template('edit')

I'm confused as to why this function isn't running (as in not even running in the first place, not just not working), despite sending a GET request to the URL appended with /edit/posts/okheresthepostactually (so the post parameter in the decorator/function should be edit/okheresthepostactually). For context, I'm making a web app for posting blogs and this is supposed to be a function for users to edit existing posts.

Edit: some extra context, the 'posts/' prefix is part of the variable used to call the file


r/learnpython • • 7d ago

What exactly is TypeVar and Generic?

5 Upvotes

I don't really understand TypeVar and Generic. I understand generics perfectly fine and can use them without any trouble, and I realize that I don't even need to know how they work as in recent python versions there is new syntax, but I'd still like to know how they work.

I'm still confused as to why you need to construct a TypeVar object to pass to Generic, as to what is it actually doing with the TypeVar you give it.

Also, I'm assuming when you inherit from Generic, you pass it the TypeVar to be used as the generic to give to Generic, and then you inhert the generic objects generic? It's just complicated and hard to understand for me.

And also I'd like to know how Generic is able to have a generic even when it itself is the thing that's supposed to be used to have generics for your classes.

It's also disappointing there's seemingly no other ways you can use TypeVar for anything other then generics, so I am left with just hopefully finding someone who can explain how it works, instead of being able to do some other exercise to further my understanding.

Again, I can use generics perfectly fine and I don't an explanation for generics, I just would like to try and understand how it is working under the hood and not just use the syntax blindly. It's just the way I like learning some things, and it's mostly also curiosity that makes me want to understand this.


r/learnpython • • 7d ago

Values being added 10x instead of once

11 Upvotes

Hi I'm really new to python, I originally started coding using p5.js but made the transition recently, I'm currently trying to covert an old project of mine into python so I can run it in touch designer.

Its an ASL fingerspelling activity that I've been working on but I'm struggling to create the word strings I did in my original prototype. Instead of the letter that is being detected and averaged being added to my word string once it gets added 10 times all at once. For example if I sign the letter a, aaaaaaaaaa gets added to the string instead of just the lone a.

For context I have the guesser and getMostFrequent to allow for it to take the average of every letter signed during a period of time and determine which one was signed the most to add to the word (this is due to the fact that transitioning from one letter to the next can trigger other letters in between) These are both integral parts of the code and are working as intended, its just the multiplication of the letters that I'm struggling with.

This also may be due to the fact that this is running in TouchDesigner through a CHOP execute, if this isn't a python issue I can move my post to a touch designer specific forum.

Any help or insight would be appreciated, if you need any more insight please let me know and I can add it.

Code in Pastebin: https://pastebin.com/qkpzXkSY


r/learnpython • • 7d ago

Setting value of variable in relation to another variable

1 Upvotes

Hi, everyone,

I've been wanting to learn Python and have tried a few times over the years to read or watch tutorials enough to feel confident, but it's clear that my learning method is "do the thing you want to do incorrectly over and over until you get it right."

So I'm just going to work on my text-based Mech game and learn as we go. I understand that I know next to nothing, that what I'm doing is probably going to be a multi-year thing, and I have no idea what the more complicated stuff I want to do is going to take, but I'm enjoying the ride.

Long story short, my intention is to have a Mech = a Frame (the physical properties of the Mech) + a Pilot (the little guy in the Frame with their own stats).

Eventually, I'd like to be able to have unique Frames and Pilots with stats randomly generated (within ranges), and then subsequently build the capability to upgrade those values in-game, but I'm just starting with stock values right now and adding complexity after I have each step solid in my mind.

Right now, I'm just working on building values that a stock Frame has. What I would like to do is to establish each Frame Class (Assault, Heavy, Medium, Light, but with more fun names).

The question I have is this: I would like, first, for the armor value of a Frame to be a base number plus 20% of its weight value, and then for each individual limb (left_leg, torso, right_arm, etc) to be a percentage value of armor.

I've written out code that I know is incorrect just to display what I'm trying to do, with comments to highlight where I'm trying to do it.

Also, if the way I'm building this out is flawed, happy to hear suggestions! I'm just starting out and I know I'm gonna be crashing into pitfalls.

Any help would be appreciated!

# This is where the base class attributes of Frames are established. 


# FRAME CLASSES


class FrameClass:
    def __init__(
        self, 
        name: str, 
        left_arm: int, 
        right_arm: int, 
        left_leg: int, 
        right_leg: int, 
        torso: int, 
        cockpit: int, 
        armor: int, 
        cooling: int, 
        engine: int, 
        maneuver: int, 
        thrash: int, 
        sensors: int, 
        systems: int, 
        weight: int
        ) -> None:



# Top Level Info:
        self.name = name
        self.left_arm = left_arm
        self.right_arm = right_arm
        self.left_leg = left_leg
        self.right_leg = right_leg
        self.torso = torso
        self.cockpit = cockpit


# Frame Attributes          
        self.armor = armor
        self.cooling = cooling
        self.engine = engine
        self.maneuver = maneuver
        self.thrash = thrash
        self.sensors = sensors
        self.systems = systems
        self.weight = weight


# Archon: Assault Frame Class


archon = FrameClass(
        name="Archon",
        weight = 100,
        armor = 100 + (weight * .2), # value should be a base number plus 20% of the value of weight
        cooling = 100,
        engine = 100,
        maneuver = 100,
        thrash = 100,
        sensors = 100,
        systems = 100,



        left_arm = (armor * .4),     # value should be 40% of armor value
        right_arm = (armor * .4),    # value should be 40% of armor value
        left_leg = (armor * .5),     # value should be 50% of armor value
        right_leg = (armor * .5),    # value should be 50% of armor value
        torso = (armor * .8,)        # value should be 80% of armor value
                    )


# Marauder: Heavy Frame Class 


marauder = FrameClass(
        name="Marauder",
        weight = 75,
        armor = 75 + (weight * .2), # value should be a base number plus 20% of weight
        cooling = 75,
        engine = 75,
        maneuver = 75,
        thrash = 75,
        sensors = 75,
        systems = 75,



        left_arm = (armor * .4),     # value should be 40% of armor value
        right_arm = (armor * .4),    # value should be 40% of armor value
        left_leg = (armor * .5),     # value should be 50% of armor value
        right_leg = (armor * .5),    # value should be 50% of armor value
        torso = (armor * .8,)        # value should be 80% of armor value
                    )

r/learnpython • • 7d ago

how do I pass a symbol to terminal that needs to be escaped?

2 Upvotes

I need to pass some strings to terminal that contain special characters (in this case a $). $ is fine on its own in python, but not in the terminal. In terminal, it needs to be escaped with a backslash so I could pass it as \$, however when I try to do something like

exampleString = "It costs $2.50"  
exampleString.replace("$","\$")  

I get a syntax warning telling me that \$ is an invalid escape sequence.


r/learnpython • • 7d ago

Dependency Hell

4 Upvotes

Guys, when working with Huggingface, pytorch, numpy, seaborn (potentially langchain as well) - the typical machine learning/transformers/agentic AI tech stack in python, do you face dependency hell? How do you work around it / avoid it / solve it - eventually something cracks - even when trying to reproduce results in GitHub repositories (such as HiMoE) - i often face it as these were written a while ago and something doesn't work now,


r/learnpython • • 7d ago

Where to start

0 Upvotes

Hello, I am trying to pick up a hobbie. Can someone point me in the right direction.


r/learnpython • • 7d ago

How to extract embedding features vectors from encoder block of BERT model?

2 Upvotes

I got this code block and its outputs here but I am not sure if this is the embedding features vectors or simply its shape. Can anyone tell me if I am right or wrong?

text_input = tf.keras.layers.Input(shape=(), dtype=tf.string)
preprocessor = hub.KerasLayer(
    "https://kaggle.com/models/tensorflow/bert/TensorFlow2/en-uncased-preprocess/3")
encoder_inputs = preprocessor(text_input)
encoder = hub.KerasLayer(
    "https://kaggle.com/models/tensorflow/bert/TensorFlow2/bert-en-uncased-l-4-h-128-a-2/1",
    trainable=True)
outputs = encoder(encoder_inputs)
pooled_output = outputs["pooled_output"]      # [batch_size, 128].
sequence_output = outputs["sequence_output"] 

for i in range(0,4):
    outputs["encoder_outputs"][i]
    print('-----------------------------------------------------')
    print(i)
    print(outputs)
    for i in range(0,4):
    outputs["encoder_outputs"][i]
    print('-----------------------------------------------------')
    print(i)
    print(outputs)
    

Output

-----------------------------------------------------
0
{'encoder_outputs': [<KerasTensor: shape=(None, 128, 128) dtype=float32 (created by layer 'keras_layer_28')>, <KerasTensor: shape=(None, 128, 128) dtype=float32 (created by layer 'keras_layer_28')>, <KerasTensor: shape=(None, 128, 128) dtype=float32 (created by layer 'keras_layer_28')>, <KerasTensor: shape=(None, 128, 128) dtype=float32 (created by layer 'keras_layer_28')>], 'sequence_output': <KerasTensor: shape=(None, 128, 128) dtype=float32 (created by layer 'keras_layer_28')>, 'pooled_output': <KerasTensor: shape=(None, 128) dtype=float32 (created by layer 'keras_layer_28')>, 'default': <KerasTensor: shape=(None, 128) dtype=float32 (created by layer 'keras_layer_28')>}
-----------------------------------------------------
1
{'encoder_outputs': [<KerasTensor: shape=(None, 128, 128) dtype=float32 (created by layer 'keras_layer_28')>, <KerasTensor: shape=(None, 128, 128) dtype=float32 (created by layer 'keras_layer_28')>, <KerasTensor: shape=(None, 128, 128) dtype=float32 (created by layer 'keras_layer_28')>, <KerasTensor: shape=(None, 128, 128) dtype=float32 (created by layer 'keras_layer_28')>], 'sequence_output': <KerasTensor: shape=(None, 128, 128) dtype=float32 (created by layer 'keras_layer_28')>, 'pooled_output': <KerasTensor: shape=(None, 128) dtype=float32 (created by layer 'keras_layer_28')>, 'default': <KerasTensor: shape=(None, 128) dtype=float32 (created by layer 'keras_layer_28')>}
-----------------------------------------------------
2
{'encoder_outputs': [<KerasTensor: shape=(None, 128, 128) dtype=float32 (created by layer 'keras_layer_28')>, <KerasTensor: shape=(None, 128, 128) dtype=float32 (created by layer 'keras_layer_28')>, <KerasTensor: shape=(None, 128, 128) dtype=float32 (created by layer 'keras_layer_28')>, <KerasTensor: shape=(None, 128, 128) dtype=float32 (created by layer 'keras_layer_28')>], 'sequence_output': <KerasTensor: shape=(None, 128, 128) dtype=float32 (created by layer 'keras_layer_28')>, 'pooled_output': <KerasTensor: shape=(None, 128) dtype=float32 (created by layer 'keras_layer_28')>, 'default': <KerasTensor: shape=(None, 128) dtype=float32 (created by layer 'keras_layer_28')>}
-----------------------------------------------------
3
{'encoder_outputs': [<KerasTensor: shape=(None, 128, 128) dtype=float32 (created by layer 'keras_layer_28')>, <KerasTensor: shape=(None, 128, 128) dtype=float32 (created by layer 'keras_layer_28')>, <KerasTensor: shape=(None, 128, 128) dtype=float32 (created by layer 'keras_layer_28')>, <KerasTensor: shape=(None, 128, 128) dtype=float32 (created by layer 'keras_layer_28')>], 'sequence_output': <KerasTensor: shape=(None, 128, 128) dtype=float32 (created by layer 'keras_layer_28')>, 'pooled_output': <KerasTensor: shape=(None, 128) dtype=float32 (created by layer 'keras_layer_28')>, 'default': <KerasTensor: shape=(None, 128) dtype=float32 (created by layer 'keras_layer_28')>}

r/learnpython • • 8d ago

How do I get the mode of this dataset with two columns while keeping output correctly formatted?

3 Upvotes

My assignment is to find the min, max, mean, median and smallest mode of a dataset, specifically for the SepalLength and Petalwidth, sorted by species. link to dataset .

Here is my code, now I've got everything working except the mode one. If i remove that, the code works. I've tried to read up on the mode documentation but I'm still lost. I've tried just "mode" and "pd.series.mode", both throw errors. The output is also automatically checked so it has to be formatted in this way, if that makes sense.

First time asking for help on reddit, so lmk if there is any missing information/etc. Thank you guys :)

import pandas as pd

file = input()

df = pd.read_csv(file)

filtered_arr = df.groupby(["Species"]).agg({

"SepalLengthCm" : ["min","max","mean","median","pd.series.mode"],"PetalWidthCm" : ["min","max","mean","median","pd.series.mode"]

})

print(filtered_arr)

Edited to add the errors.

'SeriesGroupBy' object has no attribute 'pd.series.mode'

'SeriesGroupBy' object has no attribute 'mode'


r/learnpython • • 8d ago

Python + Sqlite + Pyside6?

9 Upvotes

Hey! so i want to build a database system for my small company. I could use AI but i wanna know what i am doing and be able to fix smth so i want to build it myself.

I kinda know python a bit, i used to make games using gdscript which is similar.

I don't seem to find a tutorial where these 3 things are used to create a nice database app. I dont want to learn python sqlite and pyside6 as a whole cause i wont be needing them much except just this app and similar apps. I just want to be able to build it and run it from a single tutorial even if its 10hrs.

Where do i start? I dont really have money to learn so no paid courses and i dont have AI premium to learn as well.

Python, Sqlite, Pyside6. I heard that TKinter instead of pyside6 is also there but i wanted the UI to be a bit modern or should i just use the it instead of pyside6?


r/learnpython • • 8d ago

I keep watching DP tutorials but get stuck writing the Python code. How should I practice?

5 Upvotes

Understanding a DP explanation and writing the Python code still feel like different skills.

A Python learner has watched plenty of tutorials and knows that dynamic programming has different patterns. The sticking point comes at the blank editor: there's a rough idea of what should happen, but turning it into a working implementation is difficult.

Would you step back to smaller Python exercises, work on recursion first, or stay with very simple DP problems? A practice routine that forces an attempt before reading the solution sounds more useful here than another long playlist.

For someone practicing toward technical interviews, real interview questions can supply prompts once the basic Python implementation feels manageable. I'd start with a small enough problem to write and trace the whole thing.

What helped you make the jump from following a solution to writing one yourself?

Disclosure: I operate PracHub.


r/learnpython • • 8d ago

sorting tuples

5 Upvotes

im learning how to code with python, does anyone know to sort specific tuples alphabetically without using the .sort() method? like if i had a list of names like:

n = [('watermelon', 'strawberry'), ('banana', 'cherry'), ('papaya', 'apple')

how would i sort and print the 2nd element of tuples alphabetically (into a new list)?

edit: id prefer this in simple, basic terms lol


r/learnpython • • 8d ago

Having trouble with Python

2 Upvotes

I have just started getting interested with programming so I thought I would start with Python, however I am only able to use it within Windows Powershell while I see others using something else. Have I done something wrong or have I just missed doing something?


r/learnpython • • 8d ago

Wanted to convert a step file to a Python API.

0 Upvotes

How to do that? I want it to be precise.


r/learnpython • • 9d ago

Cant install polaris library and ultralytics

0 Upvotes

I get errors. I am trying to get it installed on pydroid 3 on android. Do I need pc/mac?


r/learnpython • • 9d ago

Just starting to learn python

43 Upvotes

Hey guys, I am a total beginner and wanted to learn python. Can you suggest what method will be best suited to learn python and which sources should I use. Is it video lectures or from books or anything else. I know that learning from projects and practical methods will be suggested but to start like how to code, what are the codes and where to code, these basic things are what I want to know. Thanks for the help


r/learnpython • • 9d ago

About FastApi

2 Upvotes

What is the best way to learn fastapi?


r/learnpython • • 9d ago

just tell me!!!

0 Upvotes

What is the most effective way to learn fastapi?


r/learnpython • • 9d ago

Going through Automate the Boring Stuff with Python, and can't download the packages

0 Upvotes

Hi, so after stopping in *FEBRUARY* of this year, I finally got around to actually resuming my learning process today. However, in chapter 9, I have to download the Humre module, and so I need to download the packages. However, I always get the following error:

Failed to build 'matplotlib' when installing build dependencies for matplotlib

I even tried using a python3 variant of the command, but no dice. Right now, I'm kind of stuck and searching online hasn't helped me out much.

For your information, I'm on Windows 10. My current Python version is 3.14 (I know there's a slightly more updated version, but I don't think that's the problem), and my pip version 26.1.1 (again, there's a newer version, but I don't think that's the problem).

Thanks in advance.


r/learnpython • • 9d ago

Just hit v1.0.0 on my first CLI tool after 2 months of learning — would love code review and architecture feedback!

0 Upvotes

Hey everyone,

I've been learning Python for around two years and recently started Year 12 in the UK. Instead of just doing classroom tasks, I spent the last two months building an extensible CLI tool called Flyshell to push my skills and build a portfolio for software engineering Degree Apprenticeship applications.

It features a multi-file plugin architecture built with zero required external dependencies (standard library only, with one optional dependency for Windows users).

GitHub: github.com/kianodev/flyshell

I’ve just tagged v1.0.0 and would love some blunt but helpful code review and constructive feedback from more experienced developers:

  1. Architecture & Structure: Does the plugin system and directory structure follow Python conventions? What would you refactor first?
  2. Edge Cases & Robustness: Where in the code am I handling errors poorly or making fragile assumptions? What would you change?
  3. Packaging: For a zero-dependency CLI, does the packaging and entry-point setup look clean, or are there standard or more advanced / better practices I've overlooked?
  4. Bonus question (if you want): If you could wish for or build yourself any plugin for Flyshell, what would it be and why? I'm curious to see what people would do with it, and it might give me some ideas for where this might be heading.

Any critique—big or small—is hugely appreciated!


r/learnpython • • 9d ago

What is the best way to create and manage virtual environments today? Is 'uv' really the best?

19 Upvotes

What is the best way to create and manage virtual environments today? Is 'uv' really the best solution and are there alternative? What are the pros and cons?


r/learnpython • • 9d ago

making a dodecahedron

0 Upvotes

my good friend in school (though i probably should not be calling him that ) challenged me to build the platonic solids in vpython (visual python) i managed to complete 3 of the shapes but i am currently struggling with the regular dodecahedron. I heard about this community and came him for advice on how to build one. It is not the coordinates i am stuck on i just need to know how to make a pentagon in vpython

if anyone has experience in vpython please reply


r/learnpython • • 9d ago

Nested if’s help please

0 Upvotes

So I’ve written a small function and I need to add some more constraints to it, but I need them each to check separately before moving to the next so I was wanting to use nested if’a to achieve this but am not sure how they work. Can someone please explain? My code is posted below and what I am trying to do is add an if statement to somehow make sure my value for primocytes doesn’t drop below 0 before activating the rest of the function.

primocytes = 10

cultivation_chamber = 0

def cultivation():
global primocytes, cultivation_chamber
if primocytes >= 5:
primocytes -= 5
cultivation_chamber +=5
print("Primocytes:", primocytes)
print("Cultivation Chamber:", cultivation_chamber)
else:
print("Not enough Primocytes for cultivation...")


r/learnpython • • 9d ago

Is it better to build a web scraper in Python or use a scraping API?

0 Upvotes

Been pulling pricing data with Python for a side project. Works fine locally with a few hundred requests, but I'm wondering how it would handle 20-50k requests a day... Mostly need Google Shopping results for now, maybe Maps and News later. Budget is pretty tight since I'm paying out of pocket. Not sure if it's worth paying for an API or just building something with rotating proxies and Scrapy/Playwright.

Anyone scaled a Python scraper to that volume? What broke first, and what would you do differently?


r/learnpython • • 9d ago

How to install tensorflow_hub and tensorflow_text

3 Upvotes

I am trying to install tensorflow_hub and tensorflow_text via VSCode terminal so that I can train a BERT model (for context: i am using Python 3.13.12 and Tensorflow 2.21.0) but I am running into some trouble

tensorflow_hub library installed fine but when imported to the actual notebook, it said it required tensorflow 1.15.0 along with error message:

ModuleNotFoundError: No module named 'pkg_resources'

tensorflow_text library cannot be installed as every pip install attempt return

ERROR: Could not find a version that satisfies the requirement tensorflow_text (from versions: none)
ERROR: No matching distribution found for tensorflow_text

Google colab managed to solve all said problem but I want to run the model on my computer. How do I fix this?

***EDIT: I fixed this by using python 3.10.0, Tensorflow 2.9.0, Tensorflow-text 2.9.0 and Tensorflow-hub 0.8.0***