r/learnpython 17h ago

What python debugging techniques do you think every developer should know ?

Upvotes

I am trying to improve my debugging skills and I was curious about what techniques experienced python developers rely on the most.

Are there any techniques or tools that you found really useful when you started working on bigger projects?


r/learnpython 8m ago

How should a Local-First AI Memory Engine scale between SQLite and Volatile RAM?

Upvotes

I am developing devmemory, an engine designed to reconstruct a project’s history by converting Git logs and code ASTs into a navigable knowledge graph. Currently, the system performs search indexing and graph traversal.

I would like suggestions on whether I should store data on disk using SQLite and then process it. Please help me find the best solution.


r/learnpython 1h ago

CPython internals deep dive:dis,==vs is and immutable vs mutable

Upvotes

Started with the dis module disassembled a simple function and saw how Python compiles source into bytecode instructions operating on a stack: LOAD_CONST (push a literal), STORE_FAST (pop and assign to a local var), BINARY_OP (pop two values, apply the operator, push the result). Noticed newer Python versions fuse common opcode pairs (e.g. LOAD_FAST_LOAD_FAST) for speed small but visible evidence of ongoing interpreter optimization work.

Then worked through == vs is confirmed with id() that two lists with identical contents are still separate objects (is → False, == → True), while b = a makes both names point to the same object.

Finished on mutable vs immutable, and specifically why it matters when passing objects into functions. Key realization: calling a function doesn't substitute the argument into the function body it creates an independent local name that starts out pointing at the same object. n += 1 on an int creates a new object and only moves the local name; lst.append(x) mutates the shared object in place, so the caller sees the change too. Proved both cases with id() before/after.

Small, foundational stuff, but building the intuition from scratch with real code has been way more effective than just reading definitions.


r/learnpython 7h ago

Help with viewing XML animations from a defunct mobile game

Upvotes

I am looking for help to be able to view animations of a defunct game called "Dragon Blaze", a side-scrolling rpg developed by GAMEVIL/FLINT. I am helping a small community from players with the intent of archiving the game. I have access to all texture and xml files, some xml files being encoded and others not, but I am no coder and I could use help with viewing those animations.

This game used 2d-skeletal-puppets using a program called 3D Max 2012 by Autodesk via a custom game engine. The XML files have coordinates and instructions to piece the broken spritesheets together, and animate them back together; often starting with the following lines: "<SR1_ANIMA version="1.2" generator="MAX 2012">".

Information about how to use these XML files were very hard to come by, so I had to rely on google's search AI for directions of how to crack it. I apologize in advance if any of those instructions are wrong.

So far the AI suggested the following methods:

  1. Convert the XML files into Json so it can be read by modern tools like Spine/Dragonbones.
  2. Build a web previewer using HTML5/JavaScript. Using Phaser or PixiJS.

We could really use some help and/or guidance about what to do, it would make archiving this game much easier.


r/learnpython 3h ago

Learning python for someone with experience

Upvotes

Hello everyone! I am with 8+ years of professional experience with .NET web backend development but lately I want to try something new and python seems interesting to me. Can you suggest some learning materials where I can skip the basic programming concepts and focus on getting used to the syntax, learning python patterns and architectures, learn some useful frameworks etc? I prefer some video lectures rather to documentations. I would appreciate your suggestions and thank you in advance!


r/learnpython 19h ago

Why isn't this code block working?

Upvotes

Hey everybody,

I'm new to programming with Python and following along with a Udemy Course. I'm now learning about lists and need to write a "Who will pay the bill"-like game.

It works like this: you have a pseudorandom number generator and a list of friends. Each time, the number generator generates a number between the given indices of the list. If the randomly generated number is equal to a specific index of that list, it should print out the person who must pay the bill by using an if-elif statement.

I've been using what I learned from the past lessons. This is what the code looks like (and yeah, I know, I messed up pretty badly, even though I have already found a solution):

import random

friends = ["Alice", "Bob", "Charlie", "David", "Emanuel"]

random_select = random.randint(0, 4)

if random_select == friends[0]:                  
    print("Alice has to pay the bill. ")
elif random_select == friends[1]:
    print("Bob has to pay the bill. ")
elif random_select == friends[2]:
    print("Charlie has to pay the bill. ")
elif random_select == friends[3]:
    print("David has to pay the bill. ")
elif random_select == friends[4]:
    print("Emanuel has to pay the bill. ")

But I couldn't really figure out why the code won't work.


r/learnpython 1d ago

How do you get better at actually THINKING in code, not just learning syntax?

Upvotes

I have been learning python for a month now but I don't see any improvements. I tend to forget the concepts of python and can't solve problems logically. I don't think it's just me who is dealing with these problems, I need tips please.


r/learnpython 17h ago

What is the best FREE website to practice python?

Upvotes

I have exams in roughly 1.5 years and want to get my python basis cracked down completely so i will do well in my programming paper

Sites like codewars and codingbat have been recommended? Can anyone else vouch if they are good and if there are any others that are better?


r/learnpython 17h ago

AtributeError clarification

Upvotes

SOLVED

Hello, I'm currently learning regular expressions and I've entered the first part of the code into the interactive shell as instructed and got the listed AttributeError. Not seeing what I did wrong I copy/pasted the code from the book and it worked as intended and I can't tell why or how because both blocks feel and smell the same but yield different results.

I've tried looking for some information on StackOverflow, but as far as I can see mo is defined in the 3rd line and I don't get why my attempt gets and error while the other doesn't.

If I didn't miss something really stupid, how would you deal with this if you'd be hit by it writing your own code independently?

I'm working in IDLE Shell and the code is from automatetheboringstuff Chapter 9 for more context

import re
phone_re = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d-\d\d\d\d)')
mo = phone_re.search('My number is 415-555-4242.')
mo.group(1)
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    mo.group(1)
AttributeError: 'NoneType' object has no attribute 'group'

import re
phone_re = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
mo = phone_re.search('My number is 415-555-4242.')
mo.group(1)
'415'

r/learnpython 17h ago

Trying to retrive voice to text in Python Vosk in transcription_output

Upvotes

I'm a total noobie with Python having only used DNS before. For over a year I could dictate into my W11 laptop and the text would appear on screen. There is no apparent Save or Save As so I would just X out and open that transcript file in MS Notepad and find that text. But, today the new text I dictated in doesn't appear. I'm presented with a window when I open that output file with - Open (that doesn't save the old text) or Save All or Save Changes so I chose Save All. I then dictated in a proper name in that command line screen and saw that name on screen and X'd out and that output file reflected a file created 2 minutes ago and this time I chose Save Changes but it didn't have that proper name anywhere in that out put file. I'm unsure what I'm doing wrong nor what I need to do to fix this so it saves newly dictated words? Thank you.


r/learnpython 8h ago

Finished Day 1 of learning python and tried to create black jack, ive had an error somewhere, not a syntax error, i dont assume this code is very good its a massive slump of if and elif, how can i fix this?

Upvotes
import random
for House_Card in range(1):
    House_Card = random.randint(1, 11)
    print("House Card:", House_Card)
for House_Card2 in range(1):
    House_Card2 = random.randint(1, 11)
for Player_Card in range(1):
    Player_Card = random.randint(1, 11)
    print("Player Card:", Player_Card)
for Player_Card2 in range(1):
    Player_Card2 = random.randint(1, 11)
    print("Player Card 2:", Player_Card2)
print("Your current cards are:", Player_Card + Player_Card2)
Player_Turn1 = input("Do you want to hit or stay? (h/s): ")
if Player_Turn1 == "h" or Player_Turn1 == "H" or Player_Turn1 == "hit" or Player_Turn1 == "Hit":
    Player_Card3 = random.randint(1, 11)
    Player_CardT = Player_Card + Player_Card2 + Player_Card3
    print("Player Card 3:", Player_Card3)
    print("Your total score is:", Player_CardT)
if Player_Turn1 == "s" or Player_Turn1 == "S" or Player_Turn1 == "stay" or Player_Turn1 == "Stay":
    Player_CardT = Player_Card + Player_Card2
    print("Your total score is:", Player_CardT)
if Player_CardT > 21:
    print("You busted! Your total score is:", Player_CardT)
if Player_CardT == 21:
    print("You got blackjack! You Win!")
if Player_CardT < 21:
    print('Your total cards are:', Player_CardT)
    Player_Turn2 = input("Do you want to hit or stay? (h/s): ")
    if Player_Turn2 == "h" or Player_Turn2 == "H" or Player_Turn2 == "hit" or Player_Turn2 == "Hit":
        Player_Card4 = random.randint(1, 11)
        Player_CardT2 = Player_CardT + Player_Card4
        if Player_CardT2 == 21:
            print("You got blackjack! You Win!")
        elif Player_CardT2 < 21:
            Player_Turn3 = input("Do you want to hit or stay? (h/s): ")
            if Player_Turn3 == "h" or Player_Turn3 == "H" or Player_Turn3 == "hit" or Player_Turn3 == "Hit":
                Player_Card5 = random.randint(1, 11)
            print("Player Card 5:", Player_Card5)
            Player_CardT3 = Player_CardT2 + Player_Card5
            print("Your total cards are:", Player_CardT3)
            if Player_CardT3 > 21:
                print("You busted! Your total score is:", Player_CardT3)
            if Player_Turn3 == "s" or Player_Turn3 == "S" or Player_Turn3 == "stay" or Player_Turn3 == "Stay":
                print("Your total cards are:", Player_CardT2)
        print("Card:", Player_Card4)
        print("Your total cards are:", Player_CardT2)
    if Player_CardT2 > 21:
        print("You busted! Your total score is:", Player_CardT2)
    if Player_Turn2 == "s" or Player_Turn2 == "S" or Player_Turn2 == "stay" or Player_Turn2 == "Stay":
        print('House card 2 is:', House_Card2)
        print('House total cards are:', House_Card + House_Card2)
        House_CardT = House_Card + House_Card2
        if House_CardT > 21:
            print("House busted! You Win!")
        if House_CardT == 21:
            print("House got blackjack! You Lose!")
        if House_CardT < 21 and House_CardT < 17:
            House_Card3 = random.randint(1, 11)
            House_CardT2 = House_CardT + House_Card3
            print("House Card 3:", House_Card3)
            print("House total cards are:", House_CardT2)
            if House_CardT2 > 21:
                print("House busted! You Win!")
            if House_CardT2 == 21:
                print("House got blackjack! You Lose!")
            elif House_CardT2 < 21 and House_CardT2 < Player_CardT2 or House_CardT2 < Player_CardT3:
                print("Player Cards Value Higher, You Win!")from ast import If
import random
for House_Card in range(1):
    House_Card = random.randint(1, 11)
    print("House Card:", House_Card)
for House_Card2 in range(1):
    House_Card2 = random.randint(1, 11)
for Player_Card in range(1):
    Player_Card = random.randint(1, 11)
    print("Player Card:", Player_Card)
for Player_Card2 in range(1):
    Player_Card2 = random.randint(1, 11)
    print("Player Card 2:", Player_Card2)
print("Your current cards are:", Player_Card + Player_Card2)
Player_Turn1 = input("Do you want to hit or stay? (h/s): ")
if Player_Turn1 == "h" or Player_Turn1 == "H" or Player_Turn1 == "hit" or Player_Turn1 == "Hit":
    Player_Card3 = random.randint(1, 11)
    Player_CardT = Player_Card + Player_Card2 + Player_Card3
    print("Player Card 3:", Player_Card3)
    print("Your total score is:", Player_CardT)
if Player_Turn1 == "s" or Player_Turn1 == "S" or Player_Turn1 == "stay" or Player_Turn1 == "Stay":
    Player_CardT = Player_Card + Player_Card2
    print("Your total score is:", Player_CardT)
if Player_CardT > 21:
    print("You busted! Your total score is:", Player_CardT)
if Player_CardT == 21:
    print("You got blackjack! You Win!")
if Player_CardT < 21:
    print('Your total cards are:', Player_CardT)
    Player_Turn2 = input("Do you want to hit or stay? (h/s): ")
    if Player_Turn2 == "h" or Player_Turn2 == "H" or Player_Turn2 == "hit" or Player_Turn2 == "Hit":
        Player_Card4 = random.randint(1, 11)
        Player_CardT2 = Player_CardT + Player_Card4
        if Player_CardT2 == 21:
            print("You got blackjack! You Win!")
        elif Player_CardT2 < 21:
            Player_Turn3 = input("Do you want to hit or stay? (h/s): ")
            if Player_Turn3 == "h" or Player_Turn3 == "H" or Player_Turn3 == "hit" or Player_Turn3 == "Hit":
                Player_Card5 = random.randint(1, 11)
            print("Player Card 5:", Player_Card5)
            Player_CardT3 = Player_CardT2 + Player_Card5
            print("Your total cards are:", Player_CardT3)
            if Player_CardT3 > 21:
                print("You busted! Your total score is:", Player_CardT3)
            if Player_Turn3 == "s" or Player_Turn3 == "S" or Player_Turn3 == "stay" or Player_Turn3 == "Stay":
                print("Your total cards are:", Player_CardT2)
        print("Card:", Player_Card4)
        print("Your total cards are:", Player_CardT2)
    if Player_CardT2 > 21:
        print("You busted! Your total score is:", Player_CardT2)
    if Player_Turn2 == "s" or Player_Turn2 == "S" or Player_Turn2 == "stay" or Player_Turn2 == "Stay":
        print('House card 2 is:', House_Card2)
        print('House total cards are:', House_Card + House_Card2)
        House_CardT = House_Card + House_Card2
        if House_CardT > 21:
            print("House busted! You Win!")
        if House_CardT == 21:
            print("House got blackjack! You Lose!")
        if House_CardT < 21 and House_CardT < 17:
            House_Card3 = random.randint(1, 11)
            House_CardT2 = House_CardT + House_Card3
            print("House Card 3:", House_Card3)
            print("House total cards are:", House_CardT2)
            if House_CardT2 > 21:
                print("House busted! You Win!")
            if House_CardT2 == 21:
                print("House got blackjack! You Lose!")
            elif House_CardT2 < 21 and House_CardT2 < Player_CardT2 or House_CardT2 < Player_CardT3:
                print("Player Cards Value Higher, You Win!")

r/learnpython 18h ago

Advice for computer science student

Upvotes

Hi, in the next month I'll start a master degree in computer science, curriculum AI. Firstly I have to say that I'm not a completely newby with programming or alghoritms. During this three years of college (computer science) I did some projects, but not with python, that I had to study for my thesis project in 1 month. Now that I'm about to start this master degree I want to learn better how python works and how can I use differents libraries that uses AI.
I read on the sub posts where someone recommends the Python Crash Course book, by Eric Matthes, but I don't know if it's the source that I need for my situation.

Don't know what to do, I have like this month to learn something to not starts lessons like a completely "ignorant".


r/learnpython 18h ago

How to pass one returned output to another functions..

Upvotes
def cal(A , B):
    add = A + B
    return add

def substract(c):
    sub = add - c
    return sub

addition = cal(3,5)

substraction = substract(4)
print(addition)

print(substraction)

In this code How can I pass function cal()return value add in function substract()

r/learnpython 1d ago

Beginner Projects

Upvotes

I am new to python and currently I am taking a class for it, I haven't been in it too long but I just want some advice. What beginner projects would you guys recommend I do to really grasp an understanding outside of class?


r/learnpython 21h ago

Quick fix for ⁠st_folium⁠ state desync when drawing new boundaries in Streamlit

Upvotes

Hit a bug using ⁠st_folium⁠ with Streamlit: drawing a new polygon triggered a re-render before Streamlit updated the spatial state, leaving downstream metrics stuck on the old site.

Fixing it required checking ⁠last_active_drawing⁠ at the top of the execution loop and forcing a rerun before running analytics:

# Intercept new shape before running downstream calculations
if map_data and map_data.get("last_active_drawing"):
drawing = map_data["last_active_drawing"]
if drawing.get("geometry"):
new_geom = shape(drawing["geometry"])

if not new_geom.equals(st.session_state.get("drawn_geom")):
st.session_state["drawn_geom"] = new_geom
st.session_state["site_area_m2"] = calculate_area(new_geom)
st.rerun() # Forces a clean state sync

This keeps multi-tab dashboards 100% in sync with live map edits.


r/learnpython 13h ago

python online course

Upvotes

name one best python course on internet


r/learnpython 22h ago

Runtime errors query

Upvotes

I have a question. Like when we have a program that takes input, so when the program reaches the input line, it stops and asks for input, right? So then AFTER the input is entered, if the compiler runs into a bug, it stops and throws an error message. How can I stop this? Like how can I make the issues appear beforehand so that I can fix them before running? Are there any settings or tools for this problem?

Please tell me.


r/learnpython 1d ago

How can I use python in finance

Upvotes

I work in finance/accounting and am looking to start using Python more in my day to day. Most of my work is in Excel / Power BI — reporting, cash flow forecasting, KPIs, cleaning up data, etc.

I’m technical enough to understand what I’m trying to accomplish, but not a programmer. Similar to Power BI, I’d probably rely heavily on AI to help write the actual code.

For those in finance / accounting / FP&A, what are some practical ways you’re using Python? Where does it actually save you time vs. Excel, Power Query, Power BI, etc?

Also curious what you’d recommend learning first if the goal is to be dangerous enough with Python + AI, not become a developer.


r/learnpython 14h ago

Hi, I want to learn Python. Where should I start if I have no experience?

Upvotes

How can I learn to code in Python if I have no experience? I tried to do something myself, but where should I start? I tried to use Pycharm, but I have a lot of errors in the code, and I don’t really know English (I’m writing this post through a translator). I want to start making websites in Python, but I’m 14 and have no experience. Where should I start? My text is not ai I'm just a foreigner without knowledge of English


r/learnpython 1d ago

Starting a deep dive into CPython internals logging progress here, feedback welcome

Upvotes

r/learnpython 22h ago

code review request: server for allowing multiple connections

Upvotes

it seemed to work when i tested it but i did it myself and just stuck in things that i read abt and thought pertained to the project i was trying to create, it is supposed to allow multiple people to stay connected at the same time but im wondering if there's some logic error anywhere that i might not have picked on, or if the code is genuinely robust enough to accommodate multiple connections. i didn't need to use any threading at all in the end, which i found a bit strange, and also im a beginner in python so i was hoping if people could point out some potential issues, thanks!

import socket
import select


s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("localhost", 80))
s.listen()

def send_response(sock, message):
    """Sends an encoded response."""
    sock.sendall(message.encode("ISO-8859-1"))


def handle_packets(queue_dictionary):
    """Performs certain actions based on packet."""
    for soc in queue_dictionary:
        if not queue_dictionary[soc]:
            continue
        #take the first item from the queue
        packet = queue_dictionary[soc].pop(0)
        #send specific responses based on the type of data sent
        if packet == b"Hello\r\n\r\n":
            send_response(soc, "Message received successfully. Hiiii!!!!\r\n\r\n")
        elif packet == b"Ignore\r\n\r\n":
            send_response(soc, "Message received successfully. Hey, don't leave me hanging...\r\n\r\n")
        elif packet == b"Hug\r\n\r\n":
            send_response(soc, "Message received successfully. *Hugs back*\r\n\r\n")
        elif packet == b"Slap\r\n\r\n":
            send_response(soc, "Message received successfully. OW! That hurt!\r\n\r\n")
        elif packet == b"Goodbye\r\n\r\n":
            send_response(soc, "Message received successfully. Goodbye!!! Do come back again!! :)\r\n\r\n")
        else:
            send_response(soc, "Message received successfully.\r\n\r\n")

#create a list of connected sockets, satrting wtih listening soccket so accept
#doesn't block

#dictionary with buffer per socket and also list which was initially queue
read_set = [s]

buffer_dict = {}
queue_dict = {}

while True:
    ready_to_read, _, _ = select.select(read_set, [], [])
    print("Creating a list of sockets currently sending data...")
    #for all sockets that are ready to read
    for sock in ready_to_read:
        #if the socket is a listener
        if sock == read_set[0]:
            #accept a new connection
            new_conn = s.accept()
            print("Accepting connection...")
            new_socket = new_conn[0]
            #initialise buffer and queue for new socket
            buffer_dict[new_socket] = b""
            queue_dict[new_socket] = []
            print("Adding socket to buffer and queue dictionaries...")
            #add the new socket to the set
            read_set.append(new_socket)
            print("read_set: " + str(read_set))
            print("Adding socket to read_set...")
            packet = "empty"
            continue
        else:
            #recieves data until full packet
            while True:
                data = sock.recv(4096)
                print("Receiving data...")
                if not data:
                   print("Connection closed.")
                   break
                buffer_dict[sock] += data
                if b"\r\n\r\n" in buffer_dict[sock]:
                    delimiter_index = buffer_dict[sock].find(b"\r\n\r\n")
                    packet = buffer_dict[sock][:delimiter_index+4]
                    buffer_dict[sock] = buffer_dict[sock][delimiter_index+4:]
                    break
            if packet:
                queue_dict[sock].append(packet)
                print("Adding a packet to the queue...")
            else:
                x = input("No packet returned.")


    #run packet handler code based on nature of packet for socket
    if packet != "empty":
        print("Sending response...")
        handle_packets(queue_dict)
        print("Response should send now.")

new_socket.close()
s.close()

r/learnpython 23h ago

How to actually create logic?

Upvotes

So hi I am new in this sub reddit and have been learning python basics on FreeCodeCamp for weeks.

So I have noticed that I can do workshops and labs but I tend to forget many syntax and have to search on the internet repeatedly.

So my average lab projects often look like 7

60% written by me and the rest 40% are written by AI or with the help of the Internet forums.

My problem that I have identified is I don't think use logic in the code or just don't remember syntax, operators, elements, conditional statements and string methods or don't find the satisfactory answer on the internet.

I want to try to write at least 80% of the code myself without being dependent that much on AI and the internet because I am learning it for *Cyber Security*


r/learnpython 1d ago

Python practice problem.

Upvotes

‎Hi everyone, I'm new to python and I'm building a project to hone my skill, and I came to a halt in this part. When I do if user_input == 'q':, it works and breaks the loop just fine, since i dont wanna make the exit just single letter so even if the user input words like 'quit' 'q' or 'QUIT' it will exit the loop, I tried a different approach like doing user_input == ['q', 'quit']: and another approach where i declared a variable first exit_word = ['q', 'quit'] then

‎user_input == exit_word: none of this breaks the loop it just goes back to the input prompt heres my work below:

import random

user = 0

computer = 0

options = ["rock" , "paper", "scissors"]

while True:

user_input = input("Rock/Paper/Scissors and Q for Quit: ").lower()

if user_input == 'q'

break

if user_input not in options:

continue

random_num = random.randint(0, 2)

computer_pick = options[random_num]

print('Computer picked', computer_pick + ".")

if user_input == 'rock' and computer_pick == 'scissors':

print('You won!')

user += 1

elif user_input == 'paper' and computer_pick == 'rock':

print('You won!')

user += 1

elif user_input == 'scissors' and computer_pick == 'paper':

print('You won!')

user += 1

else:

print('You lost!')

computer += 1

print("The user won", user, "times")

print("The computer won", computer, "times")

print('Goodbye!')


r/learnpython 1d ago

Ask Anything Monday - Weekly Thread

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

Regarding question

Upvotes

from datetime import *

year = int(input("Enter the Year:- "))

month = int(input("Enter The Month:- "))

day = int(input("Enter The Day:- "))

x = date(year,month,day)

validity = int(input('Enter the days of validity')) expiry = x + validity print(expiry)

I want to add days in this but i don't know how ,I even tried to adding manually but gives me error unsupported oparand + in datetie.datetime class something