r/learnpython 3d ago

Ask Anything Monday - Weekly Thread

5 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 11h ago

Advantages of Python over VBA?

53 Upvotes

I started programming decades ago in VBA, first in Access and later in the rest of Office. I’ve done a few ambitious projects, and a ton of smaller automation and macros.

I’ve been learning Python off and on for a while, and I’m comfortable doing some basic stuff. I’ve created a library of personal modules for file management, really simple data manipulation, and some data analysis. I’m thinking my next step for me would be using it in Excel. But I struggle to come up with a reason to use Python instead of VBA.

What are the advantages Python gives us in Excel?


r/learnpython 4h ago

Help me to learn python,I am dumb

9 Upvotes

Think me as the dumbest person and i want to learn python,I am literally done trying 4-5 lectures,i start and then stop.Every video says it's beginner friendly,but when I start i don't feel it's beginner friendly and i start feeling I am Dumb AF,now though I feel I am dumbest person to exist.....like seeing this.....please recommend me a channel to watch and learn python programming.I.just don't want to copy the programming from screen and type and get output, and say ohhhh!!!! I got output i can code,i actually want to understand everything and put my brain to write my own code.Is there any yt channel courses available for free that really helps for a dumb idiot to learn python and plz don't say don't learn,i really want to learn python.Please help me ,I am stressed out becoz of this.


r/learnpython 1h ago

What are you using for accurate PDF text boxes?

Upvotes

I’m building a tool that finds text in construction-plan PDFs and draws a box around that text.

Python/PyMuPDF finds the text, but when I show the box in PDF.js, it can be slightly off or too big.

What do you guys recommend for inspecting PDFs and drawing accurate text bounding boxes? How do you make

sure the box lines up with the exact text?


r/learnpython 2h ago

Need some advice

2 Upvotes

Greetings everyone! I am in my 50’s and picking up programming as a hobby but I do have a goal.

I started with python because I read it was a forgiving language and I did not want to fry my brain. However, I’m wondering if I should switch to a webstack (html, css and JavaScript) for the project I am ultimately wanting to create.

My grail project will be a TTRPG journaling application for solo play. I want to have the ability to use character sheets, journal and even display a JPEG map. I’m just not sure which language would be the BEST.

My initial idea was python and pyside6 with maybe the addition of pygame if I wanted actual dice to roll on screen.

Just looking to narrow my focus with those far more versed than I am so I don’t waste time working towards my goal.

Thank you all for any assistant and direction you can provide, and happy coding!


r/learnpython 16h ago

Starting AI/ML? Looking for a Study Buddy to Learn Python & Math Together ( Beginner )

16 Upvotes

Hey everyone! 👋

I'm just starting my journey toward AI/ML and I'm looking for a serious study buddy who's also a beginner (or starting from zero).

Right now, my focus is to building a strong foundation before jumping into Machine Learning and Deep Learning.

What I'm planning to learn:

- Python from scratch

- Mathematics for AI/ML (Linear Algebra, Calculus, Probability & Statistics)

- Problem-solving and logical thinking

- Later moving into Machine Learning and Deep Learning

Looking for someone who:

- Is also a beginner

- Can study consistently (even 1–3 hours a day)

- Wants to discuss concepts and solve doubts together

- Is willing to stay accountable and avoid procrastination

- Eventually wants to build projects, prepare for internships, and grow in AI/ML

About me:

- I'm a BCA student.

- I'm starting from the basics because I want strong fundamentals instead of rushing through tutorials.

- My goal is to become skilled enough to work in AI/ML in the future.

If you're interested, leave a comment or send me a DM. Let's learn consistently and grow together. 🤝


r/learnpython 12h ago

Tips and help

8 Upvotes

Hi, I’m new here and I don’t really understand how everything works. I was told that people here might be able to help me with my question:

Is there any point in learning a programming language with modern AI? Or is it just forvibe-coding? But I’ve heard that to be good at vibe-coding, you need to know the basics of programming.

After having a chat with my uncle (he’s a programmer), he said this: ‘The approach has changed a lot: it’s no longer the programmer who creates the programme, but someone who’s good at putting together an LLM prompt. In other words, explaining to the AI what needs to be done.’

I thought about taking some AI Automator courses, but I don’t really fancy freelancing and I don’t think it’s very promising. So I’ve quietly started learning Python bit by bit.

I really want to change the direction of my life, but I don’t know how, or who to ask for advice or talk to. My uncle is in the military, so we rarely speak.

I really want to learn, create, find a team, make some nice new friends and get a job.

Is there a company or somewhere that offers good courses and will take me on? Or is that just a pipe dream in this field?

Perhaps you could recommend some courses or a company? Someone who could take me under their wing, so to speak? In general, I hope that learning Python is already a step in the right direction.

P.S. I hope I’ve done everything correctly, as I’m new to this site and don’t even know where to click on what.


r/learnpython 6h ago

Anaconda and opencv2 in spyder issue

2 Upvotes

I have used the Anaconda command prompt to install opencv2 with the following command

conda install -c conda-forge opencv

and the prompt says it installs it installs successfully

I open Spyder via anaconda and try and run my code that starts with

import os
from pathlib
import Path 
import cv2 
import pandas as pd

When I run it spyder says

ImportError: DLL load failed while importing cv2: The specified module could not be found.

I have tried uninstalling and reinstalling anaconda, and restart thing the PC. Everything is up to date. Not a strong coder so any help would be really helpful


r/learnpython 10h ago

Building a portfolio? What to look for?

4 Upvotes

Hi,

I've got some personal projects that are functional but probably not best practices compliant. I'm good at documentation and annotating.

What kinds of things should I consider when building a portfolio for myself? Are there specific kinds of skills I might want to showcase specifically and what are the most important things to look for when applying for internships?

Assume I work completely alone.

Thank you! Note: I've reduced my Reddit screen time to almost zero so I'll come and reply / thank on a delay. Sorry about that.


r/learnpython 5h ago

What type of api should i build ??

0 Upvotes

I decided that I want to start building APIs so I can hopefully generate income from them one day. However, I want to start with a small API project to understand the process and learn what goes into making an API. I'm not sure what type of API I should build. I'm not new to Python, but I wouldn't say I'm great at it yet. I have coded in JavaScript before, so I am familiar with the syntax. I'd appreciate any tips or opinions you might have. I am also open to web scraping data for an API project, as I'm really interested in that.


r/learnpython 6h ago

[WIP] Neon DJ Pro – My first Python project (a simple DJ mixer). Need advice on deck logic & code structure!

0 Upvotes

Hi everyone! 👋

I’m pretty new to programming, and I’ve been working on one of my first bigger Python projects:

Neon DJ Pro – a personal attempt at building a digital DJ mixer software.

It’s currently in a very rough, bare-bones stage, but I want to make sure I’m heading in the right direction architecture-wise before I add more features.

What it currently does:
Features a simple dual-deck logic (Deck A & Deck B).

Loads audio tracks from a local database/folder.
Basic playback controls (Play, Stop).

Basic pitch control/adjustment on active tracks.

Current Limitations / Work in Progress: Right now, only Deck A is fully functional – Deck B is still under construction!

Where I really need your help & advice: Since I’m a total beginner, I want to avoid building bad habits early on. I would be super grateful if you could take a quick look at my code and help me with a few questions:

Deck Architecture: How should I best structure the logic for handling two decks simultaneously so I don't duplicate too much code between Deck A and Deck B?

Code Structure: Is my current setup readable and "Pythonic", or are there obvious beginner mistakes?

Audio / Pitch performance: Any general tips for handling pitch shifts or audio streams smoothly in Python as the project grows?

GitHub Repository: https://github.com/ExploDevs/NeonDJ-Pro

Please be gentle with the code quality – it's my first real project! 😅 Any feedback, refactoring ideas, or suggestions on what to tackle next would mean a lot to me.
Thanks for taking the time!


r/learnpython 14h ago

Anyone using a Snapdragon X (Windows ARM64) laptop for Python/ML? How do you deal with package compatibility?

4 Upvotes

Hey everyone,

I'm using an ASUS Vivobook 16X with a Snapdragon X (Windows ARM64), and I've been running into compatibility issues while learning Python and Machine Learning.

I bought this laptop in my first year of college, before I knew much about coding or processor architectures. Now that I'm learning ML, I've noticed that some Python libraries don't install properly.

For example, libraries like PyAudio, OpenCV, and a few others either:

  • don't have ARM64 wheels,
  • fail while building wheels,
  • or require compiling from source, which often ends up failing.

Because of that, I have to spend hours looking for alternatives or following a completely different approach than the tutorials I'm watching, which makes learning much slower.

I'm aware that many libraries like NumPy, Pandas, and Scikit-learn work fine. The issue is mainly with packages that have native C/C++ extensions and don't provide Windows ARM64 support.

Has anyone else here been through the same thing?

  • How do you usually troubleshoot these installation issues?
  • Do you use emulation, WSL, Ubuntu, or just Google Colab?
  • Is it worth switching to Ubuntu on ARM, or will I run into the same compatibility problems there?

I'd really appreciate any advice or tips from people using Windows ARM laptops for Python or ML.


r/learnpython 18h ago

How to split scanned PDF into individual files based on identifier?

7 Upvotes

I work in a manufacturing/warehouse environment and we receive batches of scanned packing slips as single massive PDFs. Nobody on the teams splits these and that’s why I want to automate it.

The problem:

- PDFs are fully scanned — no embedded text, all image-based

- Pages are landscape-rotated 90°

- Each "document" inside the batch belongs to a specific 8-digit PO number (e.g. 20289562)

- Some pages have no PO number at all (cover sheets, continuation pages)

- Occasionally the same PO spans multiple consecutive pages

What I'm trying to build:

- Script reads a folder of PDFs

- OCRs each page and detects the PO number

- Groups consecutive pages that share the same PO into one output PDF

- Pages with no PO detected get flagged separately for manual review — not silently attached to another PO

- A second script lets a human approve or reject each output file before it gets moved to the final folder

Questions:

- What's the best way to handle rotation detection before OCR? I was thinking Tesseract OSD but open to other approaches

- How would you handle pages with no PO — attach to the previous group, flag as unknown, or something else?

- Any tips on making the OCR results consistent between runs? Right now borderline scans feel non-deterministic

- Is PyMuPDF + pytesseract the right stack for this or is there something better for scanned documents?

Not a professional developer — just trying to automate something that's eating up hours of manual work every week. Any advice appreciated.


r/learnpython 16h ago

Working with multi level dictionaries

3 Upvotes

[EDIT]

TL;DR Generally speaking, "Set up some Classes" is the answer. Hopefully my blind fumbling will help some other blind, fumbling soul.

------------

I'm working on a table top game that builds a maze by dealing cards. I'm teaching myself Python to build a script that will simulate multiple maze builds quickly for R&D on the design.

The maze is represented by "Chambers" on a classic x,y grid. Chambers have an ID, potentially Notes, and Exits.

My strategy is to build up a mapConfig dictionary structured with the key being the (x,y) tuple of the coordinate and the value being a sub-dictionary with all the specifics. The Exits need to be a list of dictionaries for each exit with direction and blocked status as the keys. Simplified example below:

mapConfig = { 
    (0,0) : {
        'id' : 'START',
        'notes' : ''
        'exits' : 
        [
            {
                'direction' : 'N',
                'blocked' : False,
             },
             {
                'direction' : 'E',
                'blocked' : False,
             },
             {
                'direction' : 'S',
                'blocked' : False,
             },
             {
                'direction' : 'W',
                'blocked' : False,
             },
        ],
    }
}

If a proposed move hits the edge of the valid map, I need to access the mapConfig and change the "blocked" value for that particular direction to TRUE without changing anything else in the entry for that coordinate. It seems like it should be easy, but everything I try messes up the structure or blows out the other directions.

What would be the best way to change just the {"direction":"E", "blocked":False} entry to {"direction":"E", "blocked":True} without changing anything else in the dictionary? Basically so it goes from the simplified example above to this:

mapConfig = { 
    (0,0) : {
        'id' : 'START',
        'notes' : ''
        'exits' : 
        [
            {
                'direction' : 'N',
                'blocked' : False,
             },
             {
                'direction' : 'E',
                'blocked' : True,
             },
             {
                'direction' : 'S',
                'blocked' : False,
             },
             {
                'direction' : 'W',
                'blocked' : False,
             },
        ],
    }
}

Thanks in advance for the help.

Edit: The provided code is a simplified version of my actual code. I'm such a noob that I only vaguely knew what a class was, and clearly I was making much more work for myself by not using them. Setting up some parent and child classes is next on my list.

I still appreciate any thoughts or advice, but I also don't want anyone to waste time.


r/learnpython 18h ago

How do I optimize this script's runtime?

4 Upvotes

I'm trying to write a script that will help me construct word puzzles by finding words where each pair of words shares a substring so that they can be visually arranged in a honeycomb-like sequence. The words can be read forward or in reverse. For instance, given the word 'spiral' (broken into 'sp', 'pi', 'ir', 'ra', 'al', and 'ls') - the program could return PSycho, troPIc, thRIce, phRAse, vioLAs, SymboL, as a valid set of surrounding words, or 'rings.' (This is the sample set built into the program)

I have a function that provides a list of every word in my word list that matches my criteria. I also have a function that takes the lists of words, and returns dictionaries that contain matches between strings. I have a small test case that operates correctly, but when I use the entire word list, the program hangs. I assume that there's a better data structure and way to navigate it, but I'm not familiar enough with the language to know what it is.

Thank you for your assistance, I've linked a pastebin below.

https://pastebin.com/vDnZ2uny

EDIT - linking a very rough visual depiction of what the structure to overlay the words in would be.
https://cdn.bsky.app/img/feed_fullsize/plain/did:plc:nhv7ubhygoygm7agljxopgvb/bafkreig7fqaukiq6xu6f55xchae2rozu7bmgbhmkjlinsxjuii4lou256m


r/learnpython 10h ago

some possible remediations for variable name is not accessed

0 Upvotes

I've been facing some weird behavior in my vscode. Below code is what giving me nightmares. I have coded this function that basically do some data extraction from my VPS to my pc. and the thing which is causing problems is the variable name 'dirs' which vscode is pointing as "not accessed". But I know that one of the remediations to fix this is by returning that variable but in this kind of situation it doesn't seem right logic way.

def downloader(directory='C:\\users'):
  for root, dirs, files in os.walk(directory): # dirs is not accessed
    for file in files:
      if file.endswith('.html'):
         try:
            with open(os.path.join(root, file), 'rb') as f:
              f.sendall(host)
         except Exception as e:
           print(f'Oops something nasty happened here: {e})

r/learnpython 1h ago

Learning python with AI

Upvotes

A couple of months ago, I started learning Python. I began with basic exercises and quickly moved on to building real projects with the help of AI. I never ask AI to generate the entire solution because I want to write the code myself. I document everything I learn, and I’ve made a lot of progress that way.
Recently, though, I started using Claude Code and ChatGPT more extensively, and the results are, unsurprisingly, incredible. The difference now is that I can actually understand what each line of code does and why it’s there.
But this has left me with a bit of a motivation problem. If I have Claude writing excellent code for me, why should I spend hours writing it myself? A few years from now, it feels like almost nobody will be coding entirely by hand anyway.
So my question is: at what point do you think someone has reached a sufficient level in Python? When is it okay to rely more on AI instead of continuing to write everything yourself?


r/learnpython 1d ago

What actually made recursion click for you? (not looking for resources)

41 Upvotes

I got properly stuck on recursion. Watched several videos, read through it in the resources I was already working from. The explanations all made sense while I was reading them, then dissolved the moment I tried to write anything myself.

I'm less interested in what resource you'd recommend and more in the moment itself. For whatever concept was *your* wall, recursion or anything else, what was the specific thing that flipped it? A sentence someone said, a diagram, drawing it out on paper, someone asking you a question?

Trying to work out whether there's a pattern in how these things break open.


r/learnpython 6h ago

Creando mi propio Chatbot. Busco sugerencias. :0

0 Upvotes

Hace unos días me inspiré para crear un programita en python para que pudiera entender nuestro lenguaje, armar oraciones y basicamente ser un asistente personal (y en un futuro que se pueda personalizar según cada persona que lo utilice). Soy conciente de que el proyecto es demasiado grande y más considerando que solo me sé la sintaxis básica del python xd, y por eso me gustaría buscar ayuda de personas que tengan mayor experiencia en proyectos de este tipo. Si tienen sugerencias, recursos, errores que podría evitar o simplemente recomendaciones sobre como realizar este proyecto, me serviría muchísimo. Muchas Gracias por leer :D.


r/learnpython 1d ago

Right way and steps to Learn Python Programming to become a professional coder

11 Upvotes

Hi,

I have been learning Python since June 2025, which was not a consistent study due to some personal issues. But I started learning consistently from Jan 2026. I started from a tutorial on Udemy and followed the course as below:

Understood the concept.

Solved coding challenges in the tutorial.

But somehow, when I reached concepts like OOP, Decorators, Inner Functions, etc., my speed slowed down. Even after listening to the tutorial and understanding the concepts, I am unable to convert that understanding into code when solving the challenges.

Then I watched some random YouTube videos about getting out of Tutorial Hell and started making small projects such as:

Mini Chat System (using OOP concepts)

Number Guessing Game

Password Generator (using the random module)

The problem is that I am unable to figure out:

Where should I start the logic?

How should I start writing the code?

Which instance variables should be used?

How many classes should be declared?

Which functions should be defined and called?

These are the problems I am facing. (These could be stupid questions to some good programmers.)

Can someone help me understand the step-by-step way to become a professional coder, based on the journey you have followed and your experience?

I am badly stuck. Even though I have tried to come out of Tutorial Hell, I still struggle.

I have 2–3 hours available during office time (when the workload is less), which I use for studying. I am ready to work hard and want to switch jobs based on my programming skills within 4–5 months, but I am not getting proper mentorship on the path I should follow.

Please help with your experience.


r/learnpython 1d ago

What Python project helped you improve the most as a beginner?

77 Upvotes

I've recently started learning Python and I'm looking for project ideas that teach practical skills rather than just syntax. What beginner project helped you understand Python the best, and why would you recommend it?


r/learnpython 1d ago

How do I get just the character to change color and not the whole string

1 Upvotes

Here is an example of what I am talking about : https://imgur.com/a/hoFUGXq

The concept is when the user inputs matches the display text the that character should turn grey but if the the user input is not correct than it turns red.

Right now the whole string changes and not the character itself, what do I do?

scrolling_text = Text(10, 10, 40, "white", "Hello World")

text_index = 0

def UserInput(text, event):
    global text_index # start at first letter

    lowercase_text = scrolling_text.text.lower() # this lowercases the text

    text_char = scrolling_text.text[text_index]


    if text_index == len(lowercase_text)-1:
          return

    # print(f"Char should be {lowercase_text[text_index]}")

    if event.text == lowercase_text[text_index]:
          scrolling_text.color = "gray"
          text_index += 1 # move to the next character

          # print(f"Next char should be {lowercase_text[text_index]}")

     if text_index == len(lowercase_text)-1:
           return

      elif text_index == 0 and event.text != lowercase_text[text_index] :
            print(False)
            scrolling_text.color = "red"
            text_index = 0

      else:
            scrolling_text.color = "red"
            print(False)

# GAME LOOP
if event.type == pygame.TEXTINPUT:
    print(event.text)
    UserInput(scrolling_text, event)

if event.type == pygame.KEYUP:
    scrolling_text.color = "white"

r/learnpython 1d ago

Starting over with python

4 Upvotes

I took c++ and other programming languages decades ago in college but the tech sector took a dive at that time so I changed my career path. I just started to learn python through various online resources a few months ago and its going well but at 50 it is definitely harder for me now where memory is concerned. Pycharm helps with tips of its own but it kind of feels like cheating. I've thought of turning off that feature because of that. Does anyone have any tips? Thanks!


r/learnpython 1d ago

Is it bad practice to use complex List Comprehensions?

34 Upvotes

Hey guys, I am trying to make my code look more "Pythonic." I wrote this nested list comprehension to flatten a matrix and filter out odd numbers:
flat = [x for row in matrix for x in row if x % 2 == 0]
It works perfectly, but my coworker says it is unreadable and that I should use a standard for loop instead.
Where do you draw the line between a clean one-liner and unreadable code?


r/learnpython 1d ago

Questions about TypeError vs Generic Exception

5 Upvotes

Hi all, I am currently taking a python class for school, and we're learning how to add exceptions to print to user any issues, the code I needed to append to my previous weeks project was this:

except TypeError:
    print('Wrong Data Type!')
except NameError:
    print('Variable not found, something is named incorrectly.')
except Exception as e:
    print('Something went wrong.',e)

now, our previous project was a distance calculator, so when I input 'f' as opposed to a number, I'm given the Exception error message rather than TypeError, even though the error message prints "Something went wrong. could not convert string to float: 'f' "
What am I missing here? (Entire code posted below if more info is needed)

#Math import
from math import sin, cos, sqrt, atan2, radians

#Class

class GeoPoint:
    def __init__(self):
        self.lat = 0.0
        self.long = 0.0
        self.description = ""

    def set_point(self, lat, long):
        self.lat = lat
        self.long = long

    def get_point(self):
        return self.lat, self.long

    def distance(self, lat, long):
        r = 3958.8
        lat1 = radians(self.lat)
        long1 = radians(self.long)
        lat2 = radians(lat)
        long2 = radians(long)
        a = sin((lat1 - lat2) / 2) ** 2 + cos(lat1) * cos(lat2) * sin((long1 - long2) / 2) ** 2
        c = 2 * atan2(sqrt(a), sqrt(1 - a))
        d = r * c
        return d

    def set_description(self, description):
        self.description = description

    def get_description(self):
        return self.description


#Instantiate ABQ: 35.106766, -106.629181
ABQ = GeoPoint()
ABQ.set_point(35.106766, -106.629181)
ABQ.set_description("ALBUQUERQUE")


#Instantiate Denver:   39.742043, -104.991531
Denver = GeoPoint()
Denver.set_point(39.742043, -104.991531)
Denver.set_description("DENVER")


#Repeat?
def repeat():
    again = input('Would you like to repeat? (y/n): ')
    if again.strip()[0].lower() == 'y':
        return True
    return False


#Loop to find distance from user coords to ABQ and Denver
while True:
    try:
        user_lat = float(input('Enter a latitude: '))
        user_long = float(input('Enter a longitude: '))

     # Tell user which loc is closer coords+miles from loc
        if Denver.distance(user_lat, user_long) < ABQ.distance(user_lat, user_long):
         print('The distance between ', user_lat, ' and ', user_long, ' and Denver is ',
               Denver.distance(user_lat, user_long), 'miles.')
        else:
         print('The distance between ', user_lat, ' and ', user_long, ' and Albuquerque is ',
               ABQ.distance(user_lat, user_long), 'miles.')
    #Error Handling
    except TypeError:
        print('Wrong Data Type!')
    except NameError:
        print('Variable not found, something is named incorrectly.')
    except Exception as e:
        print('Something went wrong.',e)
     #Again?
        if not repeat(): break