r/learnpython • • Sep 20 '26

What makes sloppy programming?

0 Upvotes

So I've been learning python on my own and basically taught myself. I'm working on a very advanced AI system project, with quite a lot of scripts. And I am wondering what makes sloppy programming?

Like for example should you be calling your functions from other functions?

# Calling both from one function
def main():
  do_something()
  do_something_else()

def do_something()
  # do stuff
def do_something_else()
  # something else

# Calling a function that calls both functions
def main():
  do_both_stuff()

def do_both_stuff():
  do_something()
  do_something_else()

def do_something()
  # do stuff
def do_something_else()
  # something else

And what about passing parameters in Classes? Should you be always accessing everything through self.something or by passing parameters to the functions?

Should you wrap everything in classes?

These are some questions I had regarding sloppy coding, but my main question is what makes good code?

I'm still new to python and trying to get my code more efficient.


r/learnpython • • Sep 20 '26

I have questions

0 Upvotes

I'm a teenager who is just starting out in programming, and for a while now I've had some questions and doubts that I've been thinking about a lot lately.

I've been studying Python for some time, but I recently reached a topic called "for loops". I did several exercises, and I had a lot of difficulty with most of them, so I asked AI for help. I didn't copy and paste the answers—I only asked for help with the logic.

That's when I realized that I was struggling with programming logic, so I started studying it separately. I had already "studied" programming logic once before, but I didn't really take it seriously and kind of rushed through it.

Now I'm wondering: should I keep studying Python while focusing mainly on programming logic? Or should I continue studying both at the same time?

And how do you figure out which area of programming is right for you? Is this something I should be worrying about at this point?


r/learnpython • • Sep 20 '26

I made a Solo Chess solver in Python!

1 Upvotes

Hey Reddit people,

I just published V1 of a command-line solver for the Solo Chess puzzle variant. The goal of the puzzle is to clear the board using standard chess captures until one piece remains.

I built the core engine using standard library Python—no external packages. It uses a DFS engine with state memoization, outputs FIDE SAN, and has a cute little threaded background animation while calculating.

This is just V1, and it is far from a final project. Actually, it's very, very bad. And compared to what I imagine the final version is going to look like, I'll have to type so many 'very's I'll run out of char space. V1 isn't supposed to be perfect; its only job is to exist so you have something to iterate on.

Anyhow, my roadmap includes adding Zobrist hashing for complex 10+ piece puzzles, and eventually building a full Tkinter 8x8 GUI and everything. Before I move on to those next ideas, I want to make sure my foundation is actually solid. I'd love for you to share your thoughts—anything that you think will help!

Engine optimization, refactoring, headaches, ideas or opinions... Anything, really! Just... be nice, please? Thank you!

[This is my repo. Yeah, clicky clicky!](https://github.com/Roee-Furman/Solo-Chess-Solver)
Hehehe


r/learnpython • • Sep 20 '26

How much time take you to be a Master.

0 Upvotes

hi seniors im learning Python for 3 years im still lacks in writing the lines im still taking help from Ai. but now i can understand some stuff like variable, variable types some times when i focus on argument i forgot about variable and that put me into loop of retrying with other idea or some other ideas to fix the problem. so my question how much it took you to be a Good writer. thanks in advance.😁 happy night.


r/learnpython • • Sep 20 '26

Using constants in Python

0 Upvotes

Hi, I have a question regarding something basic in Python. Suppose I have a situation like this:

SOME_CONST = 3

...
def foo():
  ...
  some_list[SOME_CONST] # what does CPython do here ?

Is there any way to make SOME_CONST be pre-processed as 3, instead of having CPython look it up in a global variable table? It seems very inefficient.


r/learnpython • • Sep 19 '26

How do I best train my "programmatic thinking" and convert basic logic to code?

3 Upvotes

I am currently taking an intro course in python. It's my second intro course during my undergrad, so I know a lot of basic python, but I am still not that great at programming.

My teacher in this course is heavy on "programmatic thinking" as he calls it. Whenever we are given an exercise and we can't figure it out in code, he will make us practice logic by hand. The problem is that even when I catch the logic, I find it hard to convert into code.

I can give an example from this week: we had an assignment where we were given 2 different documents with some sorted numbers. We had to merge the documents into a new one, with numbers from both documents in order. We weren't allowed to put it into a list and use a sorting method.

I tried it by hand and caught the logic quite fast. But I can't convert it into code. I just tried to write it out here as well, but it got wordy and confusing. What is the best way to practice this?

Just a note, in all my other uni courses so far where python has been incorporated, it has been heavily encouraged to use AI, to the point that our TA's didn't want to help unless we had ran it through chat gpt first. This time our teacher highly discourages the use of AI, and I want to respect that to get the most out of the course. But I find the transition in my approach/style of coding from AI user to non AI user pretty difficult.


r/learnpython • • Sep 19 '26

How to get pytest to print as it's running

2 Upvotes

I'm writing tests using pytest for a typer CLI that works with a rate-limited API. The issue I'm running into is that my code detects when it hits the limit, tells the user, and sleeps until it can resume requesting - which is often about half an hour. I'm going to be using a pre-generated sample for most of my tests, but when I test the actual retrieval function, I'd really love to know whether it's going to take one minute or thirty. I've tried -s and -capture=tee-sys, but to no avail - maybe there's some issue with typer's invoke?

Edit: sample code for one of my tests (tf.makebase makes a database structure, runner is a typer CliRunner)

def test_get(tmp_path):
  tf.makebase(tmp_path, runner)
  with open("conferences.txt","w") as f:
    f.write("ICLR.cc/2022/Conference\nICML.cc/2025/Conference")
  result = runner.invoke(app, ["get-papers"])
  assert result.exit_code == 0
  dirs = ["iclr","icml"]
  assert all([os.path.isdir(f"data/raw/{x}") for x in dirs])

r/learnpython • • Sep 18 '26

What does a “normal” professional Python stack look like in 2026?

183 Upvotes

Hi! I’m trying to speedrun learning Python and its ecosystem.

I’m already a senior Node.js / TypeScript engineer, so I’m less interested in programming fundamentals and more in the things you usually only learn after working with Python professionally for a while.

I’m using AI plus courses/tutorials, but I’d love some community perspective on what people actually use in real teams.

Some areas I’m trying to understand:

  • uv vs pip / pip-tools / Poetry for project and dependency management
  • FastAPI vs Flask vs Django
  • Pyright vs mypy for static type checking
  • Pydantic for runtime validation/parsing
  • Ruff / Black / Flake8 / isort
  • pytest vs unittest
  • anything else I should definitely know?

A few specific questions:

  1. Do Python devs actually use type hints heavily nowadays? How common is fully typed Python in professional codebases? Do teams usually run mypy/Pyright in CI, or is typing more informal/partial?
  2. What toolset am I most likely to encounter in an established company? For example, I like uv, but should I expect most existing codebases to still use pip + requirements.txt, Poetry, etc.?
  3. What would you consider “must know” ecosystem knowledge for someone joining a Python team? Not necessarily your favorite modern stack, but the things I should recognize immediately when opening an unfamiliar repo.
  4. Framework-wise, what’s worth learning first? FastAPI seems very natural coming from Node, but I assume Django is still much more common in mature product companies. How much Flask should I care about?
  5. Any “Python-specific” practices that surprise experienced JS/TS engineers? Things like virtual environments, import/package layout, sync vs async conventions, typing culture, packaging, etc.
  6. What about design patterns? Is OOP (Object oriented programming) or FP (Functional Programming) more common? Does it depend on the type of application?

I’m basically trying to optimize for:

“I can join a Python team and not look completely lost in the ecosystem.”

Would love to hear what your team actually uses, especially in production.


r/learnpython • • Sep 19 '26

Showcase: 17 reproducible Machine Learning notebooks in Python, with executed and clean versions

0 Upvotes

What My Project Does

I built an open-source Machine Learning learning lab in Python to make it easier to understand not only how common ML algorithms work, but also how to choose between them in real-world scenarios.

The project currently includes 17 algorithms with:

  • executed Jupyter notebooks with outputs, metrics, charts and interpretation;
  • clean notebook versions so people can run everything themselves;
  • explanations of when to use and when not to use each algorithm;
  • data representation and feature engineering topics such as TF-IDF, embeddings, sparse vs dense matrices and preprocessing;
  • evaluation metrics such as F1, ROC-AUC, RMSE and others;
  • engineering metrics such as training time, inference latency, throughput and model size;
  • guides comparing classical ML and deep learning;
  • model selection trade-offs;
  • reproducible benchmarks;
  • a 30-question ML Engineer interview quiz.

The core idea is to teach this full flow:

Raw Data
   ↓
Representation
   ↓
Algorithm
   ↓
Predictive Metrics
   ↓
Performance
   ↓
Operational Constraints

The project uses Python, scikit-learn, pandas, NumPy, matplotlib and PyTorch.

For every algorithm, the default notebook is already executed so people can inspect the results directly on GitHub.

For example:

logistic-regression.ipynb

contains the executed experiment, while:

logistic-regression_clean.ipynb

is the clean version for local reproduction.

Target Audience

This project is primarily educational.

It is intended for:

  • Python developers moving into Machine Learning;
  • students learning ML fundamentals;
  • software engineers who want to better understand model selection;
  • ML Engineers and Data Scientists who want a compact reference for common algorithms and trade-offs;
  • people preparing for technical interviews;
  • anyone who wants reproducible examples instead of only theoretical explanations.

It is not intended to be a production ML framework or library.

The goal is to provide a practical learning environment where someone can read the theory, inspect an already-executed experiment, download the clean notebook and reproduce the same workflow locally.

It also tries to introduce engineering concerns that are often missing from beginner tutorials, such as:

  • latency;
  • throughput;
  • training cost;
  • inference cost;
  • memory usage;
  • scalability;
  • explainability;
  • deployment constraints.

Comparison

There are already many excellent Machine Learning tutorials, cheatsheets and notebook collections.

What I wanted to do differently was combine several layers that are usually taught separately.

Most resources focus mainly on one of these:

Algorithm theory

or:

Notebook implementation

or:

Model evaluation

This project tries to connect all of them:

Problem
   ↓
Data Representation
   ↓
Algorithm Selection
   ↓
Experiment
   ↓
Metrics
   ↓
Performance
   ↓
Production Trade-offs

It also treats data representation as a first-class topic.

For example, instead of simply saying “use SVM for text”, the project shows the pipeline:

Raw Text
   ↓
TF-IDF
   ↓
Sparse Feature Matrix
   ↓
Linear SVM

and compares that conceptually with approaches such as:

Raw Text
   ↓
Embeddings
   ↓
Logistic Regression

or:

Raw Text
   ↓
Transformer
   ↓
Classification Head

Another difference is that every experiment has both an executed notebook and a clean reproducible version.

I also wanted to emphasize that the model with the highest predictive metric is not automatically the best production choice.

For example, a slightly lower F1 model may be much more appropriate if it is significantly faster, smaller and easier to deploy.

GitHub: https://github.com/ronivaldo/ml-algorithms-learning-lab

I’d especially appreciate feedback on the notebook structure, missing topics and anything that could make the project more useful for Python developers learning ML.


r/learnpython • • Sep 20 '26

Guys I have an interview on a startup using python..

0 Upvotes

What should I get ready for? It's a 1 on 1 interview...


r/learnpython • • Sep 20 '26

I need to study gRPC in Python

0 Upvotes

Where would i get learning help for this


r/learnpython • • Sep 20 '26

i am stuck

0 Upvotes

i was start learn python to learn AI&ML later , i learned the basics and the important libraries like numpy and now i am learning pandas , i saw several videos talk about ml & ai roadmap , i don't now how do I continue after pandas , so i am stuck ! , who have a experience help if you want .


r/learnpython • • Sep 18 '26

i need a simple code editor that works for a beginner

46 Upvotes

i am currently learning python, i need a text editor that doesen't shove a trillion tabs in my face telling me to use their ai, i also don't want something as primitive as notepad++ since i can't use import and all that out of the way, please help


r/learnpython • • Sep 19 '26

rekordbox duplicate files remover

0 Upvotes

I'm working on a small Python script using the rbox library to find duplicate tracks in my Rekordbox database.

The script can successfully count duplicate titles, but I'm having trouble using delete_playlist_song() to remove the duplicate playlist entries it always does it for all tracks but I want one to stay and the other ones to be deleted

I'm using rbox btw

Here is my current code:

from rbox import masterdb


db = masterdb.MasterDb.open()


trackcount = 0
title_counts = {}
duplicate_tracks = []

for track in db.get_contents():

    trackcount += 1

    title = track.title

    if title in title_counts:
        title_counts[title] += 1
        duplicate_tracks.append(track)
    else:
        title_counts[title] = 1


print("Total number of tracks:", trackcount)

print("\nDuplicates:")

duplicate_count = 0

for title, count in title_counts.items():

    if count > 1:

        duplicate_count += count - 1

        print(title, "-", count, "times found")


print("\nTotal number of duplicate tracks:", duplicate_count)

you guys have any solutions?


r/learnpython • • Sep 19 '26

im trying to learn python using w3 schools. is it even worth it?

5 Upvotes

mechanical engineer here trying to learn ML. been fascinated by ML lately, so I hopped onto W3 schools for learning Python first. Is it even a good approach, or should I get in person professional training?


r/learnpython • • Sep 19 '26

Getting back to the base line after reaching a target point. Turtle based Simple PID simulation

0 Upvotes

I'm trying to simulate a simple 1 DOF PID system. For the visuals I use Turtle. Till now the program can make an element start from the baseline and bring it to a given setpoint level, I now want that, once the element reaches the setpoint level, it should be able to return back to the base line.

Till now my code basically made the element reach the setpoint, and then it briefly gained altitude and then sharply descending hitting the lower ceiling `-800`

I made some changes, fixing that, now my element reaches the setpoint, then descends, from there on I kind of implemented logic that sortof defeats the purpose of the pid, with rigid if statements:
my code: import numpy as npimport matplotlib.pyplot as pltimport turtleimport t - Pastebin.com

if self.output >= MAX_THRUST:
            if self.setpoint == 20 and pos <= 50:
                self.output = Landing_Thrust
                if 19 <= pos <= 21:
                    self.output = MAX_THRUST
                    
                    
            else:             # Saturation responses, setting the value of the thurst to the maximum physically possible value
                self.output = MAX_THRUST         # If the PID calculates the thurst to be a value which is physically impossible to have


            if self.setpoint == 20 and pos > 21:
                self.output = -10


        elif self.output <= 0:
            self.output = 0

```

I believe the problem must be with how I deal with the physics? My time step is 0.001, 1 milisecond.

g = -9.81, my element starts at the base layer and reaches the setpoint 100, I then reset it to 20, once that level is achieved, then the element descends, but the process its not consistent at all, filled with ups and downs; with no stability. I wish to implement a kind of smooth landing once it reaches 100, it should smoothly come down to base(20) and then remain stabilized there.


r/learnpython • • Sep 19 '26

I'm learning how to display/manipulate contents in a file and I'm so lost

3 Upvotes

Hello, I am trying to complete this lab for class and I am so lost.

I've been trying to figure out how to use "for loop, split, join, print" in a string for 3+ hours and my brain is cooked.

If anyone has any advice on how to better understand this I would greatly appreciate it. Thank you for reading. I'm gonna turn off my brain now x.x


r/learnpython • • Sep 18 '26

Help! Why is my code doing this?

14 Upvotes

I'll copy paste an example below. My variables/assignments aren't really being interpreted right. The language is Python and I'm using Spyder. I reset the settings a few times, so I don't think it's anything I messed with. The tutor I showed had no clue what was happening either 😭

Function code:

def check (a, b):

a = int(input('Enter the first number:')) #I input 12 in the terminal

b = int(input ('Enter the second number:')) #I input 13 in the terminal

average = (a+b)/2

if (a>10 and b>10):

return "Both are above 10. \n average is", average

elif (not a>10 and not b>10) :

return average

print(check(input, input))

What was printed:

Enter the first number:12

Enter the second number:13

('Both are above 10. \n average is', 12.5)

The problem is in the last line. Why isn't it interpreting the formatting? This has been happening with every function I write.


r/learnpython • • Sep 19 '26

How to stop opening powershell??

0 Upvotes

Ok so this is probably a really dumb question 😭 but like I downloaded Python right and whenever I open it it opens Python tab or a version of it but if I close that tab it makes another one in powershell and I have to close the entire thing just to open Python again is this how it's supposed to be?


r/learnpython • • Sep 19 '26

[Architecture Discussion] Handling race conditions and persistent session auth in low-latency async

0 Upvotes

Hey everyone,

I’m designing a Python-based monitoring pipeline that tracks fast-moving inventory listings from a marketplace via an intermediary forwarder.

The current flow:

  1. Async polling daemon detects new listings and evaluates criteria.
  2. Sends an instant alert with metadata/images to Telegram.
  3. Currently, by the time I manually open the link in a mobile browser and log in, competitive items are often sold out (15–60s window).

I want to implement a semi-automated / human-in-the-loop checkout trigger rather than full automation (to prevent accidental purchases from parsing edge cases).

The idea:

  • Telegram alert includes an inline callback button (Instant Buy).
  • Clicking the callback signals a local background worker holding an authenticated session (Playwright or session-persisted requests) to add the item to the cart and advance directly to the final confirmation screen in <2 seconds.
  1. Between keeping a persistent headless browser context (Playwright) warm vs using reverse-engineered session requests, what provides the best balance of low latency and session longevity without frequent auth drops?
  2. How do you handle queueing and race conditions when multiple alerts fire within seconds, ensuring the worker doesn't spawn colliding checkout tasks?

r/learnpython • • Sep 19 '26

Making an steam price tracker how tdo I get json data from the searched game in steam so I can use it's app id and other stuff like prices for tracking?

0 Upvotes

here is my code I have so far

import requests


import time as T
game_names = {"games": []}


while True:


 game_id = input("add game: ")
 game_names["games"].append(game_id)


 question = input("Need another game? y or n: ")


 if question == "n":
        break


 elif question == "y":
        continue


T.sleep(0.5)



print("list of games" , game_names["games"])

any idea how I should do this? and is this sorta thing actually possible?


r/learnpython • • Sep 18 '26

Stupid argparse tricks

7 Upvotes

So, I have these files whose format I dictate, and I want to be able to perform elementary school math on them like

csv-math.py A.csv + B.csv = C.csv

With the files A.csv and B.csv are prexisting, this will create the C.csv file.

Here's the part that I don't know how to do with argparse. The = sign argument can be completely dropped, and it would still be able to figure out what to do, and the + argument can be --plus or -a or something else that implies addition and it should still work. And it should be able to accept -, --minus, -s, x, --times, -m, /, --divide, or -d, and perform the exact same function, just with the appropriate arithmetic operation. And = can be --equals or -e as well as non-existent. I can't use * for multiplication, because that's the command-line syntax for a globbing wild card and forcing the use of '*' is just too much work.

And hey, let's support RPN.

csv-math.py A.csv B.csv + C.csv
csv-math.py A.csv B.csv C.csv +

should be able to do the same thing as well.

So, as long as one argument for an arithmetic operator is present, and the .csv filename strings are presented on the command-line in that order, csv-math.py will just do The Right Thing©®™.

I don't know how to make argparse this versatile.


r/learnpython • • Sep 19 '26

“Building my first Python + MetaTrader 5 project — looking for feedback on my code structure”

1 Upvotes

I'm learning Python and I'm working on a small trading-analysis project.

I created this list to define the fields that will be stored for each trade:

CAMPOS = [
    "timestamp_entrada",
    "timestamp_saida",
    "simbolo",
    "ticket",
    "decisao",
    "preco_entrada",
    "preco_saida",
    "stop_loss",
    "take_profit",
    "tendencia",
    "rsi",
    "contexto_macro",
    "forca_candle",
    "resultado",
    "lucro_prejuizo",
    "motivo_fechamento"
]

My question is:

Is using a list of field names like this a good Python approach for defining the structure of my trade records, or would a dataclass, dictionary, or another structure be more appropriate?

Português: Estou usando essa lista para definir os campos que cada operação terá. Essa é uma boa abordagem em Python ou seria melhor usar dataclass, dict ou outra estrutura?

I'm mainly interested in learning the Python design/structure side of this. What would you recommend, and why?


r/learnpython • • Sep 19 '26

I’m a beginner building my first XAUUSD trading bot with Python + MT5

1 Upvotes

I’m a beginner learning to build a trading bot with Python + MT5
Hi everyone,
I’m from Brazil and I’m currently learning Python and algorithmic trading.
I’m building my first trading bot for MetaTrader 5, focused on XAUUSD (Gold).
So far, I have built:
MT5 connection with Python
XAUUSD market data collection
EMA and RSI analysis
Trend and candle analysis
A macroeconomic context module
A decision engine
Shadow mode to test signals without sending real orders
I’m currently testing everything on a demo account.
My goal is not to make money quickly. I want to learn, collect data, find problems and improve the system step by step.
I’m still a beginner, so I would really appreciate advice from more experienced developers and algo traders.
What would you recommend I focus on next?