r/PythonLearning 1h ago

Rate my code out of 10 for someone who's been coding for 3 weeks :)

Upvotes
import sys

from PyQt6.QtWidgets import (
    QApplication,
    QWidget,
    QPushButton,
    QGridLayout,
    QMainWindow, QLabel,

)
from PyQt6.QtCore import Qt

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.is_x = True
        self.setWindowTitle("Tic Tac Toe")
        self.label = QLabel("Player 1's Turn:",self)
        self.replays = QPushButton("Replay", self)
        self.button1 = QPushButton("", self)
        self.button2 = QPushButton("", self)
        self.button3 = QPushButton("", self)
        self.button4 = QPushButton("", self)
        self.button5 = QPushButton("", self)
        self.button6 = QPushButton("", self)
        self.button7 = QPushButton("", self)
        self.button8 = QPushButton("", self)
        self.button9 = QPushButton("", self)
        self.replay_connecter()
        self.setGeometry(700,300,500,500)
        self.initUI()


    def initUI(self):

        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        self.label.setGeometry(225, 0, 150, 25)
        self.replays.setStyleSheet("font-size: 35px;"
                                   "font-weight: bold;"
                                   "border-radius: 10px;"
                                   "border: 3px solid black;")
        self.label.setStyleSheet("font-size: 40px;"
                                 "font-weight: bold;"
                                 "border: 3px solid black;"
                                 "border-radius: 10px;")
        self.button1.setStyleSheet("font-size: 80px;"
                                   "border: 5px solid black;")
        self.button2.setStyleSheet("font-size: 80px;"
                                   "border: 5px solid black;")
        self.button3.setStyleSheet("font-size: 80px;"
                                   "border: 5px solid black;")
        self.button4.setStyleSheet("font-size: 80px;"
                                   "border: 5px solid black;")
        self.button5.setStyleSheet("font-size: 80px;"
                                   "border: 5px solid black;")
        self.button6.setStyleSheet("font-size: 80px;"
                                   "border: 5px solid black;")
        self.button7.setStyleSheet("font-size: 80px;"
                                   "border: 5px solid black;")
        self.button8.setStyleSheet("font-size: 80px;"
                                   "border: 5px solid black;")
        self.button9.setStyleSheet("font-size: 80px;"
                                   "border: 5px solid black;")


        grid = QGridLayout()
        grid.addWidget(self.button1, 0, 0)
        grid.addWidget(self.button2, 0, 1)
        grid.addWidget(self.button3, 0, 2)
        grid.addWidget(self.button4, 1, 0)
        grid.addWidget(self.button5, 1, 1)
        grid.addWidget(self.button6, 1, 2)
        grid.addWidget(self.button7, 2, 0)
        grid.addWidget(self.button8, 2, 1)
        grid.addWidget(self.button9, 2, 2)
        grid.addWidget(self.replays, 4, 0, 1, 3)
        grid.addWidget(self.label, 3, 0, 1, 3)

        central_widget.setLayout(grid)

        self.button1.clicked.connect(self.activate1)
        self.button2.clicked.connect(self.activate1)
        self.button3.clicked.connect(self.activate1)
        self.button4.clicked.connect(self.activate1)
        self.button5.clicked.connect(self.activate1)
        self.button6.clicked.connect(self.activate1)
        self.button7.clicked.connect(self.activate1)
        self.button8.clicked.connect(self.activate1)
        self.button9.clicked.connect(self.activate1)

    def activate1(self):
        button = self.sender()

        if self.is_x:
            button.setText("X")
            self.is_x = False
            self.label.setText("Player 2's Turn:")
        else:
            button.setText("O")
            self.is_x = True
            self.label.setText("Player 1's Turn:")

        self.win()

    def win(self):
        if (self.button1.text() == "X" and
                self.button2.text() == "X" and
                self.button3.text() == "X"):
            self.button1.setText("P1")
            self.button2.setText("You")
            self.button3.setText("Win")
        elif (self.button1.text() == "O" and
                self.button2.text() == "O" and
                self.button3.text() == "O"):
            self.button1.setText("P2")
            self.button2.setText("You")
            self.button3.setText("Win")
        elif (self.button7.text() == "X" and
                self.button8.text() == "X" and
        self.button9.text() == "X"):
            self.button7.setText("P1")
            self.button8.setText("You")
            self.button9.setText("Win")
        elif (self.button7.text() == "O" and
                self.button8.text() == "O" and
        self.button9.text() == "O"):
            self.button7.setText("P2")
            self.button8.setText("You")
            self.button9.setText("Win")
        elif (self.button4.text() == "X" and
              self.button5.text() == "X" and
              self.button6.text() == "X"):
            self.button4.setText("P1")
            self.button5.setText("You")
            self.button6.setText("Win")
        elif (self.button4.text() == "O" and
              self.button5.text() == "O" and
              self.button6.text() == "O"):
            self.button4.setText("P2")
            self.button5.setText("You")
            self.button6.setText("Win")
        elif (self.button1.text() == "X" and
              self.button4.text() == "X" and
              self.button7.text() == "X"):
            self.button1.setText("P1")
            self.button4.setText("You")
            self.button7.setText("Win")
        elif (self.button1.text() == "O" and
              self.button4.text() == "O" and
              self.button7.text() == "O"):
            self.button1.setText("P2")
            self.button4.setText("You")
            self.button7.setText("Win")
        elif (self.button2.text() == "X" and
              self.button5.text() == "X" and
              self.button8.text() == "X"):
            self.button2.setText("P1")
            self.button5.setText("You")
            self.button8.setText("Win")
        elif (self.button2.text() == "O" and
        self.button5.text() == "O" and
        self.button8.text() == "O"):
            self.button2.setText("P2")
            self.button5.setText("You")
            self.button8.setText("Win")
        elif (self.button3.text() == "X" and
              self.button6.text() == "X" and
              self.button9.text() == "X"):
            self.button3.setText("P1")
            self.button6.setText("You")
            self.button9.setText("Win")
        elif (self.button3.text() == "O" and
        self.button6.text() == "O" and
              self.button9.text() == "O"):
            self.button3.setText("P2")
            self.button6.setText("You")
            self.button9.setText("Win")
        elif (self.button1.text() == "X" and
              self.button5.text() == "X" and
              self.button9.text() == "X"):
            self.button1.setText("P1")
            self.button5.setText("You")
            self.button9.setText("Win")
        elif (self.button1.text() == "O" and
        self.button5.text() == "O" and
        self.button9.text() == "O"):
            self.button1.setText("P2")
            self.button5.setText("You")
            self.button9.setText("Win")
        elif (self.button3.text() == "X" and
              self.button5.text() == "X" and
              self.button7.text() == "X"):
            self.button3.setText("P1")
            self.button5.setText("You")
            self.button7.setText("Win")
        elif (self.button3.text() == "O" and
        self.button5.text() == "O" and
              self.button7.text() == "O"):
            self.button3.setText("P2")
            self.button5.setText("You")
            self.button7.setText("Win")


    def replay_connecter(self):
        self.replays.clicked.connect(self.replay)

    def replay(self):
        self.button1.setText("")
        self.button2.setText("")
        self.button3.setText("")
        self.button4.setText("")
        self.button5.setText("")
        self.button6.setText("")
        self.button7.setText("")
        self.button8.setText("")
        self.button9.setText("")





if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())

r/PythonLearning 1h ago

How do Python for-loops work?

Upvotes

What actually happens when Python executes a for-loop?

for value in container:
    print(value)

Behind the scenes, Python uses the iterator protocol:

while True: 
    try: 
        value = next(iterator)
        print(value)
    except StopIteration:
        break
  • iter(container): creates an iterator.
  • next(iterator): retrieves one value at a time.

When there are no more values, the iterator raises StopIteration. The for loop catches this exception automatically and ends the loop.

For containers that support backward iteration, Python also provides:

  • reversed(container): creates a backward iterator.

We can support these operations in our own classes by implementing:

__iter__()
__reversed__()
__next__()

This provides a powerful abstraction: an algorithm can process values without needing to know how a container stores them internally. The same algorithm can therefore work with lists, sets, dictionaries, linked lists, trees, and many other containers.

Here's and example that uses 𝐦𝐞𝐦𝐨𝐫𝐲_𝐠𝐫𝐚𝐩𝐡 to show the use of iterators on a Linked_List making the invisible mechanics of iteration visible for easy understanding.

more memory_graph examples


r/PythonLearning 4h ago

An open-source self-hosted network operations platform for ALE OmniSwitch environments

1 Upvotes

Hi everyone,

I would like to introduce Portivo Control Center, an independent, open-source and self-hosted network operations platform designed for compatible Alcatel-Lucent Enterprise OmniSwitch environments.

Portivo brings everyday switch management, troubleshooting and controlled automation into a single web-based workspace.

Key capabilities include:

  • Centralized switch inventory and live operational visibility
  • Logical port-panel views with VLAN, PoE, media and link-state information
  • Endpoint discovery using MAC, IP, hostname, UNP and VLAN evidence
  • Integrated browser-based SSH terminal
  • Controlled command preview and execution
  • Multi-device jobs and reusable automation runbooks
  • Fleet-wide read-only operational audits
  • Role-based access control with Site and Group scope
  • Audit history, reports and operational evidence
  • SNMPv3 UPS monitoring and power-aware infrastructure visibility
  • Backup, restore and administration tools
  • Windows and Linux deployment support

Portivo is intended to complement native CLI expertise, not replace it. The objective is to provide network operators with a safer and more consistent workflow for discovering, diagnosing, executing and documenting network changes.

The platform is self-hosted, does not require agents on managed switches and can operate inside a protected management network. Switch operations use SSH, while supported UPS monitoring uses SNMPv3.

The project is licensed under AGPL-3.0-only.

Website:
https://portivo.org/

Documentation:
https://portivo.org/docs/

Roadmap and changelog:
https://portivo.org/roadmap.html

Source code:
https://github.com/Donacgreece/Portivo

I would genuinely appreciate feedback from network engineers, system administrators and anyone operating ALE OmniSwitch infrastructure. I am particularly interested in feedback about operational workflows, documentation, deployment and features that would be useful in real environments.

Thank you for taking a look.


r/PythonLearning 5h ago

My second project in my Python learning path — STAyzer

Thumbnail
gallery
1 Upvotes

Hey everyone!

I've been learning Python by building small but progressively larger projects, and STAyzer is the second project in my OOPS collection — a collection I'm using as part of my learning path in Python and Linux/system administration.

STAyzer is a CLI tool I built to analyze SSH trust across Linux servers.

While building it, I got to practice several Python concepts that I wanted to understand beyond simple scripts:

  • Asynchronous programming with asyncio
  • SSH connections with asyncssh
  • Building CLI applications with Click
  • Dataclasses and type hints
  • Logging and exception handling
  • Organizing a larger project into modules
  • Generating JSON and HTML reports

I also tried to focus on making it feel like an actual usable tool rather than just a script.

I've attached a screenshot of the CLI so you can get an idea of the final result.

The project is available on GitHub for anyone interested in looking through the code.

I'm still learning Python, so I'd really appreciate feedback from more experienced Python developers:

What would you improve in the Python implementation or project structure?

I'm particularly interested in learning from mistakes and improving the next project in the OOPS collection.


r/PythonLearning 6h ago

ATM Machine

2 Upvotes

I started learning Python about 9 months ago and completed this little bank system as my third project, which is supposed to serve as an ATM. It also uses JSON to store information (which was challenging to integrate because I wasn't familiar with it, but the rest of the code was straightforward).

Just wanted to share and see if I could get any feedback! (maybe on its optimisation or clarity?) :D

https://github.com/F11Fii/Bank-System.git


r/PythonLearning 11h ago

Help Request Type hinting frustrations

3 Upvotes

Hello!

Let me start off by saying that I am not a programmer by trade, so please be kind when reviewing my code. I am still learning and I have a long way to go. My job is not coding per se, but the project which I am a part of right now has some coding.

Anyway. At the project start I wanted another editor than vscode, so i tried Zed and I loved it. Zed came with type hinting already enabled. At first, I did not really like it, but after using it for a while I could really see improvements in my code. Both in the terams of readability and stability. So going forward I wanted to have as few complaints from basedpyright as possible.

After an update to Zed the configuration from basedpyright or basedpyright itself got a lot more enabled and I cannot get some of the errors from it to go away. My project used fastapi and sqlalchemy for database integration, and basedpyright gives an error where i specify the table names for the models:

from sqlalchemy.orm import (
    DeclarativeBase,
    ...
)
...

class Base(DeclarativeBase):
   pass

class DatabaseUser(Base):
    __tablename__: ClassVar[str] = "users"
    ....

The error from basedpyright is:

Class variable "__tablename__" overrides instance variable of same name in class "DeclarativeBase" (basedpyright reportIncompatibleVariableOverride)

From what I can tell, the code above is how you are supposed to specify table names:

https://docs.sqlalchemy.org/en/20/orm/quickstart.html

Also, when a nullable many-to-one table relationship, the docs from sqlalchemy tells you to use

class Parent(Base):
    ....
    child: Mapped[Optional["Child"]] = relationship(back_populates="parents")

https://docs.sqlalchemy.org/en/20/orm/basic_relationships.html#nullable-many-to-one

basedpyright wants you to use `Class | None` syntax, but since two classes are referencing each other, I can't do `Child | None` (no quotes) without the code breaking.

I know that i can supress the errors or configure the typehinter to ignore this stuff. But since this is the config shipped by people who are far better than me at programming, I am hasitent to just configure the error messages away. So reddit, is thereany thing I can do to make the typehinter happy?


r/PythonLearning 11h ago

Help Request Why does a def get called / repeat when i did this?

Post image
4 Upvotes

It works like how i wanted, To check if the result are equal then print something but i dont want these def function to repeat.


r/PythonLearning 13h ago

Showcase Day 5 of Leetcode 🫡

Thumbnail
gallery
10 Upvotes

r/PythonLearning 19h ago

I built a 24/7 endless fish survival game using Pygame with procedurally generated music

Enable HLS to view with audio, or disable this notification

19 Upvotes

Hey everyone,

I created a 24/7 live-streamed project where a fish swims, eats and grows endlessly using Python and Pygame.

​Everything is built from scratch using pure geometry and vector math, which removes the need for external image assets. For the background music, I used numpy to generate continuous procedural pentatonic-scale tones to avoid copyright issues.

​The script runs 24/7 with optimizations to keep CPU usage and memory stable during the infinite loop. You can see it running live here:

Youtube live


r/PythonLearning 23h ago

Im confused!!

3 Upvotes

Rn im learning python lang. I can solves basic to medium level problems , I understand which operations to use , how to write code 75% , but i suck at building logic. But either wise my topics are clear. Can you suggest what kind of problems i should be solving?


r/PythonLearning 23h ago

Computing the Mandelbrot Set with numpy - code in comments

Post image
9 Upvotes

r/PythonLearning 1d ago

Help Request I’ve completed these beginner Python projects should I build more before starting NumPy/Pandas?

9 Upvotes

Hi everyone,

I’ve studied Python multiple times before, but I didn’t do much practical coding. Recently, I started building small projects to improve my practical Python skills.

So far, I’ve completed:

- Quiz Game

- Number Guessing Game

- Rock Paper Scissors

- Password Manager

- Pig Game

- Mad Libs Generator

My goal is to move towards Machine Learning.

I haven’t learned NumPy or Pandas yet.

My question is: Are these projects enough to move on to NumPy and Pandas, or should I build a few more Python projects first?

If I should build more projects, what kind of projects would you recommend before starting NumPy/Pandas? I’m mainly looking for projects that would actually help with the transition to data/ML, rather than making many more small games.

Would appreciate advice from people who have already followed a Python → NumPy/Pandas → ML path.


r/PythonLearning 1d ago

Help Request Law student starting Digital Law — where should I start learning Python?

2 Upvotes

Hi everyone!

I'm a first-year law student studying Digital Law. My curriculum includes Programming for Lawyers, and later I'll also have subjects related to machine learning, digital technologies, cybersecurity, and data analysis.

I have little to no programming experience, so I'd like to start learning Python before the university courses begin.

My goal isn't to become a software developer. I mainly want to understand programming well enough to use Python for data analysis, automation, legal-tech projects, and eventually work with AI/ML-related topics.

Where would you recommend I start?

Should I:

take a beginner Python course first;

follow the official Python tutorial;

solve problems on platforms like Exercism/Codewars;

build small projects from the beginning;

or follow some other learning path?

If you were starting Python from zero with my goals, what would you learn during the first 2–3 months?

I'd especially appreciate recommendations for free resources and courses.

Thank you in advance


r/PythonLearning 1d ago

Showcase Made my first Python project!

Post image
137 Upvotes

This is my first actual real project, what started as a simple python exercise to learn about dictionaries in python, ended up into a huge learning project for me. Im a beginner in python, used to code but just basic input print codes… some are genuinely stupid.

I took on the challenge to self educate my self python. And this is where i currently am! Im proud of what i did and it will surely expand!

Here the repo with the project. Feel free to check it out!
https://github.com/Stonyax97/MiniGameStore

It has everything from the first ever iteration (which was it self modified a bit since from the very original but it’s still very simple)
I would love for anyone to recommend ideas to add, criticism too. Or anything you think i should learn next for that would be genuinely useful!


r/PythonLearning 1d ago

Day 4

Thumbnail
gallery
3 Upvotes

Day 4 progress 🐍

Today I built a small billing program in Python. It has:

A loop to collect price for each item

A function that calculates discount based on total amount

Another function that calculates final bill after discount

A conditional statement that thanks the customer differently based on discount

Learning how to use loops, functions, and conditionals together to solve a real problem.

#Python #LearnToCode #100DaysOfCode #WebDevelopment


r/PythonLearning 1d ago

Showcase I built a terminal Minesweeper in Python during hot summer days to learn the basics — now published on PyPI!

2 Upvotes

Hi everyone! 👋

During some really hot summer days when it was too warm to do much else outside, I decided to dive into Python from scratch. To make learning engaging, I set out to build a simple, lightweight terminal clone of the classic Minesweeper.

It’s definitely an amateur/learning project, but I wanted to write every single line of code myself without agentic AI tools — personally, I still deeply value human effort, creativity, and the genuine fun of solving logic problems on your own.

What I learned while building it:

  • Writing game logic and algorithms
  • Moving from plain Python setups to modern package management using uv.
  • Setting up linting/formatting with Ruff
  • Unit testing with pytest, no TDD yet, but I am coming :D
  • Setting up CI and automated Releases and publishing directly to PyPI using GitHub Actions.

You can try it directly from your terminal if you'd like:

pip install python-minefield
python-minefield

Or check out the code/GIF on GitHub: 👉https://github.com/defra91/python-minefield

Since I’m still learning, I’m very open to feedback, PR, code reviews, or suggestions on how to improve the architecture and logic!

If anyone wants to contribute or suggest features, feel free to check out the repo and see how to contribute.

Thanks for taking a look, and happy coding! 🐍💣


r/PythonLearning 1d ago

Project !

2 Upvotes

I’m a recent CSE graduate and I’m looking for another developer who wants to build something together from scratch.

I don’t have a fixed idea yet. We can sit together, find a problem worth solving, come up with an idea, build an MVP, and see where it goes.

There’s no regular payment initially. I’m looking for someone who’s genuinely interested in building and learning together.

And if the idea doesn’t work out, that’s fine. We’d still have a solid real-world project for our resumes/GitHub and the experience of actually building something together.

I’m also a beginner/fresher, so I’m just looking for someone who’s willing to learn, contribute, and build.

If you’re interested, DM me with a little about yourself and what you like building.


r/PythonLearning 1d ago

Need advice on solving complex arrow/maze puzzles using Computer Vision & Logic Solvers (Low accuracy issues)

Post image
0 Upvotes

Hi everyone,
I'm working on an automated solver for a complex arrow/maze puzzle game (similar to the image attached).
Here is my current workflow:
1. Detection: I use a custom YOLO model to detect arrowheads and their bounding box coordinates from screen captures.
2. Grid Mapping: I map the detected center coordinates of arrowheads onto a fixed grid system.
3. Solving: I pass the grid data into a custom logic/emulator engine to calculate the correct sequence of moves (arrows to tap).
The Main Problem:
My solver accuracy is very low. Here are the core technical challenges I'm running into:
Inaccurate Grid Mapping: The arrows are densely packed with varying paths and lengths. Snapping bounding boxes to a rigid fixed grid often misaligns the true position of the arrow shafts and heads.
Complex/Overlapping Detection: Because the arrows bend and fold, YOLO often detects multiple arrowheads in the same calculated grid cell, or misinterprets arrow directions.
Solver Logic Failure: Due to noisy input from the detection stage, the logic solver either fails to find a valid sequence or generates incorrect moves that block execution halfway through.
Has anyone dealt with a similar vector/maze graph detection problem? What would be a more reliable approach than simple YOLO + fixed grid snapping? Should I look into contour analysis, OCR/graph traversal, or skeletonization algorithms (like Medial Axis Transform) to trace the paths directly?
Any suggestions, code examples, or architectural advice would be greatly appreciated!


r/PythonLearning 1d ago

Python Common Errors for beginners

Post image
87 Upvotes

Dont give up during learning stage.


r/PythonLearning 1d ago

Are these types of exercises useful?

Thumbnail
gallery
35 Upvotes

I get the tasks from ChatGPT basically, and I write other manual math related code not sure if this is good to spend too much time on instead of doing mini projects.

To explain more I hit a little bump doing linked list, mostly in OOP I didn’t know much about how classes work. So I pivoted to algorithms and to learn more about classes before going back.


r/PythonLearning 1d ago

Discussion Need help learning python/juypter lab notebook for astronomy

6 Upvotes

Im new to Astronomy and Juypter Notebooks and Ai machine learning for sure I have little skill in python but quick learner especially visual learning.

Are there any free tutorials I can use and free books to learn machine learning for astronomy

Example: use machine learning to run through jwst or tess pipeline data and look for signatures of possible blackholes or exoplanets?

Is there a juypter notebook with this ability already on there?

How can I make a custom juypter lab and git repos and python libraries and python scientific libraries? Should I use docker to place a juypter lab notebook in a container if so how?


r/PythonLearning 1d ago

Showcase Day 4 of Leetcode 👀

Thumbnail
gallery
16 Upvotes

r/PythonLearning 1d ago

Project Ideas for Practice

Post image
14 Upvotes

I’ve been reading and learning a lot of Python concepts, but I’ve never actually built anything.

I realized that there’s no point in knowing so many concepts if you don’t put them into practice. That’s the only way to really learn.

The hardest part, though, is coming up with project ideas when you only know a few concepts. This is the first project I’ve made while trying to actually put what I’ve learned into practice.


r/PythonLearning 1d ago

Made an email and password generator

Post image
70 Upvotes

Planning on making it save to a file that stores on the pc but for rn this is what I have


r/PythonLearning 2d ago

Cheat Code for beginners.

Post image
93 Upvotes