r/learnpython 5h 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 10h 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 11h ago

I just started learning python!!!

8 Upvotes

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


r/learnpython 6h 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 3h 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 7h ago

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

19 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 14h ago

Is it bad practice to use complex List Comprehensions?

25 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 9h ago

When did Python become easier for you?

2 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 1m ago

Projects to Learn

Upvotes

I am an engineering student and I have a little exposure to python in my classes but I’d like to really hone my skills and learn how to use python for real. What are some good projects to build that will teach my the skills to code?


r/learnpython 1h ago

Python for Engineer

Upvotes

Hi everyone!

I recently graduated with a degree in Electrical Engineering, and I'd like to learn Python to improve my engineering workflow. The problem is that I don't really know what Python can do for someone in my field, so I'm not sure where to start.

I'm also unsure about the best way to learn it. Would you recommend a bootcamp, YouTube, Coursera, Udemy, or another resource?

My main goal is to use Python for engineering tasks such as automation, data analysis, calculations, working with Excel, and any other applications that are useful for electrical engineers.

If you were starting from scratch today, what learning path would you recommend?

Thanks you all!


r/learnpython 2h ago

grid or pack

0 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 22h ago

Failed to build wheel for mayavi

1 Upvotes

So I need to import mayavi for a long reason, and every time I try to import it, it says

Current thread's C stack trace (most recent call first):
        <cannot get C stack on this system>
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for mayavi
Failed to build mayavi
error: failed-wheel-build-for-install

I already installed VTK and PyQt5 with no issue using pip and tried both with and without PyQt5 (since on the website they install it after installing mayavi). I'm currently on a windows x64 and using visual studio code

If anyone knows anything about this I'd appreciate any advice ;u;


r/learnpython 9h 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 29m ago

Random bluesky post code, but it needs help with efficiency

Upvotes

I had a program made that takes all my bluesky posts, and then spits one of them back randomly at me. However, I want it to actually cache all my bluesky posts, and ask something like "Would you like to refresh your cache" which would go back through my posts, grabbing all the new ones too.

How do I make it store what it's pulled and just run a random pick from that index?

import requests
import random
import time


BASE_URL = "https://public.api.bsky.app/xrpc/app.bsky.feed.getAuthorFeed"


username = "---.bsky.social"


feed = []
cursor = None
page = 1


while True:
    params = {
        "actor": username,
        "limit": 100
    }


    if cursor:
        params["cursor"] = cursor


    print(f"Downloading page {page}...")


    response = requests.get(BASE_URL, params=params)


    if response.status_code != 200:
        print("Error:", response.status_code)
        print(response.text)
        break


    data = response.json()


    items = data.get("feed", [])


    if not items:
        break


    feed.extend(items)


    cursor = data.get("cursor")


    if not cursor:
        break


    page += 1


    # Be nice to the API
    time.sleep(0.2)


print(f"\nDownloaded {len(feed)} feed items.")


if not feed:
    quit()


chosen = random.choice(feed)


post = chosen["post"]


record = post.get("record", {})


text = record.get("text", "(No text)")


author = post["author"]["displayName"]
handle = post["author"]["handle"]


print("\n============================")
print("Random Feed Item")
print("============================")
print(f"Author : {author} (@{handle})")
print()


if "reason" in chosen:
    print("This is a REPOST")
    print("Reposted by:", chosen["reason"]["by"]["displayName"])
    print()


print(text)


print("\nURI:", post["uri"])


uri = post["uri"]


parts = uri.split("/")


did = parts[2]
postid = parts[4]


print(f"https://bsky.app/profile/{did}/post/{postid}")import requests
import random
import time


BASE_URL = "https://public.api.bsky.app/xrpc/app.bsky.feed.getAuthorFeed"


username = "aaronamethyst.bsky.social"


feed = []
cursor = None
page = 1


while True:
    params = {
        "actor": username,
        "limit": 100
    }


    if cursor:
        params["cursor"] = cursor


    print(f"Downloading page {page}...")


    response = requests.get(BASE_URL, params=params)


    if response.status_code != 200:
        print("Error:", response.status_code)
        print(response.text)
        break


    data = response.json()


    items = data.get("feed", [])


    if not items:
        break


    feed.extend(items)


    cursor = data.get("cursor")


    if not cursor:
        break


    page += 1


    # Be nice to the API
    time.sleep(0.2)


print(f"\nDownloaded {len(feed)} feed items.")


if not feed:
    quit()


chosen = random.choice(feed)


post = chosen["post"]


record = post.get("record", {})


text = record.get("text", "(No text)")


author = post["author"]["displayName"]
handle = post["author"]["handle"]


print("\n============================")
print("Random Feed Item")
print("============================")
print(f"Author : {author} (@{handle})")
print()


if "reason" in chosen:
    print("This is a REPOST")
    print("Reposted by:", chosen["reason"]["by"]["displayName"])
    print()


print(text)


print("\nURI:", post["uri"])


uri = post["uri"]


parts = uri.split("/")


did = parts[2]
postid = parts[4]


print(f"https://bsky.app/profile/{did}/post/{postid}")

r/learnpython 9h 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 2h ago

Starting over with python

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

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

42 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 6h 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 3h ago

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

6 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 20h 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 8h 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?