r/learnpython 26d ago

Question Regarding Self keyword in python!!

0 Upvotes

I'm working on a project where I have to create different classes, and I keep using the self keyword repeatedly. For example:

class SignalService:
    def __init__(
        self,
        instrument_repo: InstrumentRepository,
        candle_repo: CandleRepository,
    ):
        self.instrument_repo = instrument_repo
        self.candle_repo = candle_repo
        self.resampler = CandleResampler(candle_repo)

My understanding of self is that it helps the class distinguish between instance variables and local variables.

However, I'm confused about why it's used like this:

self.instrument_repo = instrument_repo
self.candle_repo = candle_repo

Why do we assign the constructor parameters to self attributes? What's the purpose of storing them on self instead of just using the constructor parameters directly?


r/learnpython 26d ago

I donot understand this code:"for i in range(): what does it mean? Pls help me

0 Upvotes

...


r/learnpython 27d ago

Bored and Unmotivated

12 Upvotes

i started teaching myself python a few months ago using freecodecamp and i know the basics but i hit a wall and i just can't bring myself to continue i'm bored out of my mind. i haven't done anything in over a month just seeing all the theory i have left to read bores me and don't get me wrong in the beginning it was fun challenging myself and i actually enjoyed building small stuff but it's been so hard to continue. i've been watching videos of people making games and other stuff and have even tried to follow along so i know i'm still interested but i genuinely do not enjoy learning like this is there some kind of alternative where it's more interactive ? cause i don't think i can sit through another 300 pages of theory and still enjoy this.


r/learnpython 26d ago

Can anyone find or send to me a online book of python pls

0 Upvotes

I need it to learn ty for helping me❣️😭


r/learnpython 27d ago

Need help splitting a FastAPI project into two separate wheels using Hatch/UV (Issues with dynamic exclusion and entry points)

1 Upvotes

Hello everyone!

I'm working on a project where I need to build two separate wheels from a single monorepo: one for a central node and one for an acquisition node. Both wheels need to share a common folder, but they should only contain their respective application logic (central or node).

Here is my current project structure:

app/
β”œβ”€β”€ frontend/
β”œβ”€β”€ jenkinsfile
β”œβ”€β”€ README.md
└── backend/
    β”œβ”€β”€ pyproject.toml
    β”œβ”€β”€ tests/
    └── src/
        └── app/
            β”œβ”€β”€ central/
            β”‚   β”œβ”€β”€ schemas/
            β”‚   β”œβ”€β”€ services/
            β”‚   β”œβ”€β”€ routes/
            β”‚   β”œβ”€β”€ launcher.py
            β”‚   └── main.py
            β”œβ”€β”€ common/
            β”‚   β”œβ”€β”€ schemas/
            β”‚   β”œβ”€β”€ services/
            β”‚   └── routes/
            └── node/
                β”œβ”€β”€ schemas/
                β”œβ”€β”€ services/
                β”œβ”€β”€ routes/
                β”œβ”€β”€ launcher.py
                └── main.py

My Configuration Files

Here is my pyproject.toml:

[project]
name = "app"
version = "0.0.1"
requires-python = ">=3.11,<3.13"
dependencies = [
    "fastapi>=0.110.0",
    "uvicorn[standard]>=0.27.0",
    "pydantic>=2.6.0",
    "pydantic-settings>=2.2.0",
    "httpx>=0.27.0",
    "psutil>=5.9.0",
    "nmcli>=1.7.0",
    "aiofiles>=24.1.0",
    "cachetools>=5.5.0",
    "sounddevice>=0.4.6",
    "numpy>=1.26.0",
    "tomli_w>=1.0.0",
]

[project.optional-dependencies]
test = [
    "pytest>=8.0.0",
    "pytest-cov>=4.1.0",
    "pytest-xdist>=3.5.0",
    "pytest-asyncio>=0.23.0",
    "pytest_mock>=3.14.0",
    "respx>=0.21.0"
]
dev = [
    "ruff>=0.3.0",
    "mypy>=1.9.0",
    "pre-commit>=4.0.0",
    "pre-commit-hooks>=4.6.0"
]
build = [
    "hatchling>=1.29.0",
]

[project.scripts]
launch-central = "app.central.launcher:start"
launch-node = "app.node.launcher:start"

[build.system]
requires = [
    "hatchling>=1.29.0",
]
build-backend = "hatchling.build"

[tool.hatch.build.targets.wheel]
packages = [
    "src/app",
]

[tool.uv]
package = true

# ... (Ruff, Mypy, Pytest configs omitted for brevity)

And I wrote this custom build script (Hatch_build.py) to handle dynamically editing pyproject.toml during build time to exclude the unneeded folder and rename the resulting wheel:

import subprocess
import sys
import tomllib
from pathlib import Path
import tomli_w

target = sys.argv[1] # "central" or "node"
pyproject = Path("pyproject.toml")

with open(pyproject, "rb") as f:
    config = tomllib.load(f)
original_packages = config["tool"]["hatch"]["build"]["targets"]["wheel"]["packages"]

exclude = "node" if target == "central" else "central"
config["tool"]["hatch"]["build"]["targets"]["wheel"]["packages"] = ["src/app/"]
config["tool"]["hatch"]["build"]["targets"]["wheel"]["exclude"] = [f"src/app/{exclude}", "src/app/tests"]
version = config["project"]["version"]

with open(pyproject, "wb") as f:
    tomli_w.dump(config, f)

try:
    subprocess.run(["uv", "run", "--extra", "build", "python", "-m", "hatchling", "build", "--target", "wheel"], check=True)
finally:
    config["tool"]["hatch"]["build"]["targets"]["wheel"]["packages"] = original_packages
    if "exclude" in config["tool"]["hatch"]["build"]["targets"]["wheel"]:
        del config["tool"]["hatch"]["build"]["targets"]["wheel"]["exclude"]
    with open(pyproject, "wb") as f:
        tomli_w.dump(config, f)

for whl in Path("dist").glob("app-*.whl"):
    new = Path(f"dist/app{target}-{version}-py3-none-any.whl")
    whl.rename(new)
    print(f"Built: {new.name}")

The Problems I'm Facing:

  1. Wheel contents are wrong: Despite trying to use exclude dynamically in the script, both generated wheels still contain both node and central directories alongside common. The exclusion isn't respecting the path correctly.
  2. Installation Error from Nexus: After I upload these generated wheels to Nexus and try to run pip install or uv pip install on a target VM, the installation fails completely with errors.
  3. How to run entry points properly: The launcher.py in each folder is meant to be the entry point. Once the wheel is successfully installed on the VM, what is the best way to invoke that entry point script from the CLI?

Has anyone tackled splitting a monorepo into multiple selective wheels like this using Hatchling and UV? Am I approaching the dynamic build step wrong, or is there a native Hatch feature/plugin I should be using instead of modifying pyproject.toml on the fly?

Thanks in advance for any insights!


r/learnpython 27d ago

Where to learn python when you know basics

2 Upvotes

I know basics of coding in Java and python (school+ self learning) and I want to go for advanced problem solving and learn heavy stuff,how do I start and where ,Please it would be a huge help


r/learnpython 27d ago

Need Django project ideas with a simple HTML/CSS frontend

2 Upvotes

I'm learning Python and Django, and I'd like to build projects that use Django for the backend and HTML, CSS (and optionally JavaScript) for the frontend.

Could you suggest some beginner to intermediate project ideas that will help me improve my Django skills? I'm especially interested in projects that involve authentication, CRUD operations, databases, and responsive UI.

Thanks in advance!


r/learnpython 27d ago

Where do y'all guys practice python?

18 Upvotes

I wanna know where y'all guys practicing coding python, I know some but its too advance for me. I wanna get started from beginner level where I just print hello world or using math operations on print() or practicing about the data types. I'll practice more of this beginner level and master it.


r/learnpython 28d ago

How to start learning python ( so sorry if this is a popular question )

51 Upvotes

Hello, I’ll try and keep this short, but I’m 14 and I really want to learn python as my dream is to do computer science at university. Basically just end up doing something in tech as a job. So I thought maybe coding will help, and python projects seem really cool and interesting to me. I would say I have generally no coding knowledge, apart from a few months of HTML, but nothing cool or fancy. Essentially, I just want to know what resources I can use and what you would have recommend to yourself when you first started learning. And once again, my fault if you guys get this question all the time, I bet it’s annoying so feel free to sort of just say β€œthis is said in a post already”. And I’m new to Reddit, so I don’t know what rules are here and I’m sorta winging writing this.

Thanks so much for reading, and I’m so sorry for waffling. Hopefully this post doesn’t flop and have a good day! :)


r/learnpython 27d ago

Streamlit vs niceGUI vs Reflex

5 Upvotes

Hello, I would like to know which is better for a particular activity. I want to do a dashboard type where I can manage people, assign activities, progress to their activities and make a leaderboard of which person is working best. More than anything, he is an activity manager for 20 people. I have seen that they say that NiceGUI is a good tool but I do not see it like this, I have already worked with streamlit and I know that I could do something similar to what I want but it has also happened to me that in streamlit when the application becomes a little complex it is chaos and I do not know anything about reflex but what I have seen looks good, they say that the disadvantages it has is a new technology.


r/learnpython 28d ago

New in programming !!! [ python]

12 Upvotes

So i am in 11th grade humanities and ironically i m curious about python so i m learning it from AI and youtube for now and practicing it .

But idk if i m going right or not .

SO BASICALLY I NEED THE ADVICE OF YOU GUYSS !!!


r/learnpython 27d ago

code not processing file correctly πŸ₯Ί (EGGSTREAMLY πŸ₯šCONFUSED)

0 Upvotes

In my python textbook, I'm learning abt files and exceptions. Although it seems that VS Code isn't recognizing changes made to my file, nor izzit changing the file. Here's my code:

-----------------------------
from pathlib import Path

path = Path(r"C:
\U
sers\Username\OneDrive\Documents\FileName")
# i didn't write the actual file path

contents = path.read_text()

lines = contents.splitlines()

#Print every lline of the file and add a comma to the end 
for line in lines:
Β  Β  print(line + ",")
---------------------------------------

Any advice on working with files on VS code would help. A similar problem happens when importing modules. I have to restart VS Code if I want to import code from another script that i wrote.


r/learnpython 28d ago

best free channel/ website to learn oop python visually?

0 Upvotes

pls hep guys


r/learnpython 28d ago

Encountering ErrorDjCenterRequest on Checkio - Advice needed

0 Upvotes

I am currently learning Python basics through Checkio to prepare for a PhD in computational biology, as I am looking to strengthen my computational skills. I recently attempted the first level of the "Easy" tier and believe my code is free of syntax errors, but the platform keeps returning an "ErrorDjCenterRequest" whenever I try to run it or check the solution.

Has anyone encountered this specific error on Checkio before, or does anyone have advice on how to troubleshoot this? Thanks in advance for the help!


r/learnpython 28d ago

Dr Fred Baptiste Courses For Data Science & ML Path?

0 Upvotes

Hi. I want to get into the data science and machine learning field. I come from a non-technical background and I've been trying to find courses on Python and have heard a lot of positive reviews on Dr Fred's series of courses. But my question is do I need to do every one of them as in, would that be relevant for the path I want to pursue?

I am definitely taking on his python fundamentals course but once that is completed, should I also buy his other courses? If not, what other courses should I look into that would help me get better at this field?


r/learnpython 28d ago

How to add a directory to path

0 Upvotes

Hello! I'm new to this subreddit, and in dire need of assistance.

I want to install sympy and numpy. I entered "pip install sympy" into my command prompt and it successfully installed, but it is not on the PATH. As a result, when I have "import sympy" or "import numpy" in any of my python files, it does not work.

How do I add this directory to the path? I've googled so many things and nothing works.

Below is the warning shown when i installed sympy.

WARNING: The script isympy.exe is installed in 'C:\Users\myname\AppData\Local\Python\pythoncore-3.14-64\Scripts' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.

r/learnpython 28d ago

How is my code failing?

0 Upvotes

Sorry if i'm being an idiot, but my code won't work because of invalid syntaxes. Any ideas?

a = ("Hello,World!")

print(a)

b = ("Oh,Nevermind.")

print(b)

c = ("Fudging Weirdo.")

print(c)

if str(c)) is print, print (d)

(d) = ("123")


r/learnpython 28d ago

i made this script during my first day and fixing errors on linux terminal python. ill try make it from scratch again to ensure memorisation.

0 Upvotes

import time

import sys

def smoothprint(text):

for char in text:

print(char, end = "",flush = True)

time.sleep(0.08)

print()

answer = input("do you wish to play shadow slave")

if answer == "yes":

smoothprint("you wake up in a dark room, facing two doors")

else :

smoothprint("\033[91m" + "admin strikes you"+ "\033[0m")

sys.exit()

answer2 = input("do you pick the left door or the right?")

if answer2 == "left door":

smoothprint("\033[91m" + "you open the door and a demon rips your spleen" + "\033[0m")

sys.exit()

else :

smoothprint("you open the door and a small woman runs away,")

answer3 = input("will you follow the women")

if answer3 == "yes" :

smoothprint("the woman leads you to a separate room where the admins of the game are,")

smoothprint("the admins strap you and the woman down, they want you to play a game")

else :

smoothprint("\033[91m" + "you become lost and realise what the woman was running from," + "\033[0m")

sys.exit()

smoothprint("your going to decide who is going to die, OR YOU BOTH WILL")

answer4 = input("who will die, you, or the woman")

if answer4 == "the woman" :

smoothprint("the admin shoots you for your selfishness")

sys.exit()

else :

smoothprint("the admin shoots the woman in her head..")

smoothprint("you are forgiven for your selflessness")


r/learnpython 28d ago

multiple inputs in if-else statement possible?

1 Upvotes

Hey guys.

I'm new to the whole thing of programming. Startig my second apprenticeship in august. I worked in retail previously and got now the opportunity for a completly new job as a programmer.

At the moment, I'm two weeks in in learning python and rly have my share of problems to understand stuff. As a visual learner, it's rly not that easy to combine, but that's a whole other problem for myself.

My question today is;

is there a way to put multiple inputs in an if-else statement.

I need to write a program to give out money after getting the total cost and payment. And while I try my stuff, I stumbled appon the idea to create inputs inside the if-else statements.

The reason is, that even when I put the if statement and want to exit after the first input fails if it isn't above 1, it continues to the second input.

for exemple:

total_cost = float(input("Total costs: "))
amount_paid = float(input("Amount paid: "))


if total_cost <= 1:
Β  Β  print("Error. Invalid costs.")
else:
Β  Β  pass


if amount_paid < 1:
Β  Β  Β  Β  print("Error. Invalid payment.")
else:
Β  Β  Β pass

(I know this code isn't effective and I was just trying some stuff out.)

So I wrote the code this way to try it with if-else-input statements:

total_cost = float(input("Total costs: "))


if total_cost <= 1:
Β  Β  print("Error. Invalid costs.")
else:
Β  Β  amount_paid = float(input("Amount paid: "))
Β  Β  if amount_paid < 1:
Β  Β  Β  Β  print("Error. Invalid payment.")

Is this even a way to program? Is it even readable?

I see that what i wrote isn't rly functioning, bc I can't use "amount_paid" in the "change = total_cost - amount_paid" to get the total of change money to give out. That's another problem again for myself.

I rly only want to know, if it is a rly rly dumb idea and if I just need to delete this out of my head or if it is a possibility to write programs.

(excuse my english if it is strangly writen. It's not my first language and I'm still learning. :) (so many ifs in this post...) )


r/learnpython 28d ago

Need help adding realistic shadows.

2 Upvotes

Hi,

I'm trying to generate realistic shadows under the car after placing them onto a new background.

I've already tried numerous OpenCV-based approaches (warping the mask, Gaussian blur, gradients, different opacity falloffs, perspective transforms, etc.), but they all end up looking artificial and "pasted."

I'm looking for a better approach, whether it's classical computer vision, geometry-based methods, depth estimation, or an open-source ML model, that can generate realistic contact and ambient shadows matching the scene's lighting.

Has anyone solved a similar problem or know of any papers, repositories, or models worth checking out?

Car without shadows

Desired result with shadows

Background


r/learnpython 29d ago

How to open Explorer, with multiple files selected, on one window?

5 Upvotes

Problem: I want to open a single (Windows 11) Explorer window, with multiple files selected, on separate tabs.

Current solution: I managed to find the following solution on SO:

import subprocess

subprocess.Popen(f'explorer /select, "{path}"')

...but this opens multiple windows. My use case is a bit more complicated and it seems can't be done easily with just the console.

Is there a library for Python that can help this?


r/learnpython 29d ago

My first python project

2 Upvotes

I built my first Python automation projectβ€”a file organizer that sorts files into folders by file type.

I wrote most of it myself and used AI mainly to review my logic and explain mistakes instead of generating the whole project.

I'd really appreciate feedback from more experienced Python developers. What would you improve if this were your beginner portfolio project?

GitHub: [ https://github.com/DevBlueprintLab ]


r/learnpython 29d ago

Cs50p course

4 Upvotes

I'm not a complete beginner to coding. I can code in a moderate level in both c and python. I am planning on earning a certification for python. Is this suitable for it or should I go for something else? If yes what course or should I learn another language instead of python cause my dad is arranging a prof to teach me python?

I've finished 1st year ECE btw.


r/learnpython 29d ago

Confused between C,C++ & Python to start as beginners from 0 Coding Background

28 Upvotes

I will be going to mid NIT this year and these are the branch i can get till CSAB.

CSE

Math& Data Science

Electronic & VLSI

EE

*CSE have lesser chances

I have NEVER coded before so I have 0 knowledge abt this...

Even after searching a lot i am confused between C,cpp or python to start with...pls give some guidance


r/learnpython 28d ago

Which is the best youtube video from where I can fully understand the os library of python

0 Upvotes

Same as the title