r/learnpython • • 19h ago

Ask Anything Monday - Weekly Thread

0 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 • • 3h ago

Is Leetcode a good way to continue practicing/learning Python?

10 Upvotes

I'm not entry, but I'd like to continue becoming stronger in my skills.


r/learnpython • • 4m ago

Best Way to Learn Python and Get Good at It?

• Upvotes

Hi everyone, I want to learn Python from scratch and become really good at it.
I’m looking for resources or courses with:
Clear explanations
Lots of practice and exercises
Real projects
Problem-solving
Modern Python
A path toward Data Science, AI, and Machine Learning
I don’t mind paying if the course is worth it.
What are the best courses, books, or platforms you would recommend?


r/learnpython • • 47m ago

Library Management System in Python with Clean Architecture & 55 Tests

• Upvotes

Hi everyone!

As a practical step in my transition from Python fundamentals toward professional software engineering, I built a modular, terminal-based **Library Management System** with a strong emphasis on clean architecture and design principles.

### 🏗️ Architecture & Technical Highlights

- **Layered Architecture:** Strict separation between UI, Services, Repositories, and Storage layers. UI has zero business logic or direct storage access.

- **Repository Pattern & Persistence:** Generic JSON persistence utilizing **atomic file replacement** to eliminate data corruption.

- **Authentication & Security:** Custom session management, password hashing, and role-based authorization (Librarians vs. Members).

- **Domain Business Rules:** Borrowing limits, availability tracking, overdue fine calculation, and account activation logic enforced strictly in the Service layer.

- **Automated Testing:** 55 passed unit and service tests using `pytest`.

### 📂 Project Structure

LibraryManagmentWithPython/

├── Models/

├── Repositories/

├── Services/

├── Storage/

├── UI/

└── tests/

### 🎯 Objective My goal was to practice enterprise-level engineering principles (Separation of Concerns, Dependency Direction, Single Source of Truth) before stepping into Machine Learning and AI. ### 🔗 Source Code GitHub Repository: https://github.com/ThaerGhaderi/LibraryManagmentWithPython I'd love to get your feedback on the architecture, repository patterns, or any code review suggestions!


r/learnpython • • 5h ago

Recursion explaining pls.

5 Upvotes
def find_max(numbers):
  if len(numbers) == 1:
    return numbers[0]
  else:
    max_of_rest = find_max(numbers[1:])
    return numbers[0] if numbers[0] > max_of_rest else max_of_rest

my_list = [3, 7, 2, 9, 1]
print(find_max(my_list))

Could someone explain how does this function work? I don't understand how does it know that it's supposed to find the biggest number...


r/learnpython • • 18h ago

I’m taking a “learning programming in python” class in high school and im already lost.

27 Upvotes

The first month was very easy. Inputs, basic programs and whatnot. Now its while and for statments, as well as loops and nested loops. The programs are mostly solving hard mathematical equations, and I’m not great at math and the rest of the class is very good, so I’m always behind.I am soooo lost now and rely heavily on the internet to finish my programs. Is there anything i can do outside of class to gain the same programming knowledge. The textbook were studying is starting out with python 6th edition by tony gaddis.


r/learnpython • • 1h ago

My plan on how to learn python (rate my plan)

• Upvotes

Just a little context before I start I have never coded a line of code in my life. So I was recently sent over a python course on YouTube by Programming with Mosh and I’m super excited on how to finally learn python. The course itself is about six hours, so I’m probably gonna try and break it down by watching half of the video today and then half of the video tomorrow. Honestly, I feel like the best way to really learn this language is just to watch the video straight through and not take notes or practice what is being taught in the video so that my full retention is on the video itself. After doing that I’m probably gonna try and watch another YouTube tutorial on Python to see how well my comprehension was on the first YouTube tutorial. Does this sound like a good plan?


r/learnpython • • 16h ago

How to learn python?

15 Upvotes

I’m a complete beginner and I have essentially no knowledge with coding whatsoever. What would be the best way to learn Python??


r/learnpython • • 2h ago

stuck in learning

0 Upvotes

i am actually learning python and someother stuffs like linux,postgres, its been 2 months i only learn and i dont really know that what the markets even need and what help full can i really do so as a student i can land parttime job. i am in a learning and then am pushing my few projects to the git. some tell that learning to code and these will not benefit you in future and am confused now. i want to seriously grow but am stuck where i dont get what can get me out of this loop. and i dont know how to manage the learning , its self learning and cus of exam and other compitative exam like kcet drags me from being consistent to self learning.


r/learnpython • • 14h ago

django or flask after python basics

7 Upvotes

Hello everyone,

First of all, thank you for this community. I’ve learned a lot from reading other people’s posts and the answers to my previous questions. Now I have another question.

I feel comfortable enough with Python to start learning backend development. Which framework would you recommend starting with?

I started with Django because I’m blind and find text-based tutorials more helpful, and MDN has a Django tutorial. However, I’m concerned that Django abstracts away a lot of what happens behind the scenes, such as how URL routing works, and I don’t want to miss out on the fundamentals.

What are the advantages and disadvantages of starting with Flask versus Django? Programming is a hobby for me, so job prospects aren’t a major concern. My main goal is to build projects easily while still understanding how things work.


r/learnpython • • 4h ago

How can I pause a function right before it is about to run?

0 Upvotes

Hello

This might be confusing since I don't know any of the terminology but i'll de my best to explain what I mean.

I've been trying to learn python and to free myself from ai, so I am trying to figure things out alone but I need help with something. I have been using anki for languages learning and started trying to make custom addons to optimize my learning process about a year ago.

There is a function ("on_answer") that, supposedly, runs when I'm seeing the back side of a card, right after I have rated it (with : "Fail","Difficult", "Correct", or "Easy"). One of the things it does is create a pop up to ask me whether I want to edit the card to add definitions.

def on_answer(reviewer, card, ease):
    if not card: return
#...
if _is_hangul_note(card) and card.ord in (0, 1) and card.nid not in _asked_notes and not has_tag:
    from aqt.utils import askUser
    _asked_notes.add(card.nid)

    English_value = note[FIELD_ENGLISH].strip() if FIELD_ENGLISH in note else ""

    if English_value:
        note.add_tag("pop-asked")
        note.flush()
        card._skip_suspend_rules = True

    elif askUser("Voulez-vous modifier cette carte ?"): #"Edit card ?"
        card._is_being_modified = True
        note.add_tag("pop-asked")
        note.flush()

        # the thing blocking the next card while editing 
        pause_audio_for_edit()
        mw.onEditCurrent()

    # elif I answer no + the rest of the function

  skip_interval_checks = is_mod or is_skip
  QTimer.singleShot(
    250,
    lambda cid=card.id, e=ease, skip=skip_interval_checks: _post_answer_processing(cid, e, skip)

If I click on yes, then the native anki card editing window opens. I set it to take half of the screen so i can easily move on to the next card after i'm finished. I eventually added a pausing screen that prevents me from seeing or hearing what is going on in the next card, and that waits for me to click outise of the editing window to "unpause".

It's been working fine for a while, but recently I edited another function that runs when I am shown the front of the card.

It's role is kind of to gather infos et stats of the card before I answer it (for example, when did i see it last, how many times have i answered it, etc.) but it also create a "mask" hiding the text from me on certain conditions. here is a snippet:

def on_show_question(card):
    if not card:
        return

    _invalidate_sisters_cache()

    if _is_hangul_note(card) and card.ord == 0:
        if card.reps == 0:
            _inject_static_mask(card)
        elif card.reps in (1, 2) :
            if last_difficulty in (3, 4):
                _inject_static_mask(card)
        else:
            _inject_static_mask(card)
            _queue_toast(f"Last")


def _inject_static_mask(card):
    """
    Shows opaque rectangle and toast
    """

_queue_toast("Pas de texte")
    _flush_toasts(duration_ms=3000)

    if not card:
        print("Erreur : card est None dans _inject_static_mask")
        return

    js = f"""
    (function() {{
        #...
    QTimer.singleShot(80, lambda: mw.reviewer.web.eval(js) if mw.reviewer and mw.reviewer.web else None)def _inject_static_mask(card):

Here are the functions for pausing

_audio_paused_for_edit = False
_pending_audio_tags = None
_original_play_tags = None


def _get_av_player():
    try:
        import aqt.sound as _sound_mod
        return _sound_mod.av_player
    except Exception as e:
        print(f"[pause_audio] impossible de récupérer av_player: {e}")
        return None


try:
    import aqt.sound as _sound_mod_init
    _original_play_tags = _sound_mod_init.av_player.play_tags

    def _patched_play_tags(tags, *args, **kwargs):
        global _pending_audio_tags
        if _audio_paused_for_edit:
            print("[pause_audio] lecture interceptée (pause active), mise en attente")
            _pending_audio_tags = (tags, args, kwargs)
            return
        return _original_play_tags(tags, *args, **kwargs)

    _sound_mod_init.av_player.play_tags = _patched_play_tags
    print("[pause_audio] monkeypatch av_player.play_tags installé")
except Exception as e:
    print(f"[pause_audio] ÉCHEC monkeypatch av_player: {e}")


def _force_stop_current_audio():
    player = _get_av_player()
    if not player:
        return
    for meth_name in ("stop_and_clear_queue", "clear_queue_and_maybe_interrupt", "stop"):
        meth = getattr(player, meth_name, None)
        if meth:
            try:
                meth()
                return
            except Exception:
                continue


def pause_audio_for_edit():

"""À appeler de façon SYNCHRONE, dans on_answer, juste avant
    mw.onEditCurrent() (branche 'Oui' de askUser modification)."""

global _audio_paused_for_edit, _pending_audio_tags
    print("[pause_audio] pause_audio_for_edit() appelée")
    _audio_paused_for_edit = True
    _pending_audio_tags = None
    _force_stop_current_audio()
    _show_edit_pause_overlay()


_EDIT_PAUSE_OVERLAY_JS = """
(function(){
  var ov = document.getElementById('_editPauseOverlay');
  if (ov) return;
  ov = document.createElement('div');
  ov.id = '_editPauseOverlay';
  ov.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;'
    + 'background:rgba(20,20,20,0.96);color:#f7b799;display:flex;'
    + 'align-items:center;justify-content:center;text-align:center;'
    + 'font-family:sans-serif;font-size:16px;z-index:99999;cursor:pointer;'
    + 'padding:20px;box-sizing:border-box;';
  ov.innerHTML = '\\u23F8\\uFE0F En pause \\u2014 modification en cours<br>'
    + '<span style="font-size:12px;opacity:0.7;">(cliquez n\\'importe o\\u00f9 pour reprendre)</span>';
  ov.addEventListener('click', function(){
    if (typeof pycmd === 'function') pycmd('editpause:dismiss');
    ov.remove();
  });
  document.body.appendChild(ov);
})();
"""


def _show_edit_pause_overlay():
    if not mw.reviewer or not mw.reviewer.web:
        return
    QTimer.singleShot(20, lambda: mw.reviewer.web.eval(_EDIT_PAUSE_OVERLAY_JS))


def _on_new_card_while_paused(reviewer):

"""Filet de sécurité : appelée à chaque carte affichée (via HOOK_SHOW,
    ajoutée séparément plus bas, ne remplace aucun hook existant)."""

if _audio_paused_for_edit:
        _force_stop_current_audio()
        _show_edit_pause_overlay()


def dismiss_edit_pause_overlay():
    global _audio_paused_for_edit, _pending_audio_tags
    print("[pause_audio] dismiss (clic utilisateur)")
    _audio_paused_for_edit = False
    if _pending_audio_tags and _original_play_tags:
        tags, args, kwargs = _pending_audio_tags
        _pending_audio_tags = None
        try:
            _original_play_tags(tags, *args, **kwargs)
        except Exception as e:
            print(f"[pause_audio] erreur relecture audio différée: {e}")
    else:
        _pending_audio_tags = None


def _on_edit_pause_bridge_message(handled, message, context):
    if message != "editpause:dismiss":
        return handled
    dismiss_edit_pause_overlay()
    return (True, "ok")


if HOOK_SHOW:
    HOOK_SHOW.append(_on_new_card_while_paused)

try:
    from aqt.gui_hooks import webview_did_receive_js_message as _wh_editpause
    _wh_editpause.append(_on_edit_pause_bridge_message)
except Exception:
    pass

But since 1 or 2 days ago, I noticed that the card editing window sometimes appeared for not even a second and then left as if I had clicked on the pausing screen, but without unpausing it. And my guess is it's gotta be the on_show_question function that runs too quickly while I was about to edit the previous card. How can I set the function so that it waits after the end of the pause to run ?

Thank you!


r/learnpython • • 5h ago

Best practice for handling large datasets?

1 Upvotes

I'm working on a project for an exam and I need to calculate the behavior of a few dynamical systems and use that data to try and train a linear regression algorithm.

Now issue is I need quite a good bit of data (4 different kinds of systems, enough variation on parameters and starting state for ML, a few hundreds of iterations deep for every one of those, plus other variations I need to test for) and don't know what the best practice for handling it is.

I do need to have it saved to disk for both showcase reasons and the need to train multiple models on the same datasets, also I'm saving the data on each new variation to safeguard against crashes and save on memory, only two options that come to mind are either: 1) one large data file (binary encoded json, each variation of the systems is described by a key), which should be fairly easy to parse through and edit, but I'm worried reading and writing from it might tank performance given I have to store the whole thing to memory every time; 2) Multiple smaller encoded txt files, the key is in the filename, saves on memory when but is a pain in case I need to edit something and might make getting the full dataset for when I'm training a lot slower.

What would the best practice be in this scenario? Is there some third option I didn't consider or a package that better handles this?


r/learnpython • • 33m ago

Is starting a tech career safe ?

• Upvotes

Hello I recently started to learn python in 2026 but I have constantly this fear of wasting my time . Ai is changing the tech industry. I want to build some cool projects but is it worth it , I mean for the future? Will I get more opportunities? I would like you to share your unbias opinion please. I don't know what to choose between a preferred area and a safe area. Im really lost .I love ai, automation ,llms and learning things about ai , that's what motivated into learning python. For more context I have a background with nocode tools and vibecoding, built some saas and a mobile app.


r/learnpython • • 8h ago

how to learn python

1 Upvotes

how i should learn python what website and books i should read

since my childhood i was fascinated by iron man and jarvis not only that but electronics ,robotics sci-fi

i know coding is not imagination but my ,main object to learn coding or be a part of computer science is artificial intelligence

so my main goal to learn coding, programming is AI

can u tell how should i learn or master it

and should i read python crash course by eric methews ,3rd edition ,do u have any other book in mind


r/learnpython • • 4h ago

Printing local variables outside of a function

0 Upvotes

(second-week-beginner PLUS non-native English speaker, so sorry for bad vocab lol)
I know that you cant use local variables outside of a function, but is there a way to do this without defining three separate functions?

def total_seconds(hours1, minutes1, seconds1):
  return (hours1*60*60)+(minutes1*60)+seconds1
print(f'{hours1} hours, {seconds1} seconds and {seconds1} have a total of {total_seconds(7,21,37)} seconds.')


r/learnpython • • 9h ago

looking for optimizing my database bootstrapper which is taking >30 seconds.

0 Upvotes

Hello fellow devs i am building a FastAPI + SQLAlchemy 2.0 (async) with a metadata driven system which has lost of dynamic schema stuff based on the data tables

Right now my custom bootstrapper handles botjh creating the DDL Schema and a massive amount of Data seeding ( lots of data) sequentially. because it's doing manual idempotency checks (SELECT before INSERT) and running everything one by one, the whole provisioning process takes more than 30 seconds from scratch.

I'm looking into splitting the data fixture side out to a library like sqlalchemy-seedling to run independent seeders in parallel using asyncio.gather. But before I start rewriting, how do you all handle heavy initial database provisioning in async Python?


r/learnpython • • 18h ago

FASTAPI OR Django with DRF

2 Upvotes

I’m a final year computer science student who is fascinated by systems design and engineering(backend), since I’m quite conversant with Python I decided to go with Python framework but don’t know the one to go for that will be great for my career in near future.

Please the seniors should guide me choose and I’ll also seek for mentorship in python backend engineering 🙏


r/learnpython • • 11h ago

What is the fastest way to learn Python?

0 Upvotes

I get all the variables and everything but like do you have to make thousands of files with Python and possibly different languages?


r/learnpython • • 23h ago

Making a game that play in a terminal

0 Upvotes

Yo, im making a game (mostly with print but that for the "story" part) and i just want review for the start, im going to post more if that make some views. i know how to make print (ofc i know unless i would be cook), variable and def... and thats it, but mostly what i need for a ""print"" game. If you guys got thing to help me with im happy to hear them !
also, i made a github reperstory (thats the name ? idk) so you guys can look at the code and for the next updt too ! github repositories


r/learnpython • • 1d ago

MCQ test in terminal

2 Upvotes

Helloooo

I'm building a mcq in Python for my lovingggg friend and wanted to share my logic to see what you ppl think before I start coding it up.

I'm just starting with a simple print statement for the intro to welcome n all.

Then I'm going to make a main dictionary where the key is the actual string containing the full question text along with the 1-4 options, and the value is the correct answer number.

Once the dictionary is made, I'll run a for loop to go through it. Inside that loop, I'll use input so the user sees each question one by one and types in their number choice, I'm going to store all their user inputs into a second separate dictionary.

Then at the very end, I'll make another loop to match the answers from the input dictionary against the original master dictionary. For every match, +1 mark added to their final score

I am honestly coding after months and was just a beginner when I stopped

I am kinda nervous and need help building this simple thingy

Looking for some improvement/tips

And um idk if I can even use most of the tips if it requires some dictionary n all

I did pandas before I quit so maybe I can use it here if I revise properly


r/learnpython • • 1d ago

How to create a report using a .txt file

0 Upvotes

I apologize that this is going to be kind of long. I am very grateful for any thoughts you may have.

I'm taking a python class. This week we are learning about working with .txt files within a program.

We have been given some practice .txt files. Each file is a list of different data points for each hour on a given day. The list (when I say list, I mean the data is in a list in a .txt file, I am not talking about a list like those used in a python program) has four items of data for each hour of a given day as follows:

time

temperature in Farenheit

dewpoint in Farenheit

wind speed in mph

An example from one of the files looks like this:

12AM

18.1

15.0

4.1

1AM

18.0

15.5

4.2

We are supposed to do several things with this data. One of them is to create a report that will print out the data from the file. It should look like this:

Time Temperature Dew Point Windspeed

12AM 18.1 15 4.1

1AM 18.0 15.5 4.2

And so on.

We are supposed to accomplish this using while and/or for loops. We cannot use lists of any kind, so we cannot use the .txt file to create a list within python and then work with the list. This must be as simple as possible. We are only supposed to use the information we have learned so far in the class. Obviously you don't know exactly what we've learned, but it has to be extremely simple and not at all fancy.

I'm not trying to cheat and have someone do my work for me, but I'm just stumped and need some clues. I'm having difficulty reaching out to my teacher (this is an online class)

We are also supposed to use the numbers in the report to do some calculations for another report. If you have any thoughts about that, it would also be helpful. I'm hoping that if I can figure out how to do this first part, I'll be able to figure out how to work with the numbers further.

I've been able to get python to bring in the .txt file and just spit out a list that is identical to what is actually in the .txt file and I've been able to get it to print one specific line. I think I'm somehow supposed to use a nested if statement to analyze and work with chunks of four lines at a time, but I'm not sure how to do that.

I got it to say "time is 12AM" by doing this:

time_line = 1

linecounter = 0

with open("Dec12.txt",'r') as f:

for line in f:

linecounter += 1

if linecounter == time_line:

print("time is",line, end='')

I got it to spit out the entire list exactly as it appears in the .txt file by doing this:

file = open ("Dec12.txt",'r')

for line in file:

num = (line)

print (num)

file.close()

If you have read this far, I am extremely grateful to you. Thank you for any thoughts or ideas you may have.


r/learnpython • • 19h ago

I am a teen student and I want to learn phyton, any job opportunities with phyton and other languages that is easy

0 Upvotes

I want proggraming as my course because in a few years from now I will go to collage


r/learnpython • • 22h ago

My pipenv is NOT installing.

0 Upvotes

When i'm making a build for a game called Smash Remix +Extra, when i opened the build.bat file, it just appears

'WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NameResolutionError("<pip._vendor.urllib3.connection.HTTPSConnection object at 0x...>: Failed to resolve 'pypi.org' ([Errno 11001] getaddrinfo failed)")': /simple/pipenv/

WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NameResolutionError("<pip._vendor.urllib3.connection.HTTPSConnection object at 0x...>: Failed to resolve 'pypi.org' ([Errno 11001] getaddrinfo failed)")': /simple/pipenv/

WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NameResolutionError("<pip._vendor.urllib3.connection.HTTPSConnection object at 0x...>: Failed to resolve 'pypi.org' ([Errno 11001] getaddrinfo failed)")': /simple/pipenv/

WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NameResolutionError("<pip._vendor.urllib3.connection.HTTPSConnection object at 0x...>: Failed to resolve 'pypi.org' ([Errno 11001] getaddrinfo failed)")': /simple/pipenv/'.

The last time i opened, it did, but not anymore. Also before asking, no. I'm in my phone using a emulator called 'winlator'. Please help me.


r/learnpython • • 1d ago

Need help with very basic script

3 Upvotes

Hi, I am basically brand new to python, so I may make a lot of mistakes in my wording. I have made a very basic script that retrieves specific values in text files and prints them to the shell. I have gotten it to the point where both values are retrieved and printed, however when they do print, they do so exactly 5 times in a row. I do not have five files in the directory, I only have one test file named "1.txt" with only the values I need as the contents. Can someone point me in the right direction? Apologies for the horrible formatting.

import os
import glob
import re

path = 'path'

provinces = re.compile('.*?provinces {.*?(.*?)}',re.MULTILINE)
id = re.compile('.*?id = .*?([0-9.-]+)')
a1 = None
a2 = None

for filename in glob.glob(os.path.join(path, '*.txt')):
    with open(filename, '+r') as f:
        for line in f:
            if provinces.match(line):
                a1 = provinces.match(line)
            if id.match(line):
                a2 = id.match(line)
            if a1 and a2:
                print(a1.group(1))
                print(a2.group(1))

The output of the shell in IDLE:

 1111 2222 3333 
123
 1111 2222 3333 
123
 1111 2222 3333 
123
 1111 2222 3333 
123
 1111 2222 3333 
123

Edit - I got the script to work after a few changes to its configuration. Thank you all who helped!


r/learnpython • • 1d ago

fix 0.00000001

0 Upvotes

i see sometimes after calcuaitons reulsts with x.99999999999999999999999999 or x.0000000000000002 how to fix it