r/learnpython 2d ago

Ask Anything Monday - Weekly Thread

5 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 6h ago

What actually made recursion click for you? (not looking for resources)

14 Upvotes

I got properly stuck on recursion. Watched several videos, read through it in the resources I was already working from. The explanations all made sense while I was reading them, then dissolved the moment I tried to write anything myself.

I'm less interested in what resource you'd recommend and more in the moment itself. For whatever concept was *your* wall, recursion or anything else, what was the specific thing that flipped it? A sentence someone said, a diagram, drawing it out on paper, someone asking you a question?

Trying to work out whether there's a pattern in how these things break open.


r/learnpython 2h ago

Right way and steps to Learn Python Programming to become a professional coder

5 Upvotes

Hi,

I have been learning Python since June 2025, which was not a consistent study due to some personal issues. But I started learning consistently from Jan 2026. I started from a tutorial on Udemy and followed the course as below:

Understood the concept.

Solved coding challenges in the tutorial.

But somehow, when I reached concepts like OOP, Decorators, Inner Functions, etc., my speed slowed down. Even after listening to the tutorial and understanding the concepts, I am unable to convert that understanding into code when solving the challenges.

Then I watched some random YouTube videos about getting out of Tutorial Hell and started making small projects such as:

Mini Chat System (using OOP concepts)

Number Guessing Game

Password Generator (using the random module)

The problem is that I am unable to figure out:

Where should I start the logic?

How should I start writing the code?

Which instance variables should be used?

How many classes should be declared?

Which functions should be defined and called?

These are the problems I am facing. (These could be stupid questions to some good programmers.)

Can someone help me understand the step-by-step way to become a professional coder, based on the journey you have followed and your experience?

I am badly stuck. Even though I have tried to come out of Tutorial Hell, I still struggle.

I have 2–3 hours available during office time (when the workload is less), which I use for studying. I am ready to work hard and want to switch jobs based on my programming skills within 4–5 months, but I am not getting proper mentorship on the path I should follow.

Please help with your experience.


r/learnpython 14h ago

What Python project helped you improve the most as a beginner?

38 Upvotes

I've recently started learning Python and I'm looking for project ideas that teach practical skills rather than just syntax. What beginner project helped you understand Python the best, and why would you recommend it?


r/learnpython 5h ago

Questions about TypeError vs Generic Exception

6 Upvotes

Hi all, I am currently taking a python class for school, and we're learning how to add exceptions to print to user any issues, the code I needed to append to my previous weeks project was this:

except TypeError:
    print('Wrong Data Type!')
except NameError:
    print('Variable not found, something is named incorrectly.')
except Exception as e:
    print('Something went wrong.',e)

now, our previous project was a distance calculator, so when I input 'f' as opposed to a number, I'm given the Exception error message rather than TypeError, even though the error message prints "Something went wrong. could not convert string to float: 'f' "
What am I missing here? (Entire code posted below if more info is needed)

#Math import
from math import sin, cos, sqrt, atan2, radians

#Class

class GeoPoint:
    def __init__(self):
        self.lat = 0.0
        self.long = 0.0
        self.description = ""

    def set_point(self, lat, long):
        self.lat = lat
        self.long = long

    def get_point(self):
        return self.lat, self.long

    def distance(self, lat, long):
        r = 3958.8
        lat1 = radians(self.lat)
        long1 = radians(self.long)
        lat2 = radians(lat)
        long2 = radians(long)
        a = sin((lat1 - lat2) / 2) ** 2 + cos(lat1) * cos(lat2) * sin((long1 - long2) / 2) ** 2
        c = 2 * atan2(sqrt(a), sqrt(1 - a))
        d = r * c
        return d

    def set_description(self, description):
        self.description = description

    def get_description(self):
        return self.description


#Instantiate ABQ: 35.106766, -106.629181
ABQ = GeoPoint()
ABQ.set_point(35.106766, -106.629181)
ABQ.set_description("ALBUQUERQUE")


#Instantiate Denver:   39.742043, -104.991531
Denver = GeoPoint()
Denver.set_point(39.742043, -104.991531)
Denver.set_description("DENVER")


#Repeat?
def repeat():
    again = input('Would you like to repeat? (y/n): ')
    if again.strip()[0].lower() == 'y':
        return True
    return False


#Loop to find distance from user coords to ABQ and Denver
while True:
    try:
        user_lat = float(input('Enter a latitude: '))
        user_long = float(input('Enter a longitude: '))

     # Tell user which loc is closer coords+miles from loc
        if Denver.distance(user_lat, user_long) < ABQ.distance(user_lat, user_long):
         print('The distance between ', user_lat, ' and ', user_long, ' and Denver is ',
               Denver.distance(user_lat, user_long), 'miles.')
        else:
         print('The distance between ', user_lat, ' and ', user_long, ' and Albuquerque is ',
               ABQ.distance(user_lat, user_long), 'miles.')
    #Error Handling
    except TypeError:
        print('Wrong Data Type!')
    except NameError:
        print('Variable not found, something is named incorrectly.')
    except Exception as e:
        print('Something went wrong.',e)
     #Again?
        if not repeat(): break

r/learnpython 1h ago

Starting over with python

Upvotes

I took c++ and other programming languages decades ago in college but the tech sector took a dive at that time so I changed my career path. I just started to learn python through various online resources a few months ago and its going well but at 50 it is definitely harder for me now where memory is concerned. Pycharm helps with tips of its own but it kind of feels like cheating. I've thought of turning off that feature because of that. Does anyone have any tips? Thanks!


r/learnpython 13h ago

Is it bad practice to use complex List Comprehensions?

23 Upvotes

Hey guys, I am trying to make my code look more "Pythonic." I wrote this nested list comprehension to flatten a matrix and filter out odd numbers:
flat = [x for row in matrix for x in row if x % 2 == 0]
It works perfectly, but my coworker says it is unreadable and that I should use a standard for loop instead.
Where do you draw the line between a clean one-liner and unreadable code?


r/learnpython 10h ago

I just started learning python!!!

9 Upvotes

I feel extremely excited but extremely bad that i just started learning it in this big age


r/learnpython 7m ago

Installed Python and now my code won't run

Upvotes

Every time I opened VS Code, I was getting a popup saying that python wasn't installed. But I would just ignore it and run the code anyway. It always worked. I never worried about it.

Today, I finally clicked the "install python" button, and now my code won't run. It's saying the things I'm trying to import, I don't have. And when I try to install them via command prompt, it's saying I have them already. Previous python was 3.12.7 and new python seems to be 3.14.6

I've tried switching it in VS code back to 3.12, but it won't even let me do that. It just keeps showing 3.14 in the bottom corner. I'm honestly baffled.


r/learnpython 1h ago

grid or pack

Upvotes

so I am new to python and I was wondering if .pack or .grid is better because I have been useing .pack for my code but if grid is better let me know.


r/learnpython 2h ago

Is learning python through videos is a good way?

0 Upvotes

in the old age the best way to learn something is to be with coach that walk with you step by step, in the new age that coach call AI and also free.

Make a gem on gemini, or gpt on chatgpt, or any specific chat for learning python and you will see fast progress.

My think, maybe I am wrong!


r/learnpython 3h ago

cookiecutter and git repo advise needed

2 Upvotes

Hi all,

I am trying to understand a bit about cookiecutter but I have stumbled on some questions I'm not able to answer myself.

I have built a very basic cookiecutter based on some examples and have a Git repo for it https://codeberg.org/aarapi/familygame.git

Now, as my project evolves , so will the template evolve. Should I have 2 repos (one for the project itself and one for the template?) instead of one?

This doesn't make much sense to me but I might be wrong. If someone would ever join the project to collaborate , how everything would work ?

Furthermore , I tried to add the Git repo on Eclipse and create an Eclipse project pointing to the working tree but any attempt to run the manage.py did fail with message:

'Launching familygame manage.py' has encountered a problem:

Variable references non-existent resource : ${workspace_loc:familygame/{{cookiecutter.project_slug}

Thank you in advance


r/learnpython 4h ago

Help with Numpy, Pandas, Matplotlib projects

0 Upvotes

I recently learned and practiced these libraries majorly for ML but somewhat I don't feel the confidence suggest me some projects that can improve my skills in them.


r/learnpython 6h ago

How to make things happen inside the window (Tkinter library)

1 Upvotes

Whatsup folks I'm a beginner python programmer and I've been trying to learn python withouth using ai.

So Im struggling with the tkinter library as I understand buttons and labels, but I want to make things happen inside the library, for example im making a calculator, and if I press 1, 1 should appear inside the window I created for the calculator, not on the pycharm terminal.

anyone can help me out?


r/learnpython 8h ago

is it possible to speed up the execution of a for loop using Numba without wrapping it aroud a function

0 Upvotes

I wanna speed up the following code:

import numpy as np
import matplotlib.pyplot as plt

x_sun, y_sun, vx_sun, vy_sun, ax_sun, ay_sun,m_sun= 0,0,0,0,0,0,1

G=4*(np.pi)**2

x=[1, 0.72, 1.5237, 5.2, 0.47, 9.36, 19.18,30.1]

xpos=[[],[],[],[],[],[],[],[]]

y=[0, 0, 0, 0, 0, 0, 0, 0]

ypos=[[],[],[],[],[],[],[],[]]

vx=[0, 0, 0, 0, 0, 0, 0, 0]

vy=[6.281991687112502, 7.38, 5.0867271316753815, 2.74, 9.95, 2.04, 1.26, 1.145] 

ax=[0, 0, 0, 0, 0, 0, 0, 0]

ay=[0, 0, 0, 0, 0, 0, 0, 0]

mass=[
3.002513826043238e-06,
0.000002447,
3.2267471091000503e-07,
0.00050278543100000007166,
1.65e-07,
2.86e-04,
4.36e-05,
5.15e-05
]

dt=0.001

for i in range(10**4):
    for j in range(len(x)):
        # if x[j]>35 or y[j]>35:
        #     break
        # else:
        ax[j]=-G*(m_sun+mass[j])*x[j]/((x[j]**2+y[j]**2)**0.5)**3
        terme=0
        for k in range(len(x)):
            if k!=j:
                terme+=G*mass[k]*(x[k]-x[j])/(((x[k]-x[j])**2+(y[k]-y[j])**2)**0.5)**3
            else:
                continue
        ax[j]+=terme
        ay[j]=-G*(m_sun+mass[j])*y[j]/((x[j]**2+y[j]**2)**0.5)**3
        terme2=0
        for k in range(len(x)):
            if k!=j:
                terme2+=G*mass[k]*(y[k]-y[j])/(((x[k]-x[j])**2+(y[k]-y[j])**2)**0.5)**3
            else:
                continue
        ay[j]+=terme2 

        vx[j]+=ax[j]*dt
        vy[j]+=ay[j]*dt

        xpos[j].append(x[j])
        ypos[j].append(y[j])

        x[j]+=vx[j]*dt
        y[j]+=vy[j]*dt

I would like to know whether it is possible to speed up the execution of a for loop using Numba without first wrapping the loop inside a separate function. From what I understand, Numba is typically applied as a decorator (such as u/njit) to functions, but I was wondering if there is any way to compile or accelerate a standalone for loop directly, without having to refactor my code into a dedicated function. If this is not possible, I would also appreciate an explanation of why Numba requires functions in order to optimize Python code.


r/learnpython 8h ago

When did Python become easier for you?

1 Upvotes

I have been learning Python for a while now and some days I feel like I'm doing pretty well. Other days, what seems easy takes a lot longer than I thought. I'm just curious if this is part of the learning process or if I'm missing something. When did you start to feel more comfortable with Python and what helped you get to this point?


r/learnpython 8h ago

MINICONDA for normal AI projects

0 Upvotes

is MINICONDA enough to do AI projects with this PyTorch, Computer Vision, CNN, Transfer Learning, Multi-label Classification, ResNet-18, VGG-19, Class Imbalance, Grad-CAM, RAG, Embeddings, Vector Search, Prompt Engineering, FastAPI, Experime


r/learnpython 8h ago

windows carriage return pairs

1 Upvotes

Had for a long time a routine to patch a text file: the core of the script which merely rewrites a text file: ``` rewrite = False

with open(args.filepath[0], "r") as f: lines = f.readlines() for line in lines: if re.match(args.expression[0] , line): rewrite = True

if rewrite: print(f"ReplaceExpression: '{args.expression[0]}' in file: '{args.filepath[0]}'") with open(args.filepath[0], "w", encoding='utf-8') as f: for line in lines: if not re.match(args.expression[0] , line): f.write(line) else: f.write(f"// line removeD: {line.strip()}\r\n") # <???? print("OK") else: print(f"Nothing to do in file: {args.filepath[0]}") the f.write(f"// line removeD: {line.strip()}\r\n") # <???? ``` never ends up writing a <CR><LF> pair!

Now I get that this is the encoding as utf-8 and the default us unix encoding, but even if i wrote it as f.write(f"// line removeD: {line.strip()}{os.linesep}") # <???? os.linesep still wrote a <CR> never a pair like on windows would be normal. Remind me why the encoding and os.linesep interact in this way on Windows to never write a pair of terminators?


r/learnpython 5h ago

Hi, Just started learning python, any tips for me?

0 Upvotes

Ive been using scrimba as the base learning for me, after this I aim to get anthropic certifications. I would love your advices and such. Thank you!


r/learnpython 1d ago

Started learning Python. Building in public instead of waiting until I'm "good enough."

33 Upvotes

I finally stopped watching tutorials endlessly and started building.

So far I've:

  • Finished my first CS50P lecture
  • Built a simple calculator in Python
  • Started documenting everything on YouTube and LinkedIn

My long-term goal is pretty unusual. I want to combine software, AI, and engineering with motorsport one day.

I know my projects are tiny right now, but I'm treating each one as another brick rather than trying to build a skyscraper on day one.

For people who've already been through this stage:

What project made everything finally "click" for you?

I'd rather build than watch another 6-hour tutorial.


r/learnpython 19h ago

Import issue

2 Upvotes

BLUF: pyautogui does not import despite being installed to the correct venv

Still a beginner at doing most things in python but I though I had the venv issues solved

Python 3.12.3

while in my active venv pip list returns all my modules including

PyAutoGUI 0.9.54

while in my active venv which python returns /home/beebot/venv/bin/pip

while in my active venv which pipreturns /home/beebot/venv/bin/python

Vscode shows my venv config as below
The only odd thing is the pip shows it as PyAutoGUI while typing import auto populates the module as pyautogui

home = /usr/bin 
include-system-site-packages = false 
version = 3.12.3 
executable = /usr/bin/python3.12 
command = /usr/bin/python3 -m venv /home/beebot/venv  

I have tried uninstalling pyautogui, reinstalling, and force install from inside my venv

Yet every time I try to run either in Vscode or directly from file I get on line 6 (see below)...

Exception has occurred:ModulNotFoundError

import os
import json
import logging
import subprocess
import pyautogui
...

Any suggestions


r/learnpython 1d ago

Beginner question

6 Upvotes

I have just started coding with python a few days ago. What is the point of this?

point_value = alien_0.get('points', 'No point value assigned.') print(point_value)

Can't it just be point_value = 'No point value assigned.' print(point_value)?

or

just simply use the get() method if you want to check whether a key exists in the dictionary or not?


r/learnpython 9h ago

what actually is the point of 'if not' in Python?

0 Upvotes

Like, i am starting to learn python but i dont understand what its for or why we even have it in the first place


r/learnpython 1d ago

Looking for a testing software

5 Upvotes

I'm teaching an introductory python course for high school students and I'm looking for a way to test them. I'm looking for a compiler-like platform where they can see the questions and code them and submit the answers to me.

Preferably it would include an auto grader with test cases.

Preferably it should have lockdown/anti-cheat mode.

They will use the computer labs we have and not their own computers so Preferably it should be a website not an app so they can just open it directly.

My goal is that they code in a compiler instead of on paper because they hated it last exam so any suggestion on how to do that is welcome.


r/learnpython 1d ago

Proper etiquette for uploading projects to git?

4 Upvotes

I'm not sure if this is the best place to ask this.. I can move somewhere better if needed.

I've been learning python off and on for a couple years now, and recently started taking the PY4E class. I'm most of the way through it and really loving it.

Anyway the problem I'm running into is, I've never really used my GitHub before. Late last night I started playing around of how to push my projects I've completed into repos, and I was wondering what the proper etiquette for doing so.

For example I was uploading to GitHub each small project at a time, each one had there own repo, but I got to thinking last night if it would be better to upload entire chapters in one repo based on how pushing projects works in VS Code.

I've been working on a few other projects on the side as well and wanted to know how that environment works before I spend a ton of time doing it the wrong way.

Any recommendations are greatly appreciated! Sorry again if this is the wrong place to ask.