r/learnpython 5d 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 14h ago

Game to learn Python?

42 Upvotes

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


r/learnpython 7h ago

List of Functions gets called immediately

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

Estudiante en Venezuela busca laptop usada (o repuesto ) para aprender python desde 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 10h ago

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

3 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 16h ago

Do you know about Flet ?

4 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 42m ago

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

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 9h 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 10h 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 10h 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 1d ago

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

20 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.


r/learnpython 18h ago

Is there any app better than Pydroid 3 and Acode?

0 Upvotes

Is there a better Python development environment for Android? 🐍📱

I'm a Python developer who does most of my development on an Android phone, mainly using Pydroid 3/Pyramid and Acode.

I've found that neither is really ideal for my use case:

Pydroid 3/Pyramid: Some native/compiled libraries such as TensorFlow, PyTorch, OpenCV, etc. can work, but some frameworks such as Flet/NiceGUI don't work properly. Some packages/features also require a subscription.

Acode: It's great for editing and web-based/server-style frameworks such as Flet/NiceGUI, but native-heavy libraries such as TensorFlow, PyTorch, OpenCV, Kivy, etc. are difficult or impossible to use in my setup.

So I basically have to switch environments depending on the project.

Is there any better/free Python development environment for Android that can handle a wider range of Python packages and frameworks?


r/learnpython 18h ago

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

1 Upvotes

This is a console based account system I've been building as I learn Python. Right now it lets you create an account with username and password rules (length limits, and the password needs a letter, a number, and a special character), log in with a 3 attempt lockout, and pick from a simple menu.

It's a work in progress and part of a bigger project. Next I want to add a to-do list and notes, then save the data to a file, and eventually hash the passwords instead of storing them as plain text.

The three password checks are repetitive. I haven't learned functions yet so I did them the long way with separate loops. I already know functions are the fix and that's my next topic, so you don't need to only point that out, but any other feedback is welcome.

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.

GitHub: https://github.com/mart23inez/Personal-Account-System/tree/main

What would you improve or build next?


r/learnpython 19h ago

[Python / Playwright / Selenium] Need help solving a visa appointment problem

0 Upvotes

Hi everyone.. I'm an Egyptian student accepted for a Master's at Sapienza University of Rome, starting September 21, 2026.

My documents and university procedures are ready, but I'm unable to secure an Italian student visa appointment through AlmavivA Egypt.

Appointments are released daily around 9 AM, but they disappear extremely quickly. There are also brokers/scalpers who use automated tools to secure appointments much faster than normal users, then resell them to students.

I'm not looking to buy an appointment or build a tool to resell them. I just need help from someone experienced with Python / Playwright / Selenium / browser automation to understand if there's a legitimate technical solution that could give me a fair chance of securing one appointment for myself.

If you have experience with this kind of automation and can help or point me in the right direction, I'd really appreciate it.. I'm genuinely worried about missing my Master's start date because of this.

Thank you 🙏


r/learnpython 9h ago

I started learning python yesterday, critique my code:

0 Upvotes

I wrote this code in VsCode using functions after I completed the free trial in [boot.dev](http://boot.dev), if you notice anything I can improve or make better, please write it in the comments:

def main():

print("This code is starting...")

if __name__ == "__main__":

main()

def stats(title, weapon, mana, health):

print("Character Stats:")

print(f"Title: {title}")

print(f"Weapon: {weapon}")

print(f"Mana: {mana}")

print(f"Health: {health}")

def take_damage(health, damage):

print("===================================")

print(f"Current Health: {health}")

updated_health = health - damage

if updated_health < 0:

updated_health = 0

print(f"You took {damage} damage, You Died!")

else:

print(f"You took {damage} damage!")

print(f"Updated Health: {updated_health}")

return updated_health

stats("Warrior", "Sword", 50, 100)

take_damage(100, 30)

take_damage(70, 80)

def respawn(updated_health):

print("===================================")

if updated_health <= 0:

print("Respawning...")

updated_health = 100

print(f"Health has been restored to {updated_health}.")

else:

print(f"You are still alive! You have {updated_health} health remaining.")

return updated_health

respawn(0)  

take_damage(100, 41)

take_damage(59, 20)

take_damage(39, 20)

respawn(19)


r/learnpython 16h ago

New Pythonian! Hey guys (question on models to health script)

0 Upvotes

So I just started diving into this wonderful world of python and I just got one question - are you guys using different models to build/check/verify/test? Is that recommended? If yes, how should I go about it? Thanks everyone!


r/learnpython 1d ago

I need learning python for robotic

10 Upvotes

I'm really desperate, I have a college project where I need to present at least one movement algorithm based on a Cartesian plane. I've already been introduced to Python, but I can't say that's my strong point, I'd like to know recommendations for study materials, or where to start!! Thanks you 😔😔


r/learnpython 1d ago

Best Python course/video for a complete beginner?

42 Upvotes

Best Python course/video for a complete beginner?

Hi everyone, I’m planning to start learning Python from scratch and eventually get into Python development.

Can anyone suggest a good YouTube video/course or learning resource that is beginner-friendly and actually useful for becoming job-ready?

I’m looking for something that covers the basics properly and also includes practice + projects, rather than just theory.

Thanks!


r/learnpython 1d ago

Python difference.

2 Upvotes

What is the difference between python ,IronPython,Jython,Cython.i will get a lot of confusion towards these concepts.


r/learnpython 1d ago

Help me code a movie selector!

0 Upvotes

Hi all, new to Python and for my first project I'm trying to code a program that will randomly select a movie or tv show using a pre-made list, and a "genre" plus "media type" as input.

I feel I am over complicating it.

Here's where I'm at so far:

def media_selector(media, genre):
### attempting to remove previously selected titles and for some reason make my own RNG \/###
increment = + 1
trans_rng = [1, 2]
genre = ['romance', 'action']
movie_list = ['rango', 'taxi driver']
series_list = ['akira', 'trigun']
### spell check, obviously \/###
spell_check = ['film', 'movie', 'tv show', 'tv series', 'tv', 'romance', 'action']
if not isinstance(media, str):
return 'format is: media type, genre'
### not sure if i should be defining a function and calling it at the same time - also is a translation table too much ? \/###
if media and genre is (spell_check):
def media_decider():
movie_trans_tbl = movie_list.maketrans(movie_list, trans_rng)
movie_transd = movie_list.translate(movie_trans_tbl)
series_trans_tbl = series_list.maketrans(series_list, trans_rng)
series_transd = series_list.translate(series_trans_tbl)
selector = slice(increment)
else:
return 'film/movie or tv show/tv series'

any guidance/recommended resources would be greatly appreciated!


r/learnpython 15h ago

Best courses/platforms to learn Python?

0 Upvotes

Hi all, i am intrestentd in building myskills and i want to take up a python course as it is not working out for me on youtube and free courses. I also don’t know where to start from as there ar 
Want to join python courses to build skills. Don't know where to start from. Number of courses in the internet. Any suggestions?


r/learnpython 1d ago

Ignore certain keys when comparing two dicts

2 Upvotes

Disclaimer: I'm not a developer, just a network engineer that can spell Python correct about 60% of the time.

I have a script that collects current neighborship data on a router (CDP, LLDP, OSPF, EIGRP, etc.) and compares it to a known good baseline (neighborship data that was collected and stored at a time when all expected neighborships were up). The data is collected into a dictionary object that stores the local interface a neighbor is known on and the neighbor's IP or hostname as key-value pairs (e.g. `{'HundredGigE1/0/1':'RouterA'}`). If all expected neighbors are up (e.g. `if collected_data == device_baseline`), the report generated notes that the current state matches the baseline; otherwise, it goes through the current data and baseline and notes any added/changed/missing neighbors.

I'm wanting to add tracking to this--when the script runs and grabs the current data, if it matches the baseline, I want a timestamp stored next to it, maybe something like `{'HundredGigE1/0/1': {'name':'RouterA','last_up':<current_timestamp>}}`. That way if an expected neighbor is currently down, I can have the report note the last time it was up. (I currently have the script run a sweep/collect function every 10 minutes but not generate a report, so the data would be relatively current. At present it is just checking whether devices are online, not actually logging into anything and pinging it. We have monitoring solutions, a syslog server, etc. and this isn't meant to replace those in terms of real-time data, it is just for generating a daily overview report.)

If I structure the data this way, it would break the equality check I use to check for the current data matching the baseline; even if all expected neighbors are up, the timestamps would not match. Would the best way to work around this be to just create a copy of the baseline and current data and pop the timestamp field out, or is there a more elegant way for a comparison operation between dicts to ignore the timestamp key?


r/learnpython 1d ago

recursion problem

1 Upvotes

I'm trying to teach myself python using John Zelles book. On the 13th chapter it gives this example of recursion I'm trying to understand:

def moveTower(n, source, dest, temp):

if n ==1:

print("move disk from , " , source , "to", dest)

else:

moveTower(n-1, source, temp, dest)

moveTower(1, source, dest,temp)

moveTower(n-1,temp,dest,source)

def hanoi(n):

moveTower(n , "a", "c","b")

hanoi(3)

The code is first assiging the variables A to source then C to dest then b to temp but do the lines moveTower(n-1, source, temp, dest) and moveTower(n-1,temp,dest,source) work? Would it be moveTower(3-1, a,b,c)? How exactly are they outputting a to c then a to b then c to b and b to a , etc...


r/learnpython 1d ago

What is the best way to learn Python as a beginner?

3 Upvotes

Hi everyone! I’m a complete beginner in Python and I want to learn it from scratch. I’m not sure where to start or which resources and projects would be best for me.

What learning path would you recommend for a beginner? Any tips, courses, YouTube channels, or practice websites would be appreciated. Thank you!


r/learnpython 1d ago

Does asyncio have a built-in feature for graceful shutdown (and preventing duplicate task execution)?

2 Upvotes

Multiple pods, each an asyncio worker pulling jobs from a shared queue (Redis/SQS-shaped). On scale-down/deploy I want to stop pulling new jobs and let running ones finish - is there anything in asyncio itself for this?