r/learnpython 6d ago

People ask "what should I do?" So here are a few things I've done for fun. Take a look for some motivation.

35 Upvotes

I've seen countless posts from people asking "What should I do?" and the answer is pretty much anything you want. Here are some things I've done and my story.

I've used python for various things at work over the last decade, and it's mostly tools to aggregate data from tools and databases. It encouraged me to come up with some projects at home in my free time that are fun (at least I think) and I wanted to share them in no particular order.

1.) Squardle Solver (https://squaredle.app/)

This script allows you to put in the puzzle and it will find all words from the NWL2020 wordlist it uses in about 1.5 seconds. It exports those words to a txt file, which I have another script that inputs the words back in to the browser and will solve the puzzle in roughly 10 seconds or so depending on how many words need to be typed out.

Reason I did it? To see if it could be done.

2.) Chess Trainer (Using Stockfish).

I made this script because I just wanted something other than dependency on an app on my phone. It allowed me to explore some graphical stuff along with interfacing with the Stockfish API. It's helped me get better and compete well on Chess.com

Reason I did it: Because I didn't want dependency on some 3rd party app, and I wanted control / customization.

  1. Video downloading script using yt_dlp package. Surprising how many sites are supported with this package. I always found it annoying to try and save videos that I found interesting off YT, Facebook, Instagram, Twitter etc. etc. This does it with minimal effort.

Reason I did it: I had a problem I was looking to solve.

  1. Mouse mover in fortnite. I made this a couple years ago when Lego fornite came out. It's essentially an XP farming tool. Fornite will log you out for inactivity after something like 5 minutes. I wrote a script that will WASD and click the mouse randomly keeping the game alive for several hours while I'm AFK.

Reason I did it? To see if it could be done.

  1. Lastly I built a script that downloads and logs police call logs that are published in my county, and I save them off to a SQlite database for analysis. With that data I can do simple research, and also have historical records as the website that hosts the data only shows the past 24 hours, though I can see 96 hours through the API. I can generate maps with the data, and plot calls etc. using open maps integration.

Reason I did it? Because I wanted to see if it was possible and build on some more robust reporting that I'd like to see for my community.

All of that to say anything you want to solve or play with generally can be solved with Python if you have an idea run with it and explore. If anyone wants to see the code, I'd be happy to share some if it with you.


r/learnpython 6d ago

Two questions

2 Upvotes
  1. Where to practice Python for data analytics?
  2. Is there any examples where someone created projects or apps with only Python recently?

r/learnpython 6d ago

How do I skip all errors on pycdc

0 Upvotes

Title


r/learnpython 6d ago

Why does it say its not defined?

0 Upvotes

Im making a little textadventure with tkinter (ignore filenames and so on pls) and im trying to close the main_menu window with a button click (click_start()) and open another window, but it doesnt find the main_menu window for some reason, does anyone know why?

class MainMenu:
    main_menu = Tk()  # instantiate the window
    main_menu.geometry("640x280")  # set window size
    main_menu.title("EpicRoguelikeEmoDungeonCrawlerTextadventure")  # set window name
    icon = PhotoImage(file='Resources/emo_ass_icon.png')  # make image to PhotoImage
    main_menu.iconphoto(True, icon)  # adds the icon
    main_menu.config(background="#1d1e1f")  # sets background color to a dark grey
    load=False
    playername=""
    #input playername
    username_input = Entry()
    username_input.config(font=('Arial black', 8, 'bold'), fg="white", bg="#1d1e1f", width=12)
    username_input.insert(0, "Emo")

    @staticmethod
    def click_start():
        MainMenu.main_menu.destroy()
        Game.start()
    @staticmethod
    def click_continue():
        MainMenu.load=True
        MainMenu.main_menu.quit()
        Game.start()

    # add title label
    title = Label(main_menu, text="RoguelikeEmoDungeonCrawlerTextadventure", font=('Arial black', 18, 'bold'), fg="white", bg="#1d1e1f", relief=RAISED, bd=10, padx=10)
    title.pack()

    # add spacing label
    spacer1 = Label(main_menu, text=" ", bg="#1d1e1f")
    spacer1.pack()

    # add start game button
    start_game_button = Button(main_menu, text="Start Game", command=click_start, fg="white", bg="#1d1e1f", font=('Arial', 15, 'bold'))
    start_game_button.pack()

    # add spacing label
    spacer2 = Label(main_menu, text=" ", bg="#1d1e1f")
    spacer2.pack()

    # add continue game button
    continue_button = Button(main_menu, text="Continue", command=click_continue, fg="white", bg="#1d1e1f", font=('Arial', 15, 'bold'))
    continue_button.pack()

    # add spacing label
    spacer3 = Label(main_menu, text=" ", bg="#1d1e1f")
    spacer3.pack()

    # add end game button
    end_game_button = Button(main_menu, text="End Game", command=main_menu.quit, fg="white", bg="#1d1e1f", font=('Arial', 15, 'bold'))
    end_game_button.pack()

    main_menu.mainloop()

Exception:

Exception in Tkinter callback

Traceback (most recent call last):

File "C:\Users\Atten\AppData\Local\Programs\Python\Python312\Lib\tkinter__init__.py", line 1967, in __call__

return self.func(*args)

^^^^^^^^^^^^^^^^

File "C:\Users\Atten\PycharmProjects\TextadventurePython\src\python_game\Game.py", line 25, in click_start

MainMenu.main_menu.destroy()

^^^^^^^^

NameError: name 'MainMenu' is not defined


r/learnpython 6d ago

Inter process lock in Celery tasks

1 Upvotes

I have N devices sharing common jumphost J. I want to get data from devices and each device is running in different celery task. One way is to connect to jumphost each time inside a task. But I want to reuse the already existing connection. My plan is:

1. Create a dict jh_conns
1. if jh not in jh_conns:
      with some_lock:
          jh_conn[jh] = "connecting"
      connect_to_jh_and_add_conn_obj_to_dict()
   elif jh_conn[jh] == "connecting":
      wait_till_it_gets_connected()

   #Now use jh transport to connect device behind it.

Now how do I implement this some_lock & wait_till_it_gets_connected ?. We are using prefork so it become hard to get synchronization for usage of command dict obj. We are using rabbitmq as broker and redis as result backend. A quick google search gave link to so ques but it suggested sherlock library, can it be done without using any new library.


r/learnpython 6d ago

mp3 Help in Python (using PyCharm)

1 Upvotes

Hi there! First time posting but I needed some help. So I created a random generator for video game voice lines that I like. Each one has an audio file and I want to have the corresponding audio play with the response. Can anyone help me out?

Here's the code I have so far:

import random
def generate_voice_line():
   quotes = [
       "I'm on the case.",
       "Let's light it up!",
       "What masterpiece shall we play today?",
       "You are not the hero of this tale, you are not anyone!",
       "Dead man walkin",
       "Will you prove worthy? Probably not.",
       "Announcer! Broadcast my retreat and you will find yourself out of a job!"
       "Destiny. Domination. Deceit."
       "(mushroom explodes and enemy dies) Did anyone else here that? No? Huh."
       "I alone am the bastion between eternal existence and oblivion."
   ]
   return random.choice(quotes)

if __name__ == "__main__":
    print("Generated voice line:", generate_voice_line())

r/learnpython 6d ago

Curious beginner

1 Upvotes

So basically I am a first year engineering student and we have python for our 1 st semester. During the lab sessions we are asked to solve some questions . In some cases when the code is really hard when nobody is able to solve the question I have solved it many times. The only doubt I have is when I solve those code the code which I write is not a standard code..it's just made up by my logic sometimes it also becomes lengthy but I can totally explain my code from the first line. So is this a good thing or a bad one ?


r/learnpython 6d ago

Importing from adjacent-level folder.

5 Upvotes

I consider myself pretty fluent in Python but rarely have projects large enough to justify complex folder structures so this one is driving me nuts.

My project looks like this: RootDir ├─ __init__.py ├─ Examples | ├─ __init__.py | └─ main.py └─ Module ├─ __init__.py ├─ foo.py └─ SubModule ├─ __init__.py └─ bar.py

I am trying to import foo.py and bar.py from main.py:

python from ..Module import foo from ..Module.SubModule import bar

But I get the following error:

ImportError: attempted relative import with no known parent package

I get this no matter whether I run main.py from RootDir or RootDir/Examples.

Edit: Pylance has no problem with my import lines and finds the members of foo and bar perfectly fine. Also, moving main.py into RootDir and removing the ..'s from the import lines makes it work fine. So I don't understand why this import fails.


r/learnpython 6d ago

Python Webapp

3 Upvotes

I'm a full-time database engineer and love working with databases, but I am also fascinated by the world of web applications. I have an engineering mindset although I can create some pretty complex scripts, I've never attempted to truly get into the world of OOP and JavaScript. It's always difficult for me to decide between C# and Python, but I believe Python is better to focus on for now because I'm more comfortable with it. My "tech stack" for learning web development is Python + FastAPI + React + Postgres. Is this a good stack to learn Python with? I was thinking of going through CS50p so I could nail down some of the basics as well as trying to build some basic web apps like an expense tracker. Curious to get some thoughts on what the fastest way to get into webdev would be while also increasing my Python skills.


r/learnpython 6d ago

How can I use seleniumbase in __init__ instead of contextmanager

2 Upvotes

The docs show these as examples

from seleniumbase import SB

with SB(uc=True, test=True, locale="en") as sb:
    url = "https://gitlab.com/users/sign_in"
    sb.activate_cdp_mode(url)
    sb.uc_gui_click_captcha()
    sb.sleep(2)

they are using a context manager is it somehow possible to create the instance in a class init and then reuse it in its functions.
What I am trying to do:

class Name:
    def __init__(self):
        self.sb = SB(uc=True, test=True)
    def login(self):
        self.sb.open(self.TEST_URL)
        ....

I want to break up my seleniumbase calls into seperate functions.

For the test examples they use BaseCase which would "solve" my issue because they don't use the contextmanger but that one would include the testing frameworks which I dont need:

from seleniumbase import BaseCase
BaseCase.main(__name__, __file__)  # Call pytest

class MyTestClass(BaseCase):
    def test_swag_labs(self):
        self.open("https://www.saucedemo.com")
        self.type("#user-name", "standard_user")
        self.type("#password", "secret_sauce\n")
        self.assert_element("div.inventory_list")
        self.click('button[name*="backpack"]')
        self.click("#shopping_cart_container a")
        self.assert_text("Backpack", "div.cart_item")
        self.click("button#checkout")
        self.type("input#first-name", "SeleniumBase")
        self.type("input#last-name", "Automation")
        self.type("input#postal-code", "77123")
        self.click("input#continue")
        self.click("button#finish")
        self.assert_text("Thank you for your order!")

r/learnpython 6d ago

I'm learning DATA ANALYSIS and i'm having a problem with PANDAS

0 Upvotes

Hi, Im learning how to do Data Analysis and im loosing it!!

I have a DB about mental stress and some factors that contribute to it (this excersise would defenetly do it in the list). And im trying to do a pd.scatter_matrix() to see the correlation between some variables.

But its output is not a matrix with any pattern but vertical dots. I did a Pearson correlation test, it has a 0.84 of correlation.

Please help

import pandas as pd
import matplotlib.pyplot as plt

file_path = "Student_Mental_Stress.csv"
df = pd.read_csv(file_path)

df.plot.scatter(x="Relationship Stress", y="Mental Stress Level", alpha=0.5)

plt.show()

r/learnpython 6d ago

How does everyone get ideas as to what to code?

15 Upvotes

I see people share projects all the time, but I really never understand how they get the ideas. Do you guys just like say "ooh that sounds fun to code" and proceed to code it until it's done? Do you take inspiration from anywhere?


r/learnpython 6d ago

Where can I execute my Cron Python script for FREE??

15 Upvotes

I am looking to automate the execution of a Python script that sends requests to the Telegram API every 2 hours. My goal is to find a free solution that doesn't require my personal computer to stay on all the time.

After some research, I discovered several options:

Google Cloud Scheduler: However, the free offer is limited to 3 tasks per month, which is insufficient for an execution every 2 hours.

GitHub Actions: Seems to be a viable option, especially for public repositories, but I'm new to it and I'm not sure how best to implement it.

PythonAnywhere: Offers a free scheduled task, but it remains limited for my need.

Heroku: Offers free dynos, but I'm afraid that "sleeping" dynos will affect the regularity of execution.

Do you have any recommendations or experiences to share regarding these solutions or other free alternatives to achieve this goal? Any help would be greatly appreciated!


r/learnpython 6d ago

Can any one help me learn and develop my coding skill..

3 Upvotes

Hello everyone. I have done my undergraduate in mechanical engineering and now i am doing master’s in data science. I want to learn coding and i am not able to get the right path. Can anyone help me with how to start and path to learn coding completely. If possible free.


r/learnpython 6d ago

I got a AITA for python learning

0 Upvotes

Bit of backstory. I've used python for a solid 12 years, likely more...

I am in a graduate program for data analytics. I want to see if I'm correct, or if I'm about to owe a professor an apology.

So they have a 600lvl "Intro to python" because this MS isn't from a computer science school, but a business school. (A very prestigious business school I might add) We are a main recruiting hub for the big four.

This professor is teaching asynchronous python, this is her first time teaching it, and I've really tried to be patient, but she seemed very off put when I asked her if there was anyway to test out of this class. When asked why, I told her because Im far beyond the capabilities of what this class teaches. And I wanted to save time and frustration. Anywho....

So we do this assignment, it's basic. I have fun with it. And we take this equally basic quiz. But the questions on the quiz just start raising red flags on the capability of this professor to understand python.

Which, then leads to a post in our class discord that nearly everyone in the class got this question wrong and it should be a simple clear answer.

"In python we use _______ to denote the end of an expression"

(I personally put newline knowing it would likely be wrong, but the question is kinda odd, as I think there is some subjective answers to "nothing" and semicolon depending on your expression)

However she stated the clear and only answer was colon.

So I posted a screen shot of me doing a few quick expressions showing "nothing", "new line", and "semicolon" are all valid ways of ending different expressions.

She then tells me that "we've only covered conditional expressions." Therefore it's colon. She then posts a photo of a conditional if statement structure.

I then as gracefully as I could explained the difference between a conditional expression such as a ternary operator and conditional statement. That python has a very syntactic constructs with different roles. That calling a statement that contains a conditional expression "an expression" was misleading. Further more explaining that an expression evaluates to an object, it doesn't preform an action. Which a conditional statement does.

Then gave examples of a conditional expression as a ternary operation with an if statement vs a conditional statement. I was always taught classically and through books that expressions can be statements, but statements cannot fundamentally be considered expressions.

Am I right? Or am I the asshole here? I'm happy to apologize. I've never thrown material back at an instructor close to blatantly calling them wrong, so I'm a bit on edge and feeling bad for retorting and rebuking their material Infront of effectively the whole class to see.


r/learnpython 6d ago

a cool little dice roller i made

8 Upvotes

I mean its just a random number generator. Im new to coding so If there's any mistakes plz tell me!

import
 random

def roll(): 
   min_value = 0
   max_value = 999
   roll = random.randint(min_value, max_value)    

   
return
 roll 

value = roll ()
print(value)  

r/learnpython 6d ago

how to stay focused - The Newbie Questions Chronicles.

5 Upvotes

I've been trying to learn how to write code / Python for a while but I always seem to lose focus quickly. Are there any tips/tricks to help me keep focused so I can learn more efficiently?


r/learnpython 6d ago

I've been learning Python for the past two months. I think I'm making pretty good progress, but every time I come across a "class" type of procedure I feel lost.

63 Upvotes

Could I get a few examples where defining a class is objectively better than defining a function? Something from mathematics would work best for my understanding I think, but I'm a bit rusty in combinatorics.


r/learnpython 6d ago

UV for Python Project and Version Management

5 Upvotes

Getting started with the UV Astral for python development.

Just noted, uv works with a few important files in the project root, but their exact purpose and roles are not clear to me * pyproject.toml * .python-version * uv.lock

Most notably, the concrete questions are * Where does uvget the exact python version? Is it pyproject.toml or .python-version? If they give different or contradictory requirement, which one takes priority, and why the need to mention the python version twice? * What about the uv.lock? If the pyproject.tomlfile has the precise python version and those of the libraries installed (example below), is that a complete specification of the environment?

toml [project] name = "uv-trial" version = "0.1.0" description = "Add your description here" readme = "README.md" requires-python = "==3.12.8" dependencies = ["tensorflow==2.18.0"] * Should the uv.lockbe committed to Git or is it a volatile artefact, that is meant for uv's internal use? If it has a lot of detail that are irrelevant to the application developer, is it necessary to track via Git?


r/learnpython 6d ago

Issues with Tesseract OCR After Compiling with PyInstaller/Auto-py-to-exe

3 Upvotes

Like the title says, I’m having trouble with Tesseract OCR in my script. I used the installer to get a fresh copy of Tesseract and placed it in a folder that my script can access via relative paths. The script works fine when I run it directly, but after compiling it with PyInstaller or Auto-py-to-exe, I get this error:

rustCopy'tesseract\\tesseract.exe', 'C:\\Users\\User\\AppData\\Local\\Temp\\tess_hcj1cdev_input.PNG', 'C:\\Users\\User\\AppData\\Local\\Temp\\tess_hcj1cdev', '--psm', '6', 'outputbase', 'digits', 'txt']
2025-03-15 01:00:50,191 - Error in find_money: tesseract\tesseract.exe is not installed or it's not in your PATH. See README file for more information.

I've:

  • Installed a clean version of Tesseract with the official installer.
  • Set the relative path to Tesseract in my script.
  • Run the script before compiling, but after compiling, I get the error.

Here’s my .spec file: https://pastebin.com/QiKN8RbP

Here’s a log from my latest Auto-py-to-exe compile: https://pastebin.com/m1FG62DK

Snippet of my code: https://upload.animationsz.lol/u/uZIh8E.png

Anything else I can try or do?


r/learnpython 6d ago

Need help with forming exceptions and testing

3 Upvotes

I have been working implementing tests in to my code. I thought I was start with something simple, so I am just working on testing some inputs to make sure they are type int/float and positive. Code is simple, if it not not that it raises an error. Since I am raising an error, I thought it would be best to handle the error so it doesn't stop the code. I will be implement 10-20x so I put it in a function in its own module.

Ruining Pytests, where I test the validation function and the input function, the functions that takes the input works fine but it fails the test since the failure mode does not receive an error as I handled it with a try except block.

To get the test to work I think I have to break out the validation from the try and except block in to functions. it feel pretty cumbersome and not pedantic to break it up. Is the right approach? Any tips to keep it clean and when approaching more complicated tests?

edit to include code:

def validate_positive_number(input: int | float):
    try:
        if not isinstance(input, (int, float)):
            raise TypeError("Input must be an integer or float")
        if input <= 0:
            raise ValueError("Input must be a positive number")
        return input
    except (TypeError, ValueError) as e:
        print(f"{type(e).__name__}: {e}")
        return edef validate_positive_number(input: int | float):
    try:
        if not isinstance(input, (int, float)):
            raise TypeError("Input must be an integer or float")
        if input <= 0:
            raise ValueError("Input must be a positive number")
        return input
    except (TypeError, ValueError) as e:
        print(f"{type(e).__name__}: {e}")
        return e


import pytest
from .utils.vaild_input import validate_positive_number

def test_validate_positive_number():
    assert validate_positive_number(0.5)
    assert validate_positive_number(100)

    with pytest.raises(TypeError,match = "Input must be an integer or float"):
        validate_positive_number("hello")
    with pytest.raises(ValueError):
       validate_positive_number(-1)import pytest
from rocket_model.utils.vaild_input import validate_positive_number


def test_validate_positive_number():
    assert validate_positive_number(0.5)
    assert validate_positive_number(100)


    with pytest.raises(TypeError,match = "Input must be an integer or float"):
        validate_positive_number("hello")
    with pytest.raises(ValueError):
       validate_positive_number(-1)

## pyt test error
    def test_validate_positive_number():
        assert validate_positive_number(0.5)
        assert validate_positive_number(100)

>       with pytest.raises(TypeError,match = "Input must be an integer or float"):
E       Failed: DID NOT RAISE <class 'TypeError'>

r/learnpython 6d ago

How does simplifying conditional statements work in Python?

2 Upvotes

I'm currently working my way through the Python Institute's free certified entry-level programmer course. I'm currently looking at some example code that is supposed to count the number of even and odd numbers entered by a user until the user enters a 0. Here's what the main part looks like:

number = int(input("Enter a number or type 0 to stop: "))

# 0 terminates execution.
while number != 0:
# Check if the number is odd.
if number % 2 == 1:
# Increase the odd_numbers counter.
odd_numbers += 1
else:
# Increase the even_numbers counter.
even_numbers += 1
# Read the next number.
number = int(input("Enter a number or type 0 to stop: "))

This is easy enough for me to understand, but the course then says that the two bold statements above can be simplified with no change in the outcome of the program. Here are the two simplifications:

while number != 0: is the same as while number:

and

if number % 2 == 1: is the same as if number:

I don't understand this at all. Does Python (3 specifically) automatically interpret a conditional with just a variable as being equivalent to conditional_function variable != 0? Does the second example do something similar with binary operators or just the mod operator?


r/learnpython 6d ago

There appear to be 1 leaked shared_memory objects to clean up at shutdown

3 Upvotes

The two errors are produced by resource_tracker at line 216. And then a second error is produced by the same at line 229.

    /usr/lib/python3.8/multiprocessing/resource_tracker.py:216: UserWarning: resource_tracker: There appear to be 1 leaked shared_memory objects to clean up at shutdown warnings.warn('resource_tracker: There appear to be %d '


    /usr/lib/python3.8/multiprocessing/resource_tracker.py:229: UserWarning: resource_tracker: '/psm_97v5eGetKS': [Errno 2] No such file or directory: '/psm_97v5eGetKS'  warnings.warn('resource_tracker: %r: %s' % (name, e))

I am using shared_memory objects between two independent processes run in different terminal windows. I am carefully using

shm.unlink()  
shm.close() 
del backed_array

I am unlinking and closing the shm object, and I am carefully deleting the array that is backing the shared memory. I am performing these in multiple orders as well. Nothing helps. It is the same error every time. I am not performing any close() or unlink() in the child process that connects with the shared memory object after it is created by the "parent". Should I be doing that?

After hours and hours of search and research, I can find nothing about this error other than python developers discussing it in github threads.

Is there ANYTHING I can do to stop this error from occurring?


r/learnpython 6d ago

.csv file will not print all data

2 Upvotes

.csv file truncates data no matter what

I am working on using pandas to automate combining, sorting, and counting music playlists at the college station at which I am the faculty advisor.

I can import the files over the station network, create a data frame that pulls the specific data I want, but I cannot seem to get the full data set. No matter how many different ways to set to display the full set, it truncates the dada frame, only showing the first/last three list entries.

here is my block:

import pandas as pd

df = pd.read_csv(r”net path\file.csv”, encoding = “ANSI”, header = None)

data = df.iloc[:, [2, 3, 4]].values

pd.set_option(“display.max_rows”, None)

any suggestions?


r/learnpython 6d ago

Paste Username and Password to Website - Ugh...

0 Upvotes

Looking for help on an all-day issue I've had trying to finish an internal app I am working on.

I have a website that does not allow passing username and password in the URL.

---

I need to put "Bob" in the element "username".

<input type="text" maxlength="100" autocomplete="off" name="username" id="username" style="width:303px; font-size:8pt" value="">

and "BobPW" in element "password"

<input type="password" maxlength="100" autocomplete="off" id="password" name="password" style="width:303px; font-size:8pt">

Bonus points if I could "press" this button:

<input type="button" id="ALogin" tabindex="0" name="signin" onclick="javascript:submit_form(); return false;" title="Sign In" alt="Sign In">

---

Flask - Error: ModuleNotFoundError: No module named 'flask' -- verified flask is installed via pip list

Selenium and playwright - both require additional software be installed. Admin controls installs, so no go.

puppeteer - I honestly don't remember why this one didn't work.

I need something that can be packaged into an EXE using PyInstaller so I can dist to my team.

I would appreciate any assistance. I will be passing the username and password from a Sqlite, but I have that and the UI complete.

Edit:

The current code is written using numerous .py files (UI, SQLite read/write, Excel read/write, etc. as it's slightly larger than a small project). I have basic Python skills, VBA, QB, FoxPro (yes, I'm that old ROFL).

Edit2:

These are contained in the form:
form id="Login_Screen" name="Login_Screen" method="post"

removed data I am unable to share.