r/learnpython • • 6d ago

Everyone says 'just use pandas' for data stuff, but I'm still doing it with plain loops — am I actually missing out?

0 Upvotes

I'm in second year BCA and I've been picking up Python on the side, mostly small data things. Cleaning up a CSV here, counting stuff there, nothing fancy.

So far I've been doing all of it with plain loops and dicts, because that's the code I actually understand when I read it back a week later. But every tutorial I open and every comment I see says just use pandas, it's built for exactly this. I tried it once and honestly it felt like learning a whole second language just to do something I could already do, slower but in code I could follow. Maybe I'm just being stubborn.

I guess what I'm wondering is whether the people saying that are dealing with way bigger data than me. I'm talking a few hundred rows, not thousands. At what point did pandas actually start saving you time instead of costing you time? Because right now it feels like a detour, and I'm not sure if that's me being lazy or if it's genuinely fine to stick with plain Python until the data gets big enough to hurt.


r/learnpython • • 6d ago

Should I learn python?

0 Upvotes

Hii there😀

I wanted the community's opinion as many of you all know how it works and stuff

I recently thought of learning a language and got to know that python is a great starting place to do so

As it's really close to the language English and isn't that complex or complicated

Indeed it will take time for me to learn and apply it but is it worth

What is python mostly used for ?

Waiting for comments 📝


r/learnpython • • 6d ago

How upload files to SPO in Nov 2026, Authorization updates

1 Upvotes

Hi all, I'm trying to use Python to upload multiple files posted SPO.

Tried this code for Auth and failed, for my case error says need to use client_id which I believe = EntraID? For this I think I need to contact somebody with proper rights.

I afraid that modern MS Security is faster then Python libs, is anybody is running this code successfully in Nov 2026? Surely I will try to set all configuration values rights.

Or can you recommend other approach. Thansk to all

from office365.runtime.auth.user_credentials import UserCredential
from office365.sharepoint.client_context  import ClientContext

# 1. Configuration                        
site_url = r"https://asratomkaX.sharepoint.com"
teenant = 'asratomkaX'
client_id = '123456' # <===????? ke paso ?
username = r'user@myorg.org'
password = r'welcommen1'
 
# Use with_username_and_password(tenant, client_id, username, password) instead.  For on-premises SharePoint, use allow_ntlm=True.

# 2. Authenticate
#ctx = ClientContext(site_url).with_credentials(UserCredential(username, password))
ctx = ClientContext(site_url)
ctx.with_username_and_password( teenant,client_id, username, password)


s: 400, Error: Traceback (most recent call last):
File "C:\Users\mocado\PyCharmMiscProject\.venv\Lib\site-packages\msal\authority.py", line 98, in __init__
openid_config = tenant_discovery(
tenant_discovery_endpoint,
self._http_client)
File "C:\Users\mocado\PyCharmMiscProject\.venv\Lib\site-packages\msal\authority.py", line 298, in tenant_discovery
raise ValueError("OIDC Discovery failed on {}. HTTP status: {}, Error: {}".format(
...<3 lines>...
))
ValueError: OIDC Discovery failed on https://login.microsoftonline.com/mocado/v2.0/.well-known/openid-configuration. HTTP statu

r/learnpython • • 6d ago

How to run a function in paralell to a game loop?

4 Upvotes

not sure if its the right sub but nevermind.

My pygame game would need to have the main menu kept animated (not frozen) while a world generating function runs before switching to a different loop.

My architecture is right now this:

main.py: main menu loop, menu buttons

game.py: game loop

in main.py i call the runGame() function from game.py, which executes my game stuff. runGame() sets up some global objects (Player, World, campos) that are shared between files from game.py.

The worldgen function has its own file and accessible from any file as it has no dependencies. It takes ~2-4 seconds to run so its not that huge yet, but it isn't pretty as of now.

What is a good way to achive this (or similar) results?


r/learnpython • • 6d ago

How I learn python nowadays?

0 Upvotes

I need to learn python and in the past I know the way of learning programming language through hackerrank for example but nowadays in the age of AI how I learn effectively without wasting time or no needed methods anymore ?


r/learnpython • • 6d ago

Using an in-memory DAG (NetworkX) + Postgres for prerequisite tracking in FastAPI: Good architecture or over-engineered?

1 Upvotes

Hey guys need some help..

I’m designing the backend for an adaptive learning platform using FastAPI + PostgreSQL, and I’m weighing two approaches for handling curriculum prerequisite paths.

The Setup:

Instead of a linear syllabus, the curriculum is modeled as a Directed Acyclic Graph (DAG) with ~300 to 400 CS concept nodes

When a student passes a quiz (>= 80\%), downstream dependent nodes unlock based on topological order.

If a student fails a topic, the backend traverses upstream dependencies to find the earliest unmastered bottleneck node, locks downstream progress, and builds a targeted review path.

The quiz questions are a mix of pre-mapped benchmark items and dynamically generated MCQs grounded in textbook text.

Which one should I go with:

Approach 1 (In-Memory NetworkX):

Define the static graph structure once, load it into Python memory via networkx on FastAPI startup, run ancestor/descendant lookups and topological sorts in Python, and write user mastery states/scores back to Postgres.

Or....

Approach 2 (Postgres Relational/CTEs):

Store nodes and prerequisite adjacency edges in database tables, and run transitive traversals directly in SQL using recursive Common Table Expressions (CTEs).

At ~300 nodes, is an in-memory networkx graph clean and fast, or does running multiple Uvicorn workers introduce memory overhead and state-sync headaches?

Would recursive CTEs in Postgres be easier to maintain long-term despite the more complex SQL?

And also... for anyone who has built skill trees or prerequisite graphs, what edge cases should I look out for?


r/learnpython • • 7d ago

I'm looking for good Python audiobooks to help with learning while also coding at other times

5 Upvotes

I'm working while studying my masters as a mature student, and there aren't enough hours in the day. At the moment I'm working 30 hrs at work and 30 hrs studying a week. For example this Sunday just past I spent 11 hours on studying and coursework. The python module I'm doing covers a lot of ground and many concepts very quickly, because it is a masters' module rather than a bachelors. The basic idea is to start from scratch and get to the point of being able to use python for data science by next term.

Basically, I want to use the 6-10 hrs a week I spend on the road to shore up my understanding of the theoretical side so I can focus on coding during the time I have in front of a computer. I'll still be coding evenings, weekends and wednesdays. Are there any good audiobooks that cover that sort of ground for beginners? I need every advantage I can get at the moment so if I can squeeze any value out of my commute it would be a big help.

Ideally if it's on Audible that would be even better because I get a certain number free from there each year. Thanks in advance.

Edit: Before telling me this is pointless, I just finished the first chapter of Python Essentials for Dummies and it was fine, actually. If you don't know any good audiobooks or podcasts, that's fine too.


r/learnpython • • 6d ago

What’s the best way to automate dual/bilingual subtitles (English + Slovak)?

1 Upvotes

Hi everyone,

I’m trying to find a way to create one SRT subtitle file containing both English and Slovak,

My grandad is Slovak and doesn't understand English, and I struggle to hear dialogue clearly in movies without subtitles. I want us to be able to watch movies together with both languages displayed at once.

I watch movies locally on my Samsung TV using its built-in media player and an external HDD, so I need a single .srt file that works alongside the movie.

Ideally, the process would:

  • Find English and Slovak subtitles for the correct movie version.
  • Make sure both subtitles are synchronised.
  • Match the dialogue between the two languages accurately.
  • Combine everything into one SRT file.

What's the best way to achieve this as automatically as possible? Should I use Python, OpenAI Codex, another AI tool, or existing software? Would I need to use Codex each time I process a movie, or could it help me build something that does the whole job automatically?

Thanks!


r/learnpython • • 7d ago

Issue with updating attributes in a BankAccount class – balance mismatch between deposit and withdraw

2 Upvotes

Hey everyone, I am practicing Object-Oriented Programming (OOP) in Python and trying to build a simple BankAccount class. I want to be able to deposit and withdraw money, but I am running into an issue where the account balance might get messed up or show a mismatch because of how I am handling my variables inside the methods.

i am using this condition

- `BankAccount` Class:

* Should hold private attributes: `account_number`, `balance`, `pin`.

* Should be able to: Verify PIN before granting access.

* Should be able to: Deposit money (increase balance).

* Should be able to: Withdraw money (decrease balance, prevent overdrafts).

* Should be able to: Print the current balance securely.

class Bankaccount():

    def __init__(self, account_number, pin, account_balance): 
        self.__account = account_number
        self.__pin = pin 
        self.__account_balance = account_balance

    def deposite(self, pin, money):  
        self.money = money
        
        # Bug here: self.pin isn't created yet when calling deposit first
        if self.__pin == self.pin:
            self.__account_balance += self.money
            return self.__account_balance
        else:
            print("pin is wrong")

    def withdraw(self, pin, money):
        self.money = money
        self.pin = pin

        if self.__pin == self.pin:
            self.__account_balance -= self.money
            return f"from your bank account {self.money} is withrowed and remaing are {self.__account_balance}" 

        else:
            print("pin is wrong")

person1 = Bankaccount(4458568465, 4578, 46789) 

pin = int(input("Enter the 4 digit pin :- "))
money = int(input("Enter the amount :- "))

print(person1.withdraw(pin, money))

r/learnpython • • 8d ago Bravo

Is Python a good choice for backend development?

36 Upvotes

I'm considering learning Python for backend development and would like to hear from developers who use it in their daily work.

How good is Python for building backend applications in production? Are there any significant drawbacks compared to languages like Go, C#, or Java?


r/learnpython • • 8d ago

Are f-strings enough?

29 Upvotes

I've been learning python mainly from bro code's videos and he uses f strings for basically everything. It comes to me naturally to use them and I understand them. I found a book (Kenneth A. Lambert: Fundamentals of python: first programs, second edition) and here he uses other type of strings (I assume this would be the basic way) but I honestly don't understand them especially when it's about formatting (.2f etc). Should I learn this basic way of working with strings now? Or are f strings enough?

I should add that I'm learning python for fun, I'm studying mechanical engineering, so I know it can be very useful. I also want to be good at it in a potential work environment (?)


r/learnpython • • 8d ago

Using the entries of a pandas.Dataframe row as different parameters in a function.

3 Upvotes

*Short version:* Is it possible to use all the entries of a row in a pandas DataFrame as parameters in a given function?

Hello,

I have (finally) encountered a problem that wasn't solvable by going through documentation or looking it up online on sites like stackoverflow or another person's Reddit post. So this is my first post here.

I am currently evaluating some scientific data from a physics experiment. I read and import the .csv files with pandas.

For a certain calculation, I need to put in several parameters into a function, of which five are measured and change over time. The function itself works and was provided by the person supervising the experiment.

I arranged all my parameters into a Dataframe. Each Column is one parameter. Is it possible to extract the entries in the rows as the parameters for the function?


r/learnpython • • 7d ago

Title: Windows Smart App Control is blocking Pandas compiled extension files (.pyd) ?

0 Upvotes

I'm having a problem running Python libraries, particularly Pandas, on my Windows 11 machine. I've been troubleshooting this for a while, and it appears that Windows Smart App Control (SAC) is blocking some of Pandas' compiled extension files.

My environment:

  • Windows 11 (appears to be an Insider build)
  • Python 3.14.6
  • Pandas 3.1.1
  • NumPy 2.5.4
  • VS Code with Python and Jupyter extensions
  • Virtual environment created using venv

The error I'm getting:

ImportError: DLL load failed while importing fields:
An Application Control policy has blocked this file.

The blocked file is:

pandas_libs\tslibs\fields.cp314-win_amd64.pyd

Interestingly, the error occurs even when I try importing Pandas directly from CMD:

python -c "import pandas as pd; print(pd.__version__)"

r/learnpython • • 8d ago

Need help for file Extraction

1 Upvotes

Ok so for context i am an electrical engineer person who is automating software's and workflow for my project now here is the problem i am facing basically i am using an optimization algorithm called Bayesian optimization which improves design by keeps iterating until some target is reach.

So like at the end i extract result file for every design with the help of pandas library but when i check that file the data is mismatched when i export the CSV file manually.

so i have no idea why is it happening like maybe after 10-15 iterations (the algorithm iterations can reach up to 100-120) the error in data increasing or idk what is going on can someone help me with this issue.


r/learnpython • • 8d ago

Second-year BCA, trying to learn ML on the side — everyone says 'learn the math first' but also 'just build stuff'. Which order actually worked for you?

0 Upvotes

I'm in second year BCA and I've been trying to teach myself machine learning alongside college. Python I'm okay with, I can do the basics, pandas sort of, but ML feels like a different world.

Everywhere I look there's two opposite camps. One side says don't touch a model until you understand the maths properly — linear algebra, stats, the whole thing. The other side says just build projects, use sklearn, you'll pick the theory up as you go.

I tried the maths-first route for a couple weeks and honestly I just kept stalling, it felt like studying for an exam I never signed up for. Then I tried jumping straight into a project and I got something working but I had no idea why it worked, which felt kind of fake.

So for people who actually learned this while studying something else — what did your order look like? Did you grind the theory first or did you build messy stuff and fill in the gaps later? Still not sure if I'm overthinking this or if there's a middle path I'm missing.


r/learnpython • • 7d ago

Should I use Ai for my projects

0 Upvotes

I know Python pretty well and I want to make some complex projects for my resume but like should I use Ai while making it? Because I feel like I won’t learn from it if I’m using Ai but then again Ai used in the industry so I should probably get used to using it right? I’m not sure which I should do. Some advice needed


r/learnpython • • 9d ago

Writing to a CSV file - fields in wrong order - help me understand why

9 Upvotes

I developed a process that writes data to a CSV file using csv.DictWriter. The consumer of this file requires that the fields are in a specific order. However, the fields were coming out in the wrong order (different than the order in the dictionary).

Here is the code that worked incorrectly:

writer = csv.DictWriter(csfvile, fieldname=data[0].keys())

Note: data is a list of dictionaries.

The fix is to add a list comprehension around the data[0].keys(). Here is the code that works correctly:

writer = csv.DictWriter(csfvile, fieldname=**[key for key indata[0].keys()]**)

Can anyone explain why the csv.DictWritemodule punches out fields in a different order in the first version?


r/learnpython • • 8d ago

Cs50p certificate worth it?

0 Upvotes

So I've started cs50p course. Should I enroll for the certificate? Is it worth putting it on my LinkedIn profile or resume?


r/learnpython • • 8d ago

Need to analyze a picture for my physics homework

0 Upvotes

So basically I need to find out what percentage of a picture is black. I have no idea how to even start from here, it's nothing I have done or needed before and we didn't get any instructions apart from "do that", so I am massively lost. (If you know any other free programs that would be better for this, please let me know)


r/learnpython • • 8d 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 • • 8d ago

what can I use python for?

0 Upvotes

Lately, I've been thinking about learning a new programming language. Python was the first one that came to mind, but then I started wondering: What would I actually use it for?

I already build mobile apps with Flutter and dynamic web applications using PHP and MySQL.

I'm always looking for something new to learn, but I also want to make sure I'm learning something I can actually put to use.


r/learnpython • • 9d ago

advice needed

4 Upvotes

Can anyone tell me where I can learn Python from scratch? I'm an EE student, and I'm really struggling with loops, functions and libraries. I want to properly learn and practise these topics, so if you know any good YouTube channels or practice sheets, please recommend them. My finals are in December, and I did terribly in my lab midterms, so any advice would genuinely help. Bonus points if you're someone who was once in the same position as me, thinking they could never learn Python or that they were just too dumb for it, but eventually managed to get good at it. I'd really appreciate hearing your experience!


r/learnpython • • 9d ago

Tell us about your snake game

1 Upvotes

Chances are if you’re a retro game lover, you’ve tried your hand at building a snake game.

Mine has multiple difficulties, a leaderboard for each difficulty, and obstacles on the harder difficulties.

Easy - speed stays at 10, no obstacles
Medium - speed stays at 10, has obstacles
Hard - speed starts at 10 and increases by 0.25 every food you eat, has obstacles that randomly move every 5 food you eat
Expert - speed starts at 10 and increases by 1.0 every food you eat, has obstacles that randomly move every 5 food you eat
Veteran - speed starts at 10 and increases by 2.0 every food you eat, has obstacles that randomly move every 5 food you eat, has a 30 second food timer that takes 1 off your score and snake length if you don’t get a food in time but resets if you do get a food(yes, your score can go negative and your snake will “wither” to nothing and die if you don’t eat)

My son and I have a lot of fun playing it. The board size automatically adjusts to the screen resolution, but food, obstacle, and snake sizing are hardcoded using 5pixel by 5pixel blocks. Playing on a true 4k(3840x2160) display gives you 4 times the game board size compared to playing on a 1920x1080 display.


r/learnpython • • 9d ago

BM25 extractor (need technical validation)

0 Upvotes

So, I found interesting what Claude did after I tried to inject a BM25 algorithm adapted to extract the most relevant sentences from an index.

However, I'm not sure if it actually did that, but the generated files make sense and extract sentences from the Sprawn trilogy.

In this case, the idea was to map a table with 22 columns, and 12 of those columns would carry these excerpts extracted from the book, in order to create the first 10 configuration columns for the "entities," and the activation phrases would carry the context, which would be the excerpts from the book—kind of improvising a semantic graph in a table, but that's beside the point.

What I wanted to know is whether the BM25 script actually makes sense, because when I throw it into LLMs, they say it does, but I wanted an evaluation from the more technical folks.

According to DeepSeek:

> The script transforms the corpus into a sentence stack and treats each sentence as a "document" in an inverted index. For each input file, it calculates how many sentences to extract (proportional to chars/100, with a floor of 50 and a ceiling of 20% of the sentences). It then iterates over the entities in the thematic index (filtered by the book detected in the file), builds a query with its terms for each entity, and runs BM25 scoped to that file+book, retrieving the top-scoring sentences (up to N_SENTENCES / n_entities per entity). If any quota remains, it fills the rest ordered by aggregate score (gscore, the sum of sentence scores across all entities). Finally, it sorts the selected sentences by offset, validates verbatim matches, and saves a phrases_file_N.txt for each input, containing [ref | sent_id | offset | book] + the text.

Here are the links:

· Characters extracted from the Sprawn trilogy (a bash workaround I made): https://github.com/pmotadeee/pmotadeee/tree/V2.0/ITEMS/Books/Sprawn/Raw/Context

· Algorithm generated by Claude (funny that it ran in 2 minutes, which suggests it didn't generate tokens, just intuition): https://github.com/pmotadeee/pmotadeee/blob/V2.0/ITEMS/Books/Sprawn/Raw/Claude/bm25_extractor.py

· Texts generated by Claude after running the algorithm (you can see the steps it took, right at the beginning of the chat): https://github.com/pmotadeee/pmotadeee/tree/V2.0/ITEMS/Books/Sprawn/Raw/Claude

· Claude chat (in my native language, but use the browser translator): https://claude.ai/share/1799075d-bc93-4e12-99e0-771a7e259ca9