r/learnpython 1d ago

Is it bad practice to use complex List Comprehensions?

33 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 22h 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 13h ago

Best Python libraries or tools for testing AI agents that call external APIs

0 Upvotes

Using LangChain to build an agent that calls Stripe, Slack and HubSpot. Unit testing the individual functions is fine but integration testing the full agent behavior feels impossible. Every time we think we've covered the cases something new breaks in prod. What tools are people using?


r/learnpython 4h ago

Stuck on P.O.O.P Encapsulation

0 Upvotes

I'm using Claude Ai. To teach me python. But now im very confused on encapsulation. I've tried YouTube tutorials but all I see is Javascript. I asked for a simpler explanation, but then I get hit with stuff like getter, setter, property() (I understand the property function) but then the core concept makes me scratch my head more the deeper I ask. Wondering if any of y'all can assist me.


r/learnpython 1d ago

I just started learning python!!!

7 Upvotes

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


r/learnpython 16h ago

Projects to Learn

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

Monolithic designed auth solution

0 Upvotes

I am trying to learn modular monoliths and I want to use this auth solutions for repetitive use for my applications.

If I asked you to convert the repo linked, into monolithic patterns, how would you do it for app/.

Repo: https://github.com/auth0-blog/auth0-rbac-fga-fastapi

fastapi-openfga-project/
├── app/
│ ├── main.py # FastAPI application entry point
│ ├── config.py # Configuration settings
│ ├── database.py # SQLAlchemy database setup and models
│ ├── models/
│ │ ├── organization.py # Organization Pydantic models
│ │ └── resource.py # Resource Pydantic models
│ ├── routes/
│ │ ├── organization_routes.py # Organization management endpoints
│ │ └── resource_routes.py # Resource management endpoints
│ ├── services/
│ │ └── authorization_service.py # OpenFGA integration
│ ├── utils/
│ │ └── auth0_fga_client.py # OpenFGA client wrapper
│ └── openfga/
│ └── model.fga.yaml # OpenFGA model definition
├── app.db # SQLite database file (auto-created)
├── requirements.txt
└── README.md


r/learnpython 11h ago

Would like recommendations for add-ons or libraries at a new job.

0 Upvotes

I'm a newly-hired lead engineer at a manufacturing company, been in metal cutting for 35+ years.

I dabble in Python, I used to do a lot of quick basic, then vb, even had a couple of programs marketed in the 90s, but switched over to python ​​when I started playing with raspberry pis. (Or is it pi's?)

Anyway, I do a lot of quick and dirty apps just to solve problems... a little statistics for capability studies, a fair amount of trig, and some graphics as well. At my last job I wrote a little program to turn an image into a cutter path, and a plotter that would turn cnc machine programs (g code) into a graphical plot showing cutter paths, stuff like that. Make no mistake, I'm self taught and inefficient, but I find python far more effective than vba in excel.

Sorry for rambling.

My new employer has asked for a list of software I would like to have installed on my windows 11 machine, so a few cad titles, stuff like that. I only use windows at work, so I'm not certain what a good initial install should include... my experience has all been on linux, and mostly on raspbian... so I don't know what I don't know.

I'll be requesting python, but I would like to know what add-ons should I request so im not constantly having to ask for something else (I should say, on the raspberry pi I have a lot of addafruit stuff, but won't be doing any circuit work at work.) I'm not certain beyond tkinter, and would appreciate any suggestions.

Thx!


r/learnpython 18h 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 20h ago

cookiecutter and git repo advise needed

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

Random bluesky post code, but it needs help with efficiency

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

Python for Engineer

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

can I send a message N times automatically using Python

0 Upvotes

can I send a message N times automatically using Python? short question!

edit: guys listen I found out a way to do that with PyAutoGUI here is the code:

import PyAutoGUI

import time

message="You enter the text" # or make an input

number_of_message= 4 #just an exemple you can also make an input

time.sleep(10) # let yourself 10 seconds to put the cursor where you wanna print those messages, for me it was my Web whatsapp tab

for i in range(number_of_message):

PyAutoGUI.write(message)# it writes #automatically the message where your #cursor is at

PyAutoGUI.press("Enter")#it sends the #message automatically

time.sleep(2) # it lets a time interval #of two seconds between the messages

But it won't let me use my computer normally I cant move the cursor and have to wait till all the messages are sent, if you could also help me automate (make it automatic, sorry for my english) that it will be great!


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

Started learning a 2 hours ago

0 Upvotes

So this is my first project its in german and i wanted to get some opinions from a few experienced programmers to help me and stuff so this is the code and its a password manager

import random
def passwortgenerator(parameter):
    worter = (
    "a",
    "b",
    "c",
    "d",
    "e",
    "f",
    "g",
    "h",
    "i",
    "j",
    "k",
    "l",
    "m",
    "n",
    "o",
    "p",
    "q",
    "r",
    "s",
    "t",
    "u",
    "v",
    "w",
    "x",
    "y",
    "z",

    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
    "G",
    "H",
    "I",
    "J",
    "K",
    "L",
    "M",
    "N",
    "O",
    "P",
    "Q",
    "R",
    "S",
    "T",
    "U",
    "V",
    "W",
    "X",
    "Y",
    "Z",

    "0",
    "1",
    "2",
    "3",
    "4",
    "5",
    "6",
    "7",
    "8",
    "9",

    "!",
    "@",
    "#",
    "$",
    "%",
    "^",
    "&",
    "*",
    "(",
    ")",
    "-",
    "_",
    "=",
    "+",
    "[",
    "]",
    "{",
    "}",
    ";",
    ":",
    ",",
    ".",
    "?",
    )
    passwort = "".join(random.sample(worter, k = int(parameter) ))
    return passwort

generieren = input("Passwort generieren? ")

if generieren == "ja":
    parameter = input("Wie viele Zeichen?  ")
    neues_passwort = passwortgenerator(parameter)
    print(neues_passwort)
    wo = input("Wo wirst du das Passwort verwenden? ")

    open("passwörter.txt", "a").write(wo + ":   " + neues_passwort + "\n")

    anzeigen = input("Passwörter anzeigen? ")

    if anzeigen == "ja":
        with open("passwörter.txt", "r") as passworter:
            print(passworter.read())

else:
    anzeigen = input("Passwörter anzeigen? ")

    if anzeigen == "ja":
        with open("passwörter.txt", "r") as passworter:
            print(passworter.read())

bewertung = input("Bewerten Sie bitte meinen Passwortmanager (1-10): ")

print("Danke für Ihre Hilfe!")

user = input("Wollen Sie noch Ihren Namen eingeben? ")

if user == "ja":
    name = input("Ihr Name bitte: ")
    open("Bewertung.txt", "a").write(name + ": " + bewertung + "\n")
else:
    print("Ich danke Ihnen trotzdem.")
    open("Bewertung.txt", "a").write("Anonym" + ":  " + bewertung + "\n")

r/learnpython 1d 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 1d ago

windows carriage return pairs

0 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 19h 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 1d ago

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

36 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 22h 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

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

5 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?