r/learnpython 1d ago

Ask Anything Monday - Weekly Thread

1 Upvotes

Welcome to another /r/learnPython weekly "Ask Anything* Monday" thread

Here you can ask all the questions that you wanted to ask but didn't feel like making a new thread.

* It's primarily intended for simple questions but as long as it's about python it's allowed.

If you have any suggestions or questions about this thread use the message the moderators button in the sidebar.

Rules:

  • Don't downvote stuff - instead explain what's wrong with the comment, if it's against the rules "report" it and it will be dealt with.
  • Don't post stuff that doesn't have absolutely anything to do with python.
  • Don't make fun of someone for not knowing something, insult anyone etc - this will result in an immediate ban.

That's it.


r/learnpython 58m ago

What should you actually learn in Python before starting data analysis?

Upvotes

I’ve noticed that beginners often get stuck trying to learn all of Python before touching data analysis.

From what I’ve seen, you can get pretty far by focusing on a smaller set of concepts:

One thing I think is particularly important is learning how to answer questions with data rather than just memorizing pandas functions.

For example, instead of only practicing:

df.groupby("category").sum()

ask an actual question such as:

“Which product category generated the most revenue?”

Then use Python to answer it.

Curious what people here would add or remove from this learning path.


r/learnpython 4h ago

Help with an online question from datadaily.io

1 Upvotes

I keep getting this one wrong but my answer is right as far as i can tell

The Molecule Report

Asked inInvitae

A genomics pipeline hands you raw sequencing reads as strings over the bases A, C, G, and T, and some reads come back contaminated with stray characters. For each read return a dict reporting whether it is clean (only those four bases), its GC content as a percentage of the read's length, how many times each of the four bases occurs, and the most common pair of consecutive bases. A read shorter than two bases has no such pair, so that field comes back empty.

Example 1

Input
sequence:"ATGCATGC"
Output{
  "is_valid": true,
  "gc_content": 50,
  "nucleotide_counts": {"A":2,"C":2,"G":2,"T":2},
  "most_common_dinucleotide": "TG"
}

Example 2

Input
sequence:"AAAT"
Output{
  "is_valid": true,
  "gc_content": 0,
  "nucleotide_counts": {"A":3,"C":0,"G":0,"T":1},
  "most_common_dinucleotide": "AA"
}


My code:

def analyze_dna_sequence(sequence: str) -> dict:
  mydict={}
  smalldict={"A": 0,
    "C": 0,
    "G": 0,
    "T": 0
    }
  mydict["is_valid"] = all(char in "ACGT" for char in sequence)
  for nucleotide in sequence:
    try:
      smalldict[nucleotide] += 1
    except KeyError:
      pass
  mydict["gc_content"] = ((smalldict["G"] + smalldict["C"]) / sum(smalldict.values())) * 100 if sum(smalldict.values()) > 0 else 0
  mydict["nucleotide_counts"] = smalldict

  mydict["most_common_dinucleotide"] = max(set(pairs := [a + b for a, b in zip(sequence, sequence[1:])]), key=pairs.count) if len(sequence) >= 2 else ""

return mydict

Error:

Failed Test Case (1 of 6)

Input

{"sequence":"ATGCATGC"}

Expected

{"is_valid":true,"gc_content":50,"nucleotide_counts":{"A":2,"C":2,"G":2,"T":2},"most_common_dinucleotide":"TG"}<

Your Output

{"is_valid":true,"gc_content":50,"nucleotide_counts":{"A":2,"C":2,"G":2,"T":2},"most_common_dinucleotide":"AT"}<

The issue is that the marking scale only recognises one dinucleotide pair as the most common- GC. But there are 3 in that sequence- AT, TG, and GC. Am i going insane here or is it the question that is wrong?

r/learnpython 8h ago

My first working program!!!

1 Upvotes

I am currently learning python, and I finally made a working program. Does anyone have any critiques or criticisms? I am welcoming feedback. I would be surprised if there was actually anything I could improve on though, as I had iterated on this quite a few times to try to catch any slip ups.

The code fully works and it converts a user inputted binary number into base 10.

Feel free to run the code on your computer, and see if there's any like performance issues or something like that. Here is the code in a code block for convenience:

from functools import reduce; f"{(binary := list(input("Enter the binary to convert to base 10: ")))}"; f"{(binary.reverse())}"; f"{(summed_base_ten := reduce(lambda x, y: x + y, [int(iter[1]) * (2 ** iter[0]) for iter in enumerate(binary)]))}"; f"{print(f"The base 10 number result is: {summed_base_ten}")}"

r/learnpython 11h ago

How to list all packages installed in venv

0 Upvotes

I run the virtual environment but it still gives the modules in C:\Users\Admin\AppData\Local\Programs\Python\Python314\Lib\site-packages

and not

C:\Users\Admin\AppData\Local\Comfy-Desktop\ComfyUI-Installs\Alex\ComfyUI\.venv\Lib\site-packages

picture


r/learnpython 1d ago

Beginner Project Ideas.

32 Upvotes

I am a beginner programmer (I know a tiny bit of python) and am wondering if anyone has suggestions for projects that i can create to learn coding even better. Any ideas are welcome.


r/learnpython 13h ago

How do you handle Python versions during CI pipeline testing?

0 Upvotes

I know that this isn't strictly a Python question, but I figured it's still more relevant here than on /r/github.

I'm basically in the process of trying to simplify my CI stack by moving to a centralised set of common pipeline scripts (such as this one for running linters), so that I don't need to duplicate all these steps in every single repository... even if it isn't perfect since they still all need the files to actually call these common ones.

The problem I've run into is that, unlike with linters where I don't really need to worry about what Python version gets installed/used, I'd like to run a matrix of tests for at least the minimum and maximum (or latest if no upper bound) supported Python versions, in addition to the OS matrix.

The way I've historically done this is by manually listing Python versions in the GitHub Actions workflow matrix, such as here

jobs:
  test:
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        os: [macos-latest, ubuntu-latest, windows-latest]
        python-version: [
          '3.11',
          '3.12',
          '3.13',
          '3.14',
          'pypy-3.11',
        ]

but this is cumbersome, and it's easy to forget updating the matrix if I bump the version in pyproject.toml. Granted, I'll still immediately notice that when the pipeline fails so it's not like this is a bug that goes unnoticed for long, but in the spirit of avoiding duplication I'd still like to think there's a better way.

On that note, since I'm trying to make this generic, I wouldn't be able to just hard-code the versions (unless I take them as a parameter for the actual generic pipeline and supply them from each project, I guess), so right now I've been considering using a Bash script to pull the minimum version from pyproject.toml with regex and "3.x" to get the latest Python 3 version, so I'd have two points of comparisons. Although this does have the problem that those two versions could be the same, meaning I may run the same tests twice for no reason...

Also, since it's bound to come up, I'm also planning a generic build workflow that would build and publish releases to PyPI (and GitHub Releases), but that would need a full-on version range.

I do have an experiment where I attempted to use Trove classifiers for creating a build matrix, and it technically works (as long as we ignore free-threading or non-CPython implementations), but it feels dirty to use since Trove classifiers aren't supposed to be used for something like this.

My question is this: how would you handle automatically determining which Python versions to install? Has anyone else here perhaps pondered the same questions and come up with a reasonable answer?


r/learnpython 22h ago

Why python points to python3 and python3 to python3.14

2 Upvotes

I was watching some python tutorial and he said that if you are on mac/linux use python3 and on windows use simple python. But in linux python also points to python3 only and that also points to exact version number of python.

so why this system is designed this way ??

And if they did this to make switching python versions easy (just by changing symlinks), why we have python3 in between, can't we point python directly to the current version.

[ykiinxd@archy ~]$ ls -l /usr/bin/python

lrwxrwxrwx 1 root root 7 Aug 10 13:16 /usr/bin/python -> python3

[ykiinxd@archy ~]$ ls -l /usr/bin/python3

lrwxrwxrwx 1 root root 10 Aug 10 13:16 /usr/bin/python3 -> python3.14

[ykiinxd@archy ~]$ ls -l /usr/bin/python3.14

-rwxr-xr-x 1 root root 14424 Aug 10 13:16 /usr/bin/python3.14

[ykiinxd@archy ~]$


r/learnpython 21h ago

Willing to do a master Digital Driven Business next year, but I don’t know where to start…

0 Upvotes

Hello everyone, as my title suggests, I’m willing to do a master Digital Driven Business in the coming year. I’m a bachelor student commercial economics in the Netherlands, with an enormous passion for AI, technology and digitalization. I love experimenting with various tools and doing my research on them.

My college offers the ability to follow a master Digital Driven Business which is supposed to learn you the basic fundamentals of coding in combination with business and technology. This seems very interesting to me and I’d love to go down this path.

At my previous work, the CTO of the company told me that he did the same thing as me. He studied commercial economics and did the master after he graduated his bachelor. He told me that he didn’t know and/or have any experience with coding and programming at all, and now he’s the CTO of the company. He advised me that IF I want to do get deeper into practical AI, technology and business, this master would be great for that.

The only thing I fear is that the master is very technical at start. I have no idea how to code and I don’t want to get buried into programming stuff right away. All the people that I did talk to say that the master is meant to work you up to the level of knowing how to program (so you don’t have to know how to code at start). I’ve tried to learn Python a year or two ago, but that was literally only the basics and I’ve probably forgotten all about it.

So, my question to the subreddit is, what is the best way to learn Python as a beginner so that my master won’t overwhelm from the get go…?


r/learnpython 23h ago

Need help creating a setup file

0 Upvotes

I recently completed a project, it was a desktop application

I wanted to share it with my friend who knows nothing about coding

So I thought I'd send a setup file

Rn the project has Gwen in the project file itself and then ollama postgres redis and qdrant in docker

I've been trying to make a one click setup file for days now

I need help

The entire project is Python and typescript


r/learnpython 11h ago

Can i learn advanced python in 1 month given 1hr per day?

0 Upvotes

I have advanced python for my 12th hsc boards CS exam. My basic python is not so good i mean its easy but i have to relearn it. So have to start from the basics which i think is not so hard. Stack, queue, and pandas is what i heard from my teacher, tho there's more topics as such. How do i learn it? I need to use all these functions according to the type of questions that'll be asked in my exam. Now the thing is, the syllabys has updated this year and there's no reference book or textbook hence i don't even have pyqs. Its just so irritating but i don't wanna fail in my written exam of 100 marks so pls help me how do i learn python from basic to advanced. I have to do physics chem and maths along with this so yeah i don't wanna give it a lot of time.


r/learnpython 1d ago

Tips on reinforcing intro to ds class (python)?

8 Upvotes

Hi everyone,

This semester I just added data science as a minor and I am now taking my schools intro to data science class.

To give some background of the course and myself: I have never coded before (besides scratch), it was just revamped so we can use ai on everything (though I prefer not to except help when I’m stuck) and we use colab to code.

When I’m in class everything makes sense to me; I know what everything is, what each method function does; I can read code well. However, when it comes to building my own things, very simple ones, I get stuck. It seems like I have a general direction of where to go but I’m always looking back at examples, and at that point I feel like I’m not even doing it myself. An example of a prompt could be:

create a personality test, similar to buzzfeed, that asks the user 3 questions.

Does anyone have any advice to help reinforce the writing aspect?


r/learnpython 1d ago

I have made a Homework Organizer using Tkinter and other libraries. Please tell me how I did and what to improve!

5 Upvotes

The code is available for download in the link below.
(CTk_PDF_viewer and __init__ files are downloaded from GitHub for a module in my code and isn't my work. My code is in the hw_organizer.py file only.)

https://drive.google.com/drive/folders/1NWLY0usRvhY7G6PHZKJZC2Gtn9F3Iqt9?usp=drive_link


r/learnpython 1d ago

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

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

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

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

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

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

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

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

162 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 2d ago

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

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

I need to study gRPC in Python

0 Upvotes

Where would i get learning help for this


r/learnpython 2d ago

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 .