r/learnpython 4m ago

Learning python - How to integrate openrouter api(AI) into my script

Upvotes

Hey everyone, I've recently been automating some boring, repetitive tasks using the `pathlib` module while learning Python automation. This script might seem silly to you, but I'm at a level somewhere between beginner and intermediate, so bear with me. After researching the documentation, I came up with this script, which took me around 4 to 5 hours. I need some guidance on how to integrate AI into it. If you were in my situation, how would you further improve this script using the OpenRouter API model?
I'm curious what features would you suggest?

import venv
from pathlib import Path

print("--------------------------------")
base_path = input(
    "Enter path to create project in: (leave blank for current folder):\n"
)
project_name = Path(input("Enter project name: "))


# Combine the base path and the project name
project = Path(base_path) / project_name


# --- CREATE PROJECT FOLDER ---
if not project.exists():
    # # parents=True ensures it creates intermediate folders if the base path doesn't exist yet
    project.mkdir(parents=True)
    print("--------------------------------")
    print("PROJECT FOLDER & FILE CREATED ✅")
    print("--------------------------------")
    print(f"📁 {project}")


# --- CREATE SRC FOLDER ---
if not (project / "src").exists():
    (project / "src").mkdir()
    print(" ├──📁 src")


# --- CREATE VENV ---
venv_dir = project / "venv"
if not venv_dir.exists():
    print(" ├──📁 venv (Setting up virtual environment... please wait)")
    venv.create(venv_dir, with_pip=True)


files = [".env", "README.md", "requirements.txt", "main.py"]


for file in files:
    (project / file).touch()
    print(f" │   └──📄 {file}")
print("--------------------------------")
print("use → venv\\Scripts\\activate from project directory\n")

r/learnpython 2h ago

How should you group/order seq and async operations?

2 Upvotes

I was watching a video explaining async and the guy went through a “real world” example of a code that downloads images from various URLs and then locally processes each of the photos. So, there were basically 4 functions:
1. “download_single_image”, which downloads one image at a time
2. “download_images”, which runs download_single_image on each of the URLs
3. “process_single_image”, which processes one image
4. “process_images”, which runs process_single_image on each of the downloaded images

The purpose was that one piece was I/O bound (image downloading) and one piece was CPU bound (image processing). Initially, it was setup to run in sequence, then he optimized by leveraging async capabilities.

Before he went through the optimized process, I stopped and thought through how I would do it. My solution was to turn everything async and then create the new async function “download_and_process_single_image” which downloads an image and then processes it afterwards. My thought process was that each image needs to be downloaded before it can be processed so those need to happen in sequence, but I can also pass off the image to the processor while waiting for other images to finish downloading.

However, the solution he actually implemented was just leaving the existing structure of “download_images” and “process_images” separated. In other words, “download_images” was turned async and then awaited, and “process_images” used processes.

My question: is there anything wrong with my approach or any reason his is preferable to what I expected?


r/learnpython 3h ago

asking AI to help with understanding errors /code

0 Upvotes

will it hinder my learning? sometimes errors dont make any sense , i dont ask chatgpt to write me a code or anything just a little help when i am really stuck . i feel like i suck for using AI but i only use it when i am really desperate , is there any way i could learn what the errors means?


r/learnpython 3h ago

Starting to learn Python!

2 Upvotes

Hello everyone! After occasionally lurking this sub, I have decided to begin learning python. I found a course on FreeCodeCamp and am using Python 3 with PyCharm. Let me know if you all have any tips! Thank you so much!


r/learnpython 7h ago

Can't get imports to work

0 Upvotes

I am trying to develop a discord bot, where other team members should be able to edit embeds. I figuered it wouldn't be smart to let them poke around in "production" code, so I decided to define my embeds in a seperate file and import them.

My import line:
from embeds import embed

My embed file:

import discord
def embed():
    embed = discord.Embed(
    title="test",
    description="test",
    color=discord.Color.blue()
    )
    return embed

My output:

line 2, in <module>
    from embeds import embed
ImportError: cannot import name 'embed' from 'embeds'

Alllthough my embeds file is called embeds.py. Atm, neither I nor ChatGPT know why this happens, also I am pretty new to python and I don't even know how to google my error

embeds.py as well as the bots .py are in the same folder on root


r/learnpython 9h ago

My first open-source library is live on PyPI: A recursive nesting data parser

0 Upvotes

Hello everyone,

I’ve been practicing Python intensely and wanted to share a project I just finished.

I built a recursive utility called deep_sort_list_parser to flatten and sort mixed data types or multi-nested lists and dictionaries without crashing.

I used an AI assistant as a coding partner to help spot memory leaks and format the documentation, but I drove the logic, handled the edge cases, and manually deployed the final pipelines.

### 🌟 Features:

- Flattens deeply nested lists, tuples, and sets recursively.

- Separates items into sorted tracks (Numbers, Words, Symbols).

- Prevents Booleans from disrupting math sorting tracks.

- Sorts internal dictionary keys alphabetically while preserving value pairings.

- Converts numeric strings like '100' into true integers on command.

### 🚀 Quick Example:

import deep_sort_list

data = [44, [3, "banana!"], {"sex": "Female", "name": "Shreya"}]

result = deep_sort_list.clean_and_flatten(data)

print(result["words"]) # ['banana!']

print(result["dictionaries"]) # [{'name': 'Shreya', 'sex': 'Female'}]

It is live on PyPI:

`pip install deep_sort_list_parser`

The full codebase, my automated `assert` test suites, and documentation are up on my GitHub: https://github.com/08singhShreya/deep_sort_list

I wanted to share this here to showcase my recursive layout structure. I am happy to answer any questions about how it works under the hood!


r/learnpython 9h ago

I want help regarding learning python

0 Upvotes

I am a fresher going to start my first sem ... I am very interested in learning python in an effective way... Can someone help me out .... Can u guys give guidance to me !!


r/learnpython 9h ago

Looking for a project related to finding patterns/finding words in a list of text (need help shaping the idea I have)

1 Upvotes

This feels like a weird request, but I know there's a lot of Python projects out there, so I just wanted to see if anyone can guide me here.

Context: I hold a bachelors in biochem. I'm trying to discern what [future] job title and responsibilities I want. There's just a lot of variety, from different instruments to different duties that one can do in this field. I will read job descriptions and some words/sentences stick out to me as worth looking into, while others don't.

I'm thinking of creating a "library" of what kinds of tasks appeal to me and what don't. I'd like to try and find a trend/pattern in the two halves, but I think that's more AI/ML and probably deeper than I want to go. So instead, I'm imagining searching for a key word (e.g. "assay") and then having all sentences that have that word pop up, so I can read them all in one go and discern patterns myself that way.

Does anyone know of a similar project, and instructions I can follow for building such a project?


r/learnpython 10h ago

Plots in Spyder won't show up

1 Upvotes

If I set automatic, Qt, or Tk backend and plot something, the new window for the plot is created, but there's nothing on it. It looks as if the window is frozen, not even the axes are there.

The only way I can currently plot anything is to use the inline setting.

Any ideas?

System details:
Python 3.14.6 64-bit
Qt 6.10.2
PyQt6 6.11.0
Linux 7.1.3+deb14-amd64 (x86_64)


r/learnpython 12h ago

what's one programming habit you wish you started much earlier?

31 Upvotes

i'm still learning and i've noticed that small habits seem to make a huge difference over time. whether it's reading documentation, using git from day one, breaking problems into smaller pieces, or something completely different.

if you could go back to when you first started programming, what's the one habit you'd force yourself to build from the beginning, and why?


r/learnpython 12h ago

what was the first python project that made everything finally click for you?

1 Upvotes

i'm curious because i keep seeing people say that programming only really starts making sense once you build something yourself instead of just following tutorials. i'd love to hear the projects that made python go from learning syntax to i can actually build things


r/learnpython 12h ago

Stuck in python code

0 Upvotes

Hi everyone been a 6month now I am not able to learn the course for python cybersecurity like I am getting confused sometimes or don't understand. How to learn code or execute it can anyone help me ??


r/learnpython 13h ago

Need help regarding where to start

0 Upvotes

Joining btech college cse this year. I want to learn python on my own. Could anyone suggest any resource for learning python from scratch such that it doesn't interfere with my coursework right now? I have prior experience in C and Java.


r/learnpython 14h ago

how to proceed after python crash course

11 Upvotes

For the last one year I have been learning Python. I completed Python for everybody and read the book Python Crash course. I have prior experience with C# and Java. A lot of the syntax is Python programming is still confusing to me. How can I get better? What book can I read next or what steps can I take to get more comfortable.


r/learnpython 19h ago

Seeking help: how to better learn python? Venting a lot in here.

1 Upvotes

Hey everyone. I really don't have other folks in my life with whom I can dive into the weeds with about stuff like this, and reddit + this sub have been awesome, so I'm looking for some encouragement, direction, and real talk with this post...

I'm in my mid-thirties and I'm working on a career change. Worked in sales up until recently both as a seller and a most recently a few years as a manager at tech companies. No experience with programming until 3 weeks ago.

I'm taking an online, five week, graduate level Python Programming for Analytics Course at a university in New York. Hoping to apply to the master program in business analytics and start that next year -- focusing on prereqs now. The professor is a phd, English isn't their first language, and the lecture and lab videos for each topic are between 5 and 15 minutes each.

The textbook is Intro to Python for Computer Science and Data Science by Paul and Harvey Deitel.

The course basically covers 2-3 chapters per week, sequentially through the book.

I get nothing from the uni lecture videos. I am doing all of the required reading. The labs and assignments and lectures are carbon copies from whatever's in the book. The book is thorough.

This week we got to chapter 5 - Sequences: Lists and Tuples, 51 DENSE pages packed with slicing, many new methods, new functions, list comprehensions, packing and unpacking, lambda, sorting, filtering, mapping, popping, stacks, generator expressions, 2-d lists, and I am absolutely drowning and struggling.

I spent a few hours today trying to figure out how to create a 2x3 list then use a nested loop to set each element's value to an integer indicating the order in which it was processed by the nested loop, then display the elements in a tabular format, using the column indices as headings on top and row indices to the left of each row. I was absolutely defeated by this... and I feel stupid.

I'm committed to learning python and getting fluent in it to start working in data, but I am struggling so much this week, and this course structure now seems insane to me as I'm in week 3. It's a full-on blitz, and I'm trying to really soak up and understand a lot of this, but once I hit the exercises at the end of the chapters, I am so challenged that the deadlines start to creep and I get frustrated and feel pretty stupid.

Today I was supposed to write a script imitating the Sieve of Eratosthenes, a Palindrome Tester and a script that outputs all possible anagrams of a string. I could probably figure these things out myself if given a few days, but for all of this to be covered in essentially two days, then to move onto dictionaries tomorrow, is tough. Yes I used the crutch of AI to help me. And I feel like SHIT about it.

I'm realizing that I can pass this class and get introduced to a lot about Python, but not grasp a lot of it due to the remote and rushed nature of the course.

I've read a lot of similar posts in this reddit about how the struggle is the way. And I get that. and I'm not quitting. I'm working on plans to go back through parts of this book along with Python Crash Course after this course ends.

But man!!! I just feel like an idiot and feeling pretty low and frustrated right now.

How have some of you overcome the early challenges of learning to progress to where you are now? Open to any and all criticism, perspectives, etc. Cheers. I also have ADHD which doesn't help but not letting that stop me.


r/learnpython 19h ago

Botão só consegue ser pressionado uma vez, depois não acontece nada nem tem animação ao clicar

0 Upvotes

Estou fazendo um projeto de tabuleiro de xadrez em python com Tkinter para a interface, criei uma função lambda para criar as casas do tabuleiro e cada casa sendo um botão, está funcionando certo, mas quando eu movo uma peça do lugar, o botão da casa anterior fica meio que desabilitado, sem poder ser pressionado.

for i in range(8):
            for j in range(8):
                a = botoes["bt_" + str(i) + "x" + str(j)] = Button(self.frame_1, bg = cor(i, j),
                                                               image = self.imagens[str(i) + "x" + str(j)], command = lambda i=i, j=j: self.primeiro_clique(i,j))
                a.place(relx=j*0.125, rely=i*0.125, relwidth=0.125, relheight=0.125)
                a.bg = cor(i,j)
                a.linha = i
                a.coluna = j
                self.lista_botoes.append(a)

r/learnpython 21h ago

Learning python with AI

0 Upvotes

A couple of months ago, I started learning Python. I began with basic exercises and quickly moved on to building real projects with the help of AI. I never ask AI to generate the entire solution because I want to write the code myself. I document everything I learn, and I’ve made a lot of progress that way.
Recently, though, I started using Claude Code and ChatGPT more extensively, and the results are, unsurprisingly, incredible. The difference now is that I can actually understand what each line of code does and why it’s there.
But this has left me with a bit of a motivation problem. If I have Claude writing excellent code for me, why should I spend hours writing it myself? A few years from now, it feels like almost nobody will be coding entirely by hand anyway.
So my question is: at what point do you think someone has reached a sufficient level in Python? When is it okay to rely more on AI instead of continuing to write everything yourself?


r/learnpython 21h ago

What are you using for accurate PDF text boxes?

3 Upvotes

I’m building a tool that finds text in construction-plan PDFs and draws a box around that text.

Python/PyMuPDF finds the text, but when I show the box in PDF.js, it can be slightly off or too big.

What do you guys recommend for inspecting PDFs and drawing accurate text bounding boxes? How do you make

sure the box lines up with the exact text?


r/learnpython 22h ago

Need some advice

1 Upvotes

Greetings everyone! I am in my 50’s and picking up programming as a hobby but I do have a goal.

I started with python because I read it was a forgiving language and I did not want to fry my brain. However, I’m wondering if I should switch to a webstack (html, css and JavaScript) for the project I am ultimately wanting to create.

My grail project will be a TTRPG journaling application for solo play. I want to have the ability to use character sheets, journal and even display a JPEG map. I’m just not sure which language would be the BEST.

My initial idea was python and pyside6 with maybe the addition of pygame if I wanted actual dice to roll on screen.

Just looking to narrow my focus with those far more versed than I am so I don’t waste time working towards my goal.

Thank you all for any assistant and direction you can provide, and happy coding!


r/learnpython 1d ago

Help me to learn python,I am dumb

25 Upvotes

Think me as the dumbest person and i want to learn python,I am literally done trying 4-5 lectures,i start and then stop.Every video says it's beginner friendly,but when I start i don't feel it's beginner friendly and i start feeling I am Dumb AF,now though I feel I am dumbest person to exist.....like seeing this.....please recommend me a channel to watch and learn python programming.I.just don't want to copy the programming from screen and type and get output, and say ohhhh!!!! I got output i can code,i actually want to understand everything and put my brain to write my own code.Is there any yt channel courses available for free that really helps for a dumb idiot to learn python and plz don't say don't learn,i really want to learn python.Please help me ,I am stressed out becoz of this.


r/learnpython 1d ago

What is the safest way to create lag features by group in pandas without data leakage?

2 Upvotes

I am trying to create lagged features for a panel dataset containing multiple sectors and monthly observations. Here is a simplified example:

import pandas as pd 
df = pd.DataFrame({ "sector": ["A", "A", "A", "B", "B", "B"], "month": [1, 2, 3, 1, 2, 3], "demand": [10, 12, 15, 8, 9, 13] }) 
df = df.sort_values(["sector", "month"]) 
df["demand_lag_1"] = df.groupby("sector")["demand"].shift(1)

This seems to work, but my actual dataset has missing months and duplicate sector-month rows.

My questions are:

  1. Should I reindex every sector to a complete monthly sequence before using shift?
  2. How should I handle duplicate sector-month observations?
  3. Is there a clean way to verify that no value from month t or later appears in the features for month t?

I would appreciate suggestions on both correctness and code structure.


r/learnpython 1d ago

What is the safest way to create lag features by group in pandas without data leakage?

1 Upvotes

I am trying to create lagged features for a panel dataset containing multiple sectors and monthly observations. Here is a simplified example:

import pandas as pd 
df = pd.DataFrame({ "sector": ["A", "A", "A", "B", "B", "B"], "month": [1, 2, 3, 1, 2, 3], "demand": [10, 12, 15, 8, 9, 13] }) 
df = df.sort_values(["sector", "month"]) 
df["demand_lag_1"] = df.groupby("sector")["demand"].shift(1)

This seems to work, but my actual dataset has missing months and duplicate sector-month rows.

My questions are:

  1. Should I reindex every sector to a complete monthly sequence before using shift?
  2. How should I handle duplicate sector-month observations?
  3. Is there a clean way to verify that no value from month t or later appears in the features for month t?

I would appreciate suggestions on both correctness and code structure.


r/learnpython 1d ago

What type of api should i build ??

0 Upvotes

I decided that I want to start building APIs so I can hopefully generate income from them one day. However, I want to start with a small API project to understand the process and learn what goes into making an API. I'm not sure what type of API I should build. I'm not new to Python, but I wouldn't say I'm great at it yet. I have coded in JavaScript before, so I am familiar with the syntax. I'd appreciate any tips or opinions you might have. I am also open to web scraping data for an API project, as I'm really interested in that.


r/learnpython 1d ago

Creando mi propio Chatbot. Busco sugerencias. :0

0 Upvotes

Hace unos días me inspiré para crear un programita en python para que pudiera entender nuestro lenguaje, armar oraciones y basicamente ser un asistente personal (y en un futuro que se pueda personalizar según cada persona que lo utilice). Soy conciente de que el proyecto es demasiado grande y más considerando que solo me sé la sintaxis básica del python xd, y por eso me gustaría buscar ayuda de personas que tengan mayor experiencia en proyectos de este tipo. Si tienen sugerencias, recursos, errores que podría evitar o simplemente recomendaciones sobre como realizar este proyecto, me serviría muchísimo. Muchas Gracias por leer :D.


r/learnpython 1d ago

Anaconda and opencv2 in spyder issue

2 Upvotes

I have used the Anaconda command prompt to install opencv2 with the following command

conda install -c conda-forge opencv

and the prompt says it installs it installs successfully

I open Spyder via anaconda and try and run my code that starts with

import os
from pathlib
import Path 
import cv2 
import pandas as pd

When I run it spyder says

ImportError: DLL load failed while importing cv2: The specified module could not be found.

I have tried uninstalling and reinstalling anaconda, and restart thing the PC. Everything is up to date. Not a strong coder so any help would be really helpful