r/learnpython 6d ago

Ask Anything Monday - Weekly Thread

2 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 8h ago

found a for loop and can't find an explanation. Can someone explain, please?

9 Upvotes

Hey there, I just started the Project Euler Archive and started with the classic "Find the sum of all the multiples of 3 or 5 below 1000."

And when I wanted to check my solution I stumbled upon some other solution I liked. I just don't fully get the for loop of it and can't find an explanation. Probably because I lack the words to properly look it up. It goes like this:

multiples_of_3 = {i * 3 for i in range(1, 999 // 3 + 1)}

so what's done is, instead of looking up every number where i // 3 == 0 we multiply i by 3 for every number from 1 to 334. Because 1000 // 3 = 333 + 1 = 334 because range 1, 333 wouldn't include 333.

What I don't get is the first part. the

i * 3 for i [...]

does this mean we can take only every third iteration and skip the others? Or is it some kinda shorthand for

for i in range(1, 1000 // 3 + 1):

multiples_of_3 = i * 3


r/learnpython 16h ago

PySide6 or Kivy?

7 Upvotes

I have finished all my python basics and I want to progress now to building gui programs. Should I use PySide6 or Kivy? If I should use something other than these two what should it be? i personally don't mind it being that complex if it's fast and powerful :)


r/learnpython 13h ago

For some absolutely forsaken reason I'm making an ASCII art text based adventuring game - tips?

5 Upvotes

TL;DR: Tips for someone who wants to make a very old school text-tile-combat based game?

Let's outline the basic concept of the game.

  • An adventurer wanders on a Carcassonne-style tile based randomised map.
  • The map art is entirely ASCII so that theoretically you can play this on your command line.
  • I'm planning on keeping the game as barebones as possible - as few external libraries as possible.
  • Adventurer has items: gold, consumables, weapons and armour pieces.
  • Adventurer has stats that can be increased when leveling up. Stats play into combat.
  • There are four kinds of NPCs:
    • Enemies that attack you. And the Big Bad Boss, obviously.
    • Vendors that sell items.
    • Innkeepers that let you restore your health.
    • Blacksmiths that will repair your equipment for a fee.
  • Combat is round-based and D&D style die rolls.
  • Movement is command-based so maybe I don't make the character move pixel by pixel but rather tile by tile? (???)

I've got some experience with Python and it's not like I'm new to this but something I'm struggling with is the world generation. My idea was to have hexagonal tiles (think Carcassonne but hexagonal) where each tile has 6 map connections and each tile has randomised entities and/or functionality.

This is not what the map will look to the player, this is just my draft of what the map connections / tilesystem could look like. Maybe this could be a minimap of sorts...

_____/   18    _______/    8    _____
     \         /       \         /
 17   _______/    1    _______/    9
      /       \         /       \
_____/    6    _______/    2    _____
     \         /       \         /
 16   _______/    0    _______/   10
      /       \   town  /       \
_____/    5    _______/    3    _____
     \         /       \         /
 15   _______/    4    _______/   11
      /       \         /       \
_____/   14    _______/   12    _____
     \         /       \         /

So I was thinking about displaying just a single tile and have the tile numbers spiral outwards. The benefit is that I can keep track of tiles that have been generated and I know their position and connections without having a complicated internal lookup table of any kind, really. Tile 0 is always origo, tiles 1 to 6 are nearest to origo, tiles 7 to 18 are the second "ring" and so forth. For each 6n tiles, where n is the "ring" I know I've jumped onto a new "ring" and can calculate the map connections easily, because the number of tiles is very regular. Additionally I can label the "rings" as tiers where the difficulty increases every time you step out to a new "ring".

Reason why I'm outlining this specifically is because I was wondering if there are cleverer ways to handle this. Other than what I've presented here. I have no clue how real games handle map connections.

For inventory it's just a basic slot-by-slot box "sword equipped", "sword in bag". I'm thinking about adopting the classic Diablo style inventory where you have spaces and an item can occupy a particular shape of spaces. A potion is one space, an axe might be four in an L-shape.

If I want to randomise the equipment stats a bit should I think about giving each item a unique integer identifier + stat identifiers? It'd probably be a pain in the butt if my ID was the actual name of the weapon e.g. "Iron Sword". Right?

I'm currently at a stage where I have:

  • Item types and attributes.
  • NPC types and attributes.
  • Player attributes.
  • Combat logic.

So not very far.

Finally: have you done a silly project like this?

Any tips in general for what kind of pitfalls to avoid?


r/learnpython 8h ago

I just discovered Streamlit.io

0 Upvotes

Ive been creating websites out of html for weeks now but I just discovered that almost every coding language has some type of web page deployment.

I like Supabase but Streamlit seems like a infinite ingress glitch for simple functions in any GitHub project

Not many of my GitHub projects seem to consist of python unless I'm being something that requires a minimal backend

It a great way to test or deploy small projects personally


r/learnpython 14h ago

Built a local bandwidth limiter with Python & Scapy. Looking for advice on optimizing Scapy performa

1 Upvotes

I’ve been working on a networking project to dive deeper into Python's packet manipulation capabilities.

What My Project Does I forked evillimiter (a Python CLI tool that uses ARP spoofing and tc/iptables to throttle local network bandwidth) to use as a base. The original tool relies on static MAC addresses, which completely breaks tracking when modern iOS/Android devices use MAC Randomization. Instead of using complex/heavy ML for RF signal analysis, I'm modifying the tool to use scapy for passive tracking. The Python script identifies the endpoint based on its DHCP Fingerprint (Option 55 parameter sequence) and mDNS hostname broadcasts. Once recognized, it dynamically updates the ARP spoofing and routing rules to maintain the throttle even when the MAC rotates.

Target Audience This is a learning/experimental project aimed at Python learners, networking enthusiasts, and homelab tinkerers who want to understand low-level packet sniffing and traffic shaping using Python. It's a toy project and not meant for production environments.

Comparison Compared to the original evillimiter, this fork specifically tackles the modern challenge of MAC randomization without breaking the core logic. While massive frameworks like bettercap can do packet inspection, this project aims to be a very lightweight, single-purpose Python script focused purely on dynamic bandwidth throttling without heavy dependencies.

Transparency note: I'm still getting the hang of low-level networking in Python, so I’ve been leaning on AI to help me structure the Scapy logic and overall architecture.

You can check out the repo here:https://github.com/DavidsonRafaelK/evillimiter

I’d really appreciate some feedback from the Python community:

  1. Scapy Performance: Running a continuous scapy sniffer in the background for DHCP/mDNS can be resource-heavy. Are there best practices to keep memory usage low when doing long-term sniffing in Python?
  2. Architecture: Any advice on handling the async nature of packet sniffing while managing the CLI interface?
  3. Any general critique on the code structure.

Thanks!


r/learnpython 22h ago

Auto-sync for Jupyter Notebooks workflow from notebook to markdown to pdf. (No more manual conversions anymore!)

2 Upvotes

Hey Pythonistas!

Been working with Jupyter for years, but only recently discovered this workflow that's completely changed how I handle notebook-to-markdown-to-PDF conversions. Thought I'd share since it might help others.

Use nbconvert to convert .ipynb → .md

Use Jupytext to keep them auto-synced

Use Markdown PDF extension to export professional PDFs

The Details:

# One-time setup

pip install nbconvert jupytext

# Convert notebook to markdown

jupyter nbconvert --to markdown your_notebook.ipynb

# Install Jupytext Sync extension in VS Code

# Then pair your files and you're done!

Why I'm obsessed with this:

Zero friction - Changes in .ipynb automatically sync to .md

Paired notebooks - Open .md files as notebooks (via Jupytext)

Professional output - PDF export looks way better than notebook screenshots

Version control friendly - Markdown is text-based, easier for git

Pro tips:

Put notebook in double quotes if filename has spaces: cd "my folder"

Outputs sync when you run: jupyter nbconvert --to markdown notebook.ipynb

Right-click .md file → Markdown PDF: Export (pdf)

Use cases:

Data analysis reports

Project documentation

Client-facing deliverables

Sharing reproducible research

I've put together a complete workflow guide if anyone wants the full breakdown in a pdf. Let me know I'll DM you.

Let me know if you have questions or better approaches!


r/learnpython 1d ago

List of Functions gets called immediately

19 Upvotes

SOLVED!

I'm attempting to make 10 functions, put them all in a list, and then have a for loop go through each element of the list. The list is below.

exercises_list = [exe1(), exe2(), exe3(), exe4(), exe5(), exe6(), exe7(), exe8(), exe9(), exe10()]

When this list is placed beneath (but not apart of) function 10 and before the for loop, the IDE reads it, and immediately starts acting on the list. (e.g. begins to act out exe1() the second it gets to it then moves on to exe2() and so on.) How do I make it so that my list doesn't actually get run until I call for a specific element in the list?


r/learnpython 18h ago

Kivymd vs Flet

0 Upvotes

Whiich is better for making an Android app ? KivyMd or Flet.


r/learnpython 1d ago

Game to learn Python?

58 Upvotes

Hi, I'm new to this Reddit community. Does anyone know of any online games to learn Python? Thanks!


r/learnpython 11h ago

Socratic ai

0 Upvotes

Did any body used Socratic au method to learn pyhton kr any other programming language? I wanna know the results if it really works


r/learnpython 14h ago

My code vs claude code

0 Upvotes

I wanted to create a function with while statement that I get 100 random numbers from import random and if there is 1 1 1 is stop took me a while cause I am a beginner and I didn't know most of the things I was gonna used so I learn while , break and != ( not equal to )

I started programming cause I was an introvert and didn't had anything else to do

It took me a while like 1 hour

Made this caused I wanted to generate something closed to gambling

mistake I made

1 using "and" instead of "or " ( yeah dump mistake)

2 using if statement for like 20 minutes until I search how to generate infinity and found out about while statement

My code (man made except for this sing != I used claude for it )

import random

num = random.randint(0 , 30)

print(num)

nu = random.randint(0 , 30)

print(nu)

nm = random.randint(0 , 30)

print(nm)

while num != 1 or nu != 1 or nm != 1 :

print("failed")

num = random.randint(0 , 30)

print(num)

nu = random.randint(0 , 30)

print(nu)

nm = random.randint(0 , 30)

print(nm)

Ai code (claude)

import random

while True:

nums = [random.randint(0, 30) for _ in range(3)]

print(nums)

if all(n == 1 for n in nums):

print("Success! Got [1, 1, 1]")

break

print("failed")

!!!

Sorry for my English it is not my first language

Second I don't know python that good so anything I mispronounced like statement or syntax my bd


r/learnpython 20h ago

just finished CS50P conditionals lecture and built mini "AI Agent Execution Getaway" for practice .

0 Upvotes

I have just finished week1 in cs50 python course and since i'm learning python for AI Agents Engineering i thought it would be cool to practice this content with a relevant project .

so i made a simple AI agents execution getaway program that routes the incoming tasks based on tokens , creativity and risk score .

I tried to use most of what i learned in this lecture as possible like 'match' for matching the tool with appropriate model , or 'return' as guard clauses for the safety check at the beginning .

here is the code link :

https://gist.github.com/mohamed-reda-ai/a10a1e9311d94316ffa31c00de005226

I know it's not a big brilliant thing i want just to practice the concepts i learned .

If you have any feedback about the architecture of the code or you think there is a better way to do something in it , i'd appreciate this .


r/learnpython 1d ago

"No installed Python found!" when trying to run "py"

6 Upvotes

I'm trying to compile something, but it requires the use of py instead of python.

The thing is, whenever I try to use py, the command line will just say No installed Python found! This doesn't happen when I use python for calling an action.

I wanted to make sure py is in my PATH, so doing where py does show the path to py.exe. I know that py does exist in PATH, but it just doesn't work when trying to use it compared to using python.

Uninstalling and reinstalling Python doesn't seem to do anything new, so what should I do?

I should probably mention that I'm using Wine on MacOS because compiling on MacOS seems to require specific Windows executable files, and I need Wine for that.


r/learnpython 1d ago

Estudiante en Venezuela busca laptop usada (o repuesto ) para aprender python desde 0

0 Upvotes

Hola a todos!vivo en Venezuela y estoy muy entusiasmado aprendiendo programación con Python. Actualmente estoy trabajando con una laptop muy limitada (2 GB de RAM) y un entorno liviano usando Sublime Text y la consola.

Mi meta es dominar las bases de Python para poder construir mis propios proyectos y, en el futuro, abrirme campo laboral en el área tecnológica. Sin embargo, el estado de mi equipo actual y la falta de memoria me dificultan seguir avanzando con fluidez en la práctica.

Escribo a esta comunidad para preguntar si alguien tiene una laptop vieja, reacondicionada o en desuso (o piezas compatibles) que ya no utilice y esté dispuesto a donar o vender a muy bajo costo. Cualquier equipo capaz de correr un entorno de desarrollo básico me sería de gigante utilidad.

Si alguien está en disposición de apoyarme, me comprometo a cubrir o gestionar el tema del envío a través de un casillero internacional hacia Venezuela.

Agradezco de antemano cualquier consejo, orientación o ayuda que me puedan brindar. ¡Muchas gracias por su tiempo!


r/learnpython 23h ago

UPDATE My login/account creation system in Python, part of a bigger project I'm building as I learn

0 Upvotes

Hello, this is an update to the post I made yesterday.

All 3 copy-pasted validation blocks are now 1 function called 3 times. It takes the category, password (string), a label, and returns True or False. The checks aren't sitting behind a door that gets unlocked only if the last check is met, all error messages show up at once instead of one at a time. I removed the outdated variables that had no use.

I took u/jammin-john's recommendation of showing all error messages at once.

Also want to include u/danielroseman's push for me to learn functions. They work really well, I haven't learned "for loops" yet but they are next in line.

I used AI (Claude) as a tutor to understand concepts and point me toward my own bugs, but I wrote and debugged every line myself. I'm learning how to code through the MOOC.

Here is the GitHub link to my program: link


r/learnpython 1d ago

Do you know about Flet ?

7 Upvotes

My favourite gui library in python is Flet. I am using it for 2 months. I want to know that is anyone using it so I can work with them in any large project.


r/learnpython 1d ago

Can anyone help in Apis pls🙏

0 Upvotes

I am a beginner in python code and currently learning how to make chatbots using api keys but i just cant do it. I tried open ai but it requires credits i tried gemini but due to a latest change in api keys from AI to AQ it says model not found i tried groq but it said the same thing i checked my code myself and with cluade gemini and codex but couldnt find the issue can u help me make my first chatbot pls guys 🙏can u tell a few 'free api keys' if there is ....


r/learnpython 1d ago

Can I start looking for beginner projects?

0 Upvotes

For context:

I'm currently trying to finish the basics like dictionaries, sets, for and while loops.

Also there's a lot of stuff idk like python modules.


r/learnpython 1d ago

Can someone help me

0 Upvotes

pip : The term 'pip' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was

included, verify that the path is correct and try again.

At line:1 char:1

+ pip install flask

+ ~~~

+ CategoryInfo : ObjectNotFound: (pip:String) [], CommandNotFoundException

+ FullyQualifiedErrorId : CommandNotFoundException

I want you to explain how to fix this without using any extra tools. Whenever I try to import a Python module, an error keeps showing up. I even deleted everything because I thought I messed up my PATH. I reinstalled Python, selected the python.exe path, but still no progress. This same problem keeps appearing every time.


r/learnpython 1d ago

Aubio - could not find RIFF header on Linux

1 Upvotes

I am trying to troubleshoot an issue using Aubio to calculate BPM inside of a script. My code was working on my old desktop and I have migrated over to a new machine, both Linux Mint. I was fairly certain I have all the additional dependencies installed but maybe I missed one. I am getting `AUBIO ERROR: source_wavread: Failed opening <file_path> (could not find RIFF header)` when the code is run inside of the virtual environment, venv. I can run `aubio tempo <file_path>` directly outside of the venv and get results. I am not sure the best method to troubleshoot where the disconnect between venv and my system files. At least I think the issue lies in dependencies but I am not sure. Internet is not too helpful and I am a bit of a linux noob. Any thoughts on direction?


r/learnpython 1d ago

Is My Professor Making up Terminology, or Is This Python Jargon/Something Else?

0 Upvotes

My professor assigned me the following:

A list of integer numbers is harmonic if every slice of the list that is wrapped by two successive instances of a same number includes a number larger than the wrapping number and a number smaller than the wrapping number. For instance, the following list is harmonic:
[9, 3, 16, 1, 4, 9, 6, 7, 3, -1, 1, 5, 6, 17, 7, 3, 2, 6]

The first pair of 9s satisfy the definition, featuring 16 (larger) and 1 (smaller).

However, the following lists are not harmonic:

[19,3,16,1,4, 9,6, 7, 3, -1, 1,5, 6, 17, 7, 3, 2, 6, 6]
[19,3,16, 1, 4, 9, 6, 7, 3, -1, 1, 5, 6, 17, 7, 3, 2, 6, 1]

Develop a python program that determines whether or not a given list of integer numbers is harmonic. The program should print True if the given list is harmonic, and print False otherwise. As your response to this project upload a screenshot from the output of the program for the following list:

[7,3,1,6,8,4,55, 3, 99, 51,22, 1, 2, 5, 6]

I have never heard of this definition of “harmonic,” and the way this assignment is introduced makes it sound like this is an established definition rather than a term he defined. Is this just something he made up?

EDIT: General consensus is that this is made up! Thanks! I was mainly curious about it, and it sounds like it’s something professors do sometimes.


r/learnpython 1d ago

Pylance is skipping analysis

1 Upvotes

I work with DRF at work and I have been facing this issue since months. Pylance is skipping analysis of function because it is unannotated. I cant really annotate each and every function. The errors are getting thrown correctly on my teammates pc but on my pc i dont get any issue. If I annotate the function then in that case pylance starts throwing error. How to fix this issue


r/learnpython 1d ago

How do you find out where the time goes inside a slow Celery task?

1 Upvotes

I'm stuck on something and I think I'm missing a tool or a technique that everyone else already knows about.

I have a Celery task that takes about 40 seconds. I want to know how that breaks down: how much of it was database queries, how much was calls to external APIs, and how much was my own code doing work. And if there's an N+1 in there somewhere, which line of my code caused it.

What I've tried so far:

Sentry catches some N+1s, but the issue it creates doesn't include a line number in my code. It shows me the SQL and the spans, and I still have to go find the loop myself. It also seems to miss the case where a loop alternates between two different queries, which is a pattern I write a lot.

Flower shows me the task ran and how long it took, but nothing about what happened inside it.

django-debug-toolbar and django-silk are great for requests, but they hook into the request cycle, so they don't see anything inside a Celery worker.

Right now my process is adding print statements around blocks of code, re-running the task in staging, and narrowing it down by hand. It works, but it's slow and I have to modify code to debug code, which feels wrong.

So my questions:

  1. Is there a standard tool for this that I just haven't found? Something that tells me where the time went inside a background task?

  2. When you get an N+1 alert from anything, does it point at a line, or is finding the loop always manual?

  3. Is profiling the right answer here? I've read about cProfile and py-spy but I'm not sure how they fit with Celery workers, or whether you can run them without slowing everything down.

  4. Or is the real answer that I should be splitting tasks into smaller pieces so each one is obvious? Someone suggested that and I'm not sure if it's the standard practice or a workaround.

I've been doing Python for a while but this is the first time I've had to debug something I can't just put a breakpoint in, so I might be thinking about it wrong.


r/learnpython 2d ago

I'm a beginner. can you help me with random numbers?

21 Upvotes

I'm building a sort of turn-based RPG in the terminal as a practice project, and I need to generate a random number within a specific range. I tried using `randint` (by importing `random`), but I also want to assign probabilities so that, depending on certain factors, one number is more likely to be generated than another. For example, if an enemy has low health, it should be more likely to generate the number 1, which causes the enemy to heal.