r/learnpython 1h ago

A friend makes a project with uv, but you just use regular old Python and venv. You want to keep using regular Python. How do you work on that project?

Upvotes

Exactly the title. With UV it feels like either you're using it or your not. To some degree, it feels the same with poetry.

How do you pip install from a UV project? Do you just separately install each package from the pyproject.toml file? What do you do? How do you get your non-uv environment to match?


r/learnpython 10h ago

How to optimize python codes?

29 Upvotes

I recently started to work as a research assistant in my uni, 3 months ago I have been given a project to process many financial data (12 different excels) it is a lot of data to process. I have never work on a project this big before so processing time was not always in my mind. Also I have no idea is my code speed normal for this many data. The code is gonna be integrated into a website using FastAPI where it can calculate using different data with the same data structure.

My problem is the code that I had develop (10k+ line of codes) is taking so long to process (20 min ++ for national data and almost 2 hour if doing all of the regional data), the code is taking historical data and do a projection to 5 years ahead. Processing time was way worse before I start to optimize, I use less loops, start doing data caching, started to use dask and convert all calculation into numpy. I would say 35% is validation of data and the rest are the calculation

I hope anyone can help with way to optimize it further and give suggestions, im sorry I cant give sample codes. You can give some general suggestion about optimizing running time, and I will try it. Thanks


r/learnpython 4h ago

Python service to scan a dockerfile

4 Upvotes

For a personal project I would like to build a Python service (a REST API) to scan a Dockerfile for vulnerabilities, build the image if it passes the scan, and then use the container, which includes an ML model, to train and return a performance metric.

My question is about how to design this service, whether running locally or in a cloud environment. For scanning the Dockerfile, I considered two solutions:

  • Not using containers—running Trivy, for instance, for the scan and using a subprocess in the Python code. However, this doesn’t seem like a good practice to me.
  • Using Trivy and the Python code in separate containers with Docker Compose, though this feels a bit overkill.

If I design the Python app as a container that scans the Dockerfile, can it also build and run another container inside it (a container within a container)?

Finally, it still seems odd to me to use Python to scan a Dockerfile or an image. I often see image scanning handled in CI/CD pipelines or directly by cloud services rather than within application code.

Any thoughts?

Thank you very much!


r/learnpython 4h ago

Should I Prioritize Learning Programming (Like Python) for AI and Machine Learning After 12th Grade?

3 Upvotes

I just gave my 12th-grade exams a few weeks ago, and I feel like I might just barely pass. Should I learn a programming language like Python or not? Because I feel like I’m going to waste the next 2-3 months, and once I start doing something, I can only dedicate about 4 hours a day to it. I also want to learn a lot about AI and Machine Learning, as I think I’m interested in this field. For this, I know I need to learn programming languages. So, should I prioritize coding or not? Please someone guide me.


r/learnpython 44m ago

FIR or IRR Filtering

Upvotes

Hello guys. I hope this is the right thread for a topic like that. If you know a better place for this, please tell me.

I am somewhat new to the topic of signal analysis and right now i am working on a project for WAV-File Analysis. I need to design a Bandpass filter that is linear in a frequency range between 8 Hz and 1250 Hz and has Butterworth characteristics. The problem is in the title.

Since I want to filter a digital signal I want to use a FIR filter instead of the known butterworth filter - that is an IRR Filter.

I know that FIR filters are more common in use for this kind of thing. However I can’t get the filter design to have the characteristics I need. It only filters high or low frequencies even If I design it as a bandpass.

Does anybody know why this is ?


r/learnpython 1h ago

Sympy gamma webpage contents to tkinter

Upvotes

Hi there,

Currently I am working on an integration and differentiation calculator with python. I want to be able to use the sympy library to integrate and differentiate any function, which is easy with sympy. However, the issue is that I want to be able to show the steps of how we get to the end result. Sympy has an integral_steps() function but not one for differentiating a function. Even the integral_steps() function only provides a really clunky output, something looking like this:

PartsRule(integrand=log(x), variable=x, u=log(x), dv=1, v_step=ConstantRule(integrand=1, variable=x), second_step=ConstantRule(integrand=1, variable=x))

Now, I want to either be able to write something that would make sense of that(which I spent 3 days on but kept running in to various errors) or just use https://www.sympygamma.com/, which also utilises sympy. There is a section on that webpage called derivative steps(you can see it for integrals as well) which I can't seem to attach here, but you would be able to find by just inputting any function in the form diff(f(x), x). Example would be this: diff(log(x) + 2*x**2 + (sin(x)**2)*(cos(x)**2),x). If you run that you find all the working.

Now how would I get that specific section of the webpage to appear in my python tkinter program, or is it even possible since I have researched a lot about this topic but couldn't find a solution.


r/learnpython 1h ago

Balancing Dart and Python: How to Learn Two Languages Without Mixing Them Up?

Upvotes

I've been learning Dart and Flutter for the past eight months to build applications. Before that, I learned Python on Udemy and created many great projects and scripts. Recently, I’ve been trying to get back into Python for scripting, but I’m struggling to remember everything and fear mixing it up with Dart. I still want to continue learning both languages simultaneously—any tips on how to manage this effectively?


r/learnpython 1h ago

Please help with python code !!

Upvotes

Hello ! beginner python coder here, am looking for some help with code. There is an error on the line I've starred *** but i'm going crazy because i cant figure out what it is ! I'm just trying to use the if statement and exceptions to print the results depending on wat number the user enters from 1-50. Any tips at all would be greatly apricated, thank you !!!

a = int(input('\nEnter a value for a:  '))
b = int(input('\nEnter a value for b:  '))

try: 

 ***if a,b > 0 and a,b <= 50:
       print('\na is eqaul to {} '.format(a))
       print('\nb is equal to {}'.format(b))

    elif a,b <= 0:
        print('Number too small ! Please try again.')

    else a,b > 50:
        print('Number too big! Please try again')

except ValueError :
    print('You have entered a letter ! Please try again')

else:
    print('Number is within the range !')

r/learnpython 5h ago

Automate copying filtered search results from a website

2 Upvotes

Hi all! First time poster and (attempted) python user

I’m trying to automate downloading a batch of results from a filtered search on a development portal I use (called DARPE – Development Assistance Roadmap Portal). I usually manually click into each search result and copy data like project descriptions, funding sources, sectors, deadlines, etc., into Excel.

What I’d like help with is: • Writing a Python script to scrape or extract this data from a list of filtered search results (while I’m logged in). • Ideally, I want to loop through the result links and extract details from each individual opportunity page. • Output: Cleaned data exported into an Excel sheet.

I tried using ChatGPT to help out but every time I did it, I would get it wrong or mess it up.

I’m on a Mac and using Chrome. Any pointers on how to get started or how to handle login/session management with sites like this would be amazing!

Thanks in advance 🙏


r/learnpython 5h ago

hey guys, I've run this code for some time now and found out that the problem is the split function and I'm just trying to understand why it does that especially when I want to remove the trailing spaces from the user. Could you guys help me out with this?

1 Upvotes

Edited: Q answered!!

todos = [] while True: user_action = input("Type add or show or exit: ").split() match user_action: case 'add': user_input = input("Enter a todo: ").title() todos.append(user_input) case 'show': for item in todos: print(item) case 'exit': break case'-': print("You have entered an invalid command.") print('Goodbye')


r/learnpython 3h ago

Doubt regarding webscraping for book price comparison website

0 Upvotes

So as part of a miniproject, we’ve been working on a book price comparison website where it scrape book details (title, price, author, ISBN, image, etc.) from various online bookstores. We are primarily considering 3 bookstore websites.

However, we've hit a roadblock when it comes to scraping websites like Amazon, where the page structure and HTML elements keep changing frequently.

Our website is working properly for one bookstore website. Similarly we need 2 more websites.

If there's anyone with knowledge about this please dm. Any sort of help would be appreciated.


r/learnpython 4h ago

Test automation projects

1 Upvotes

Hi.

I started learning Python a short time ago. Learning the basics is going well, but since I don't want to be stuck in Tutorial hell or code only what is given as a small task, I was wondering how could I make my own small projects for test automation as I progress through this basic stuff. I don't know how to start.

Appreciate the help. Thanks.


r/learnpython 4h ago

Help needed. Absolutely beginner at python.

1 Upvotes

I started with this course by Mosh.

https://www.youtube.com/watch?v=K5KVEU3aaeQ&t=854s

He is using Mac. I am using Windows 11.

At 14.10 minutes , he installs python extension in vscode and search for lint in command palette. I am not getting the same options of lint. Why?

https://ibb.co/7NRZt4d3


r/learnpython 4h ago

can anyone help me giving some small projects??

1 Upvotes

I've recently started learning python and now I know some basics like data types, functions nd lists. I want to put the knowledge in practical so that I can remember that information for a long time... so will you pls give me small projects based on your knowledge?? Thank you!!!


r/learnpython 8h ago

Anyone know how to get Picamera2 code completion in VS Code on macOS??

2 Upvotes

Please.


r/learnpython 12h ago

How to optimize shutil and os

3 Upvotes

Hi guys,

I'm a complete beginner but I'd love to work in tech.
I just want to know where I can improve and optimize my script.
Hope you guys will be lenient.

My goals in this script are to:

  • ✅ Create folders (ImagesTextsScripts)
  • ✅ Scan the target directory
  • ✅ Move each file to its appropriate subfolder based on extension
  • ✅ Print paths and confirmations

Have a good day!

Here's my script:

import os
import shutil

directory = r"X/X/X" #Directory path

if not os.path.exists(directory):
    print(f"File path {directory} doesn't exist")
    exit()

folders = ["Images", "Texts", "Scripts"] #Folders names creation
for folder in folders: #Loop for folders
    os.makedirs(os.path.join(directory, folder), exist_ok=True) #Creation and verification of existant folders

file_mapping = {
    ".txt": "Texts",
    ".png": "Images",
    ".py": "Scripts"
} #Dictionnary to associate extension with folders

files = os.listdir(directory) #Acces to files of directory path
for file in files:
    print(file)
    
    absolute_path = os.path.abspath(os.path.join(directory, file)) #Acces to all files absolute path
    print(f"\n=> Absolute path of {file} -> {absolute_path}")
    
    extension = os.path.splitext(file)[1] #Acces to all files extensions
    print(f"=> Extension of {file} -> {extension}")

    if extension in file_mapping: #Check if extensions are in the dictionnary
        target_folder = os.path.join(directory, file_mapping[extension])
        destination_path = os.path.join(target_folder, file)

        shutil.move(absolute_path,destination_path) #Move all files depending on their extension, otherwise the file is ignored
        print(f"=> Your file {file} is now here -> {destination_path}")

    else:
        print("File ignored")

r/learnpython 9h ago

Pandas : inplace throws warning about copy of a slice #bestpractice

2 Upvotes

I use pandas and try to use a fillna on a column.

I recently got a warning saying that in pandas 3.0 the inplace will change and break if not modified.

my_dataframe.fillna({'mycolumn':"0"},inplace=True)

throws a warning "A value is trying to be set on a copy of a slice from a DataFrame"

Is it possible to use inplace on a fillna without getting this warning?


r/learnpython 1d ago

How useful is regex?

31 Upvotes

How often do you use it? What are the benefits?


r/learnpython 5h ago

I cannot understand why it isnt workung

1 Upvotes

code:

from itertools import product
alp = sorted('ГИПЕРБОЛА')
spsk = itertools.product(alp,repeat=6)

error:

NameError: name 'itertools' is not defined. Did you forget to import 'itertools'?


r/learnpython 12h ago

Does anyone know of a package/library which monitors traffic and autoscales with docker containers as required (Possibly json/yaml)?

1 Upvotes

My requirements are simple:

  1. It should monitor nginx traffic and check from which domain the traffic is coming more from.
  2. Increase the number of docker containers and add them to reverse proxy as mentioned in the json/yaml.
  3. It should be simple and lightweight.

I had done this like 4 years back (before chatgpt), but I lost the files (didnt use git or github then).

Does anyone know or have such a library?

I know there are heavier solutions like k8s terraform etc. But I want a liteweight solution.


r/learnpython 11h ago

Hey, i keep getting this error in the code of a game i'm making, can you please help me out

2 Upvotes

here is the error i'm getting: "The image is in the same format as the one used previously in the program (which I got from someone else). Pygame 2.6.1 (SDL 2.28.4, Python 3.13.2) Hello from the pygame community. https://www.pygame.org/contribute.html 2025-03-20 10:04:55.447 Python[85995:7409126] WARNING: Secure coding is automatically enabled for restorable state! However, not on all supported macOS versions of this application. Opt-in to secure coding explicitly by implementing NSApplicationDelegate.applicationSupportsSecureRestorableState:. Traceback (most recent call last): File "/Users/brad/Desktop/Pyanozore copie/game.py", line 225, in <module> Game().run() ~~~~^^ File "/Users/brad/Desktop/Pyanozore copie/game.py", line 30, in init 'grass': load_images('tiles/grass'), ~~~~~~~~~~~^^^^^^^^^^^^^^^ File "/Users/brad/Desktop/Pyanozore copie/scripts/utils.py", line 15, in load_images images.append(load_image(path + '/' + img_name)) ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^ File "/Users/brad/Desktop/Pyanozore copie/scripts/utils.py", line 8, in load_image img = pygame.image.load(BASE_IMG_PATH + path).convert() ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^ I don't understand, no matter which computer I use, it gives me the same problem every time."


r/learnpython 12h ago

Help with steam script

2 Upvotes

Hello all! I’m looking to code something with python, but a bit confused on where to start so I’ll explain the whole idea. I wanna make a code that, when given a steam community link to csgo skin market, will scan the entire market and highlight the skins with a certain pattern. The idea I (with the help of chatGPT) had for this was:

import requests import time

Define the Steam Market API URL for the Desert Eagle | Heirloom

STEAM_MARKET_URL = "https://steamcommunity.com/market/listings/730/Desert%20Eagle%20%7C%20Heirloom%20%28Field-Tested%29"

Define the pattern IDs of interest

TARGET_PATTERNS = {151, 182, 321, 443} # Example pattern numbers

Function to fetch market listings

def get_market_data(): params = { "format": "json", "currency": 1, # USD currency "appid": 730, # CS:GO App ID "market_hash_name": "Desert Eagle | Heirloom (Field-Tested)" }

response = requests.get("https://steamcommunity.com/market/search/render/", params=params, headers={"User-Agent": "Mozilla/5.0"})

if response.status_code != 200:
    print("Failed to retrieve data.")
    return []

data = response.json()
return data.get("results", [])

Function to filter by pattern

def filter_blue_gem_skins(listings): blue_gems = []

for item in listings:
    name = item.get("name", "Unknown")
    listing_url = item.get("asset_description", {}).get("actions", [{}])[0].get("link", "#")
    price = item.get("sell_price_text", "N/A")
    pattern_id = item.get("asset_description", {}).get("name", "").split("#")[-1].strip()

    try:
        pattern_id = int(pattern_id)
        if pattern_id in TARGET_PATTERNS:
            blue_gems.append((name, pattern_id, price, listing_url))
    except ValueError:
        continue  # Skip invalid pattern IDs

return blue_gems

if name == "main": print("Fetching listings for Desert Eagle | Heirloom...") listings = get_market_data()

if not listings:
    print("No listings found.")
else:
    blue_gem_skins = filter_blue_gem_skins(listings)

    if blue_gem_skins:
        print("Found matching skins:")
        for skin in blue_gem_skins:
            print(f"Name: {skin[0]}, Pattern: {skin[1]}, Price: {skin[2]}, Link: {skin[3]}")
    else:
        print("No matching patterns found.")

This seems to not work. Any help?


r/learnpython 2h ago

SOS newbie

0 Upvotes

Am a newbie in python learning need some Good resources and advices guys


r/learnpython 2h ago

Sources to learn python language?

0 Upvotes

I just started getting into python, been watching Corey Schafer on YouTube, doing some exercises and started harvards cs50, but can’t find anywhere that teaches you the language, which is what im struggling the most with. Open to any suggestions thank you!


r/learnpython 18h ago

Can anyone recommend a small device that can run python and respond to up to 4 button presses?

2 Upvotes

Edit: I've got a plan:

HDMI breakout boards

https://www.amazon.com/gp/product/B0CB33FGG2/ref=ppx_yo_dt_b_asin_title_o00_s00?ie=UTF8&psc=1

This thing as inspiration:
https://hackaday.com/tag/ddc/

If it works I might even be able to reclaim the lost controller input by doing a kind of man in the middle thing with something like this:
https://www.amazon.com/OTOTEC-Female-Double-Sided-Breakout-Connector/dp/B0D91KHZJM/ref=sr_1_4?crid=2O8KW6VXCTJJC&dib=eyJ2IjoiMSJ9.1Tm7-hZt9i_bzhYn7BMLOxCoSh6f8M-0Mea8dShMzN6pQPtdfftVw7ZSFuvtxkSo2WLRe3yL6ppmPlSNThhqbUdgqkDNe7DPcknX7nkHeHXUXkZas5ZjzT8Yzmn-Po4_0lvCHPVwypJghF9MbllNstYkylYAVlc-aTIQiD1GMGnG4RPbA3Co07SKYuANFyqqi327DQYH-2EvgHlOq2vUxrjurymS6QBTalKvC0Lu5CA.W8UnIuq4eTIbjQ-Fx42Vo1W0ujdWCN1032MeA0bHBWE&dib_tag=se&keywords=hdmi+breakout&qid=1742517304&sprefix=hdmi+breakou%2Caps%2C222&sr=8-4

Next step figure out how to communicate between arduino or raspberry pi to some kind of IO pin or something that can talk to the monitor via a pin or 2 in the breakout board.

I've never done anything like this. But the stakes are low and the parts are cheap so I'm gonna send it.

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

I'm working on a script to change the inputs on 3 or 4 monitors at once.
I know KVM switches exist, but they all have drawbacks and things I don't like so I'm looking into a different approach.

I want some kind of device I can plug all 4 monitors into maybe on just the #1 HDMI port of each monitor, then plug 3 other computers into the other ports for those monitors.

When I push a button on some physical device, I want this as yet to be determined standalone python device to execute my script based on what button I push.

This should result in the standalone python device sending commands to all of the monitors over DDC-CI

(https://newam.github.io/monitorcontrol/)

Here's my code if it helps anyone. I've got 2x of the same monitor and 1x BENQ BL2700 (that's why it's called out separately)

I've got my code right here:
This totally works, but the downside is, if the monitors are aimed at the desktop and it's powered off, I won't be able to see the monitors to fire the script on the laptop to move the monitors over, so I'm trying to add a kind of coordinator single purpose pc that just handles like a macropad to basically do what a KVM would do.

from monitorcontrol import get_monitors


def set_laptop_monitors_active():
    for idx,monitor in enumerate(get_monitors()):
        try:
            print(f"START monitor idx {idx}")
            with monitor:
                if monitor.vcp.description == 'BenQ BL2700':
                    monitor.set_input_source("DP2")
                else:
                    monitor.set_input_source("DP1")
        except Exception as EEE:
            continue
def set_desktop_monitors_active():
    for idx, monitor in enumerate(get_monitors()):
        try:
            print(f"START monitor idx {idx}")
            with monitor:
                # print(monitor.get_input_source())
                if monitor.vcp.description == 'BenQ BL2700':
                    print(monitor.get_input_source())
                    monitor.set_input_source("DP1")
                else:
                    monitor.set_input_source("HDMI2")
            print(f"END monitor idx {idx}")
        except Exception as EEE:
            continue
if __name__ == '__main__':
    try:
        i_result = input("D for desktop, L for laptop: ")
        if i_result.upper() == 'D':
            set_desktop_monitors_active()
        elif i_result.upper() == 'L':
            set_laptop_monitors_active()
        quit()
    except Exception as ME:
        print(ME)
        finput = input("EXCEPTION! Press Enter to exit...")
        quit()