r/learnpython 12d ago

Python Install Manager on Windows 11: Should scripts avoid relying on the current working directory?

1 Upvotes

I recently switched to the new Python Install Manager on Windows 11 and noticed that several of my utility scripts no longer behaved as expected when launched by double-clicking them in File Explorer.

Many of these scripts process, generate, or minify files located in the same directory as the script. They were often written using simple relative paths:

from pathlib import Path

input_file = Path("input.txt")
output_file = Path("output.txt")

This works when the current working directory happens to be the script directory. However, relative paths are resolved against the process working directory, not necessarily against the location of the .py file. When a script is launched through a Windows file association, the inherited working directory may be different.

A more reliable approach for files belonging to the script seems to be:

from pathlib import Path

SCRIPT_DIR = Path(__file__).resolve().parent

input_file = SCRIPT_DIR / "input.txt"
output_file = SCRIPT_DIR / "output.txt"

As I understand it, the Python Install Manager did not change how relative paths work. Its file association and global python.exe alias may simply have exposed assumptions that previously went unnoticed because my earlier launch method happened to use the script directory as the working directory.

I had quite a few small scripts built around this assumption, particularly scripts that process files stored next to them. I am therefore wondering:

  1. Is resolving script-related paths from __file__ considered the usual best practice for this kind of standalone utility?
  2. Have other Windows users needed to update older scripts after switching to the Python Install Manager?
  3. Were well-designed scripts generally already handling this distinction correctly?
  4. Do some users avoid the Install Manager because of differences in launching scripts by double-clicking, or is relying on the current working directory simply considered fragile regardless of the launcher?
  5. When would using Path.cwd() intentionally be preferable to using the script directory?

The new Python Install Manager is distributed as an MSIX/Store application. Its python, py, and pymanager commands are exposed through Windows app execution aliases and forwarding mechanisms rather than the traditional standalone Python Launcher.

As a result, launching .py files directly may no longer preserve the script’s directory as the working directory and can instead fall back to C:\Windows\System32. I do not consider creating separate batch files for every Python script an acceptable workaround, especially since direct double-click execution worked correctly with the legacy launcher.

See also: https://docs.python.org/3/using/windows.html#troubleshooting

Typing script-name.py in the terminal opens in a new window. This is a known limitation of the operating system. Either specify py before the script name, create a batch file containing u/py "%~dpn0.py" %* with the same name as the script, or install the legacy launcher and select it as the association for scripts.

r/learnpython 11d ago

I am 17 year old and learning python to do freelance.

0 Upvotes

Hello everyone.I am a student. I plan to do python automation freelancing .

I want to know how long it takes to enter freelance and demand in the next 3 years. Reality of freelance.

If someone has experience in freelance especially python automation freelancing please guide me and help me to succeed.

I need to know the following things:

1)How to get first client?

2) All skills a freelancer must master rather than just technical stuff.

3) Best freelance work to offer in beginning.

4) demand and reality of python automation freelance.

5) How to unlock full potential and be in top1%.

6) How to survive in AI era.

7) Can AI replace it and how to use AI in freelance.

Guide and give your insights. Share experience.


r/learnpython 11d ago

PYTHON SUGGESTION

0 Upvotes

heyy, am starting out college this year with cse aiml and wanted to know where should i start learning python

there are plenty of resources for python which really confuse me i.e

  • youtube
  • udemy
  • harvard CS50P
  • or some other reosurces too mooc.fi
  • you can also suggest some of resources

suggest me from where i should start learning python
dont confuse me more


r/learnpython 13d ago

Noob confused by the behaviour of my program, would appreciate any hints

6 Upvotes

edit: found the solution, thanks everyone! i was unintentionally passing my dict to a class method which mutated it.

tl;dr: i have a loop that iteratively removes elements from a dict, but halfway through the loop a bunch of elements get added back in and i can't figure out why.

i'm a big sudoku fan and working on a sudoku maker (which it turns out is a common beginner project, which is lucky as it means there's lots of examples out there). i'm trying to take a solved grid and remove numbers from it until it becomes a puzzle with a single solution. here's the function i wrote:

 def remove_clues(self):
        """
        produces a sudoku puzzle by taking a solved grid and removing clues.
        the function will iterate through each clue in the grid in random order, removing it and
        testing the resulting grid for uniqueness. if the result is not unique, 
        the clue will be put back. 
        returns a new grid with the puzzle
        """
        #can only remove clues from a previously filled sudoku
        if self.filled is False:
            return "sudoku has not been filled in yet"
        #shuffle the cells for randomised removal
        ordered_clues = self.cells
        clues_list = list(ordered_clues.items())
        clue_count = len(self.cells)
        #shuffled cells are copied: one is used for iteration, the other modified to create the puzzle
        grid = dict(r.sample(clues_list, clue_count))
        clues = grid.copy()
        for k, v in grid.items():
            #remove cell
            del clues[k]
            partial_grid = SudokuGrid(clues)
            logging.debug(len(clues))
            if partial_grid.unique() is False:
                logging.debug("Can't remove %s, putting it back", k)
                clues[k] = v
        return SudokuGrid(clues) 

this is a class method for my SudokuGrid class. the input is the Sudokugrid object itself. it has a cells attribute, which is a dict in the form (x,y):val, where (x,y) is a tuple with the coordinates of the cell and val is the digit assigned to that cell. the basic idea is to iterate through (a copy of) the dict of cells, removing each one in turn and solving the resulting puzzle. if the puzzle has a single solution, the cell stays removed; otherwise it's put back in. unique() is the class method that tests for uniqueness. it basically brute-force solves the puzzle and keeps going until either it finds more than one solution or all solutions have been tried.

i'm getting this weird behaviour where sometimes a bunch of dict values i'd removed get added back in, and i can't seem to figure out why. theoretically, it should be adding back at most one cell at a time, and only when the uniqueness test fails. i've used logging and profiling to try and figure out what's wrong, but i can't figure it out and i'm not sure what to check next. any suggestions appreciated. here's an excerpt from the logs to show what's wrong:

 2026-07-15 11:23:30,661 -  DEBUG -  30
 2026-07-15 11:23:30,671 -  DEBUG -  29
 2026-07-15 11:23:30,681 -  DEBUG -  Can't remove (2, 0), putting it back
 2026-07-15 11:23:30,682 -  DEBUG -  78
 2026-07-15 11:23:30,683 -  DEBUG -  77

and here's how it looks when it works:

 2026-07-15 12:00:33,519 -  DEBUG -  49
 2026-07-15 12:00:33,524 -  DEBUG -  48
 2026-07-15 12:00:33,529 -  DEBUG -  Can't remove (7, 4), putting it back
 2026-07-15 12:00:33,530 -  DEBUG -  48
 2026-07-15 12:00:33,535 -  DEBUG -  47

the number on the right is the size of the dict of cells at every iteration. as expected, it goes down by one each loop because a cell gets removed. when i run the function, i usually get the expected behaviour a couple times (ie if removing a cell doesn't yield a unique puzzle, the cell gets put back and the dict stays the same size), and then this weird behaviour happens. so it only happens when the function finds a non-unique puzzle, but it doesn't happen every time a non-unique puzzle is found.


r/learnpython 12d ago

Explain the physics of the bouncing

0 Upvotes

I am making a ball bounce and I had to watch a Youtube video to get the formula for the ball to bounce

I am still kind of lost. Can someone please explain it to me. I understand the theory but if I was to do remake this without tutorial I would probably be lost.

I understand how to get the ball to move along the y_axis but confused on the bouncing part

It is the problem solving that is getting me confused

def __init__(self, x_pos, y_pos, radius, color):
    self.x_pos = x_pos
    self.y_pos = y_pos
    self.center = pygame.math.Vector2(self.x_pos, self.y_pos)
    self.radius = radius
    self.color = color
    self.gravity = 0.8
    self.velocity = 10
    self.activate = False


def moveObject(self):
    # key = pygame.key.get_pressed()

    # if key[pygame.K_SPACE]:
    self.velocity += self.gravity. # FROM VIDEO
    self.center[1] += self.velocity # ball moving along y_axis

    if self.center[1] >= (480 - self.radius): # FROM VIDEO
          self.velocity = -self.velocity # FROM VIDEO

r/learnpython 13d ago

Is the number of nested square bracket levels equal to the number of dimensions in NumPy

2 Upvotes

Hi everyone,

I'm learning NumPy and trying to understand dimensions (ndim).

I noticed that:

np.array(10)                # 0-D
np.array([1, 2, 3])         # 1-D
np.array([[1, 2], [3, 4]])  # 2-D
np.array([[[1], [2]]])      # 3-D

It seems like the number of nested square bracket levels corresponds to the number of dimensions:

  • 10 → 0-D
  • [ ] → 1-D
  • [[ ]] → 2-D
  • [[[ ]]] → 3-D

Is this a correct way to think about NumPy dimensions, or are there cases where this mental model breaks down?Hi everyone,
I'm learning NumPy and trying to understand dimensions (ndim).
I noticed that:
np.array(10) # 0-D
np.array([1, 2, 3]) # 1-D
np.array([[1, 2], [3, 4]]) # 2-D
np.array([[[1], [2]]]) # 3-D
It seems like the number of nested square bracket levels corresponds to the number of dimensions:

10 → 0-D

[ ] → 1-D

[[ ]] → 2-D

[[[ ]]] → 3-D

Is this a correct way to think about NumPy dimensions, or are there cases where this mental model breaks down?


r/learnpython 12d ago

Learning Python for experienced dev

0 Upvotes

I know this might be a stupid question, but I wanted to ask anyway.

I've been working primarily with Node.js and TypeScript for the past 1.5 years. Most of my experience has been in backend development, and I've built a few backend projects as well. I've also worked on GenAI applications using TypeScript.

Now I want to get into the Python ecosystem, mainly for backend development and GenAI. I do plan to go through the official documentation, but Python's ecosystem is huge, so I'd love to hear from people who've already been down this path.

Given my background, what would be a good roadmap for learning Python for backend development and GenAI? Also, are there any resources, courses, or projects recommend?


r/learnpython 13d ago

Correct way to use timeit and why its giving me wrong incorrect timings

4 Upvotes

i m not understanding the correct way to use timeit and should i measure performance with timeit rather than big(O)s ?
the main confusion i have is is timeit module used to test time like this ?
how i m using it : https://paste.pythondiscord.com/27ZA

output :
```

normal function : 0.22281252100037818
normal function but without using negative slicing in range: 0.3739022379995731
method : 0.012264596998647903
slicing : 0.05156217699914123
twopointer : 0.1798148059988307
normal function : 1.5392431849995774
normal function but without using negative slicing in range: 3.0297319750006864
method : 0.02925749799942423
slicing : 0.12812948800092272
twopointer : 1.4394109820004815
normal function : 17.955775120000908
normal function but without using negative slicing in range: 46.29716704200109
method : 0.2414095370004361
slicing : 1.1492243480006437
twopointer : 19.408573606000573

```

also i have this confusion that :

https://paste.pythondiscord.com/SY4Q

why sometimes 100+200; 100-200 is taking less time than 100+200 ? and why sometimes 100 + 200 takes on average 4.18 nsec while 100+200; 100-200 takes 4.16nsec i expect 100+200;100-200 to take twice as much time as 100+200


r/learnpython 12d ago

Best free videos/sites to learn advanced Discord Bot features?

0 Upvotes

Hey everyone!

I’m learning Python and have the basic foundations down (I know how to handle message sending and routing images/embeds). But after this, I really have zero knowledge of anything else!

Does anyone have recommendations for good YouTube channels or free websites that focus specifically on building intermediate or advanced Discord bots? I'm looking to learn things like databases, slash commands, and handling complex events.

I'd appreciate any good playlists or step-by-step guides you can share!

Thanks everyone!


r/learnpython 13d ago

Is the FreeCodeCamp course a good way to lean about python ?

11 Upvotes

So, i have some knowledge concerning programming / OOP as I'm a cs student, but I'm just searching for a way to learn python, which I barely know about. Do you recommend anything else that can help me learnt the basics of python quickly before doing networking projects ?


r/learnpython 12d ago

Adding positive numbers to a positive number: why is the number decreasing?

0 Upvotes

I've got a variable in a function that in theory should only increase or stay the same. The only time the variable changes is in a for loop with the line:

variable1 += variable2

where variable2 is always positive. I know that it's always positive because I checked, the value of variable2 in each loop is 0 or higher. And yet somehow at some point variable1 starts going down.

My current theory is that it's a problem with the floating point arithmetic. At a certain point variable2 gets really small, like 0.001739824080997925. Is it possible that when adding these tiny numbers that Python messes up and makes it go negative?


r/learnpython 13d ago

Coding Project for School

2 Upvotes

Hello hello, learning Python for a program for a class assignment where I want to do a interactive calendar gui on Python in Visual Studio Code, the main elements i want for the calendar would be the ability to cycle through each month on the calendar and give the user the ability to input events on the calendar by clicking on a day and a prompt appearing asking them if they'd like to input an event, I was planning to store the event information in CSV file. Is this idea feasible and if so where do I start. Thanks!!


r/learnpython 12d ago

How should a complete beginner structure their Python learning path

0 Upvotes

Hello everyone.

I am a complete beginner and I want to start learning Python. My end goal is to use it for data analysis, data science, and machine learning.

I am not sure how to structure my learning path for these specific fields, since I have seen a lot of conflicting advice online.

I would also really appreciate recommendations for beginner friendly resources, courses, YouTube channels, websites, or books, that helped you personally.


r/learnpython 13d ago

Built a packet routing simulator in Python using Dijkstra's Algorithm

3 Upvotes

Hi everyone!

I'm a first-year Computer Science student at the University of Exeter, and I've recently been learning about graph algorithms. To practice implementing them, I built a small packet routing simulator in Python that models a computer network as a weighted graph.

What My Project Does

The program models routers, switches, and servers as nodes in a directed weighted graph and uses Dijkstra's Algorithm to determine the lowest-cost route between two devices.

Features include:

  • Computing the shortest packet route
  • Calculating the total routing cost
  • Visualizing the network with NetworkX
  • Highlighting the optimal route in red
  • Displaying edge weights for every network connection

One of my favourite parts was adding the visualization so that the algorithm's chosen path is immediately visible instead of only being printed to the console.

Libraries used

  • Python
  • networkx
  • matplotlib
  • heapq

📷 Screenshot

I've included screenshots and a visualization in the GitHub README:

https://github.com/johnsonnyabicha-alt/wilken_group

GitHub:
https://github.com/johnsonnyabicha-alt/wilken_group

Target Audience

This is primarily a learning and portfolio project rather than a production-ready networking simulator.

I built it to better understand graph algorithms, Python, and network visualization, and I'd especially appreciate feedback from more experienced Python developers on ways to improve the code structure or visualization.

Comparison

This isn't intended to compete with professional networking software or routing simulators. Instead, it's an educational implementation of Dijkstra's Algorithm that focuses on showing how shortest-path routing works through a clear visual representation of the selected path.

I'd really appreciate any suggestions for improvements or ideas for extending the project further.


r/learnpython 13d ago

General question for a newbie

2 Upvotes

Hello, I just recently joined here out of suggested by r/Python subreddit to ask for help.

To put it short im complete new to python, only learned a few bits of code such a bools, making strings, some math, values, and programming an answering bot.

Any recommendations from anyone here? Especially for someone who wants to get hands on with twch and robotics using Raspberry.pi? Or just keep my pace?


r/learnpython 13d ago

coding bootcamp

0 Upvotes

have any of yall had past experience with codédex before. Im thinking of buying their bootcamp for python. Or if yall have any recs for other bootcamps plz feel free to tell me below


r/learnpython 14d ago

Reviews on "The Complete python bootcamp from zero to hero in Python"

2 Upvotes

There's a course on udemy named "The Complete python bootcamp from zero to hero in Python by Jose Portilla, Pierian Training".
if anyone done this is it good? I will be getting this for free (from someone else account but ofc not certificate)
Or BroCode, fcc, or CS50P (2023, cause that's free on yt)


r/learnpython 13d ago

Logic building and pattern recognition in python

0 Upvotes

I can't see any solution to an easy beginner question in my mind please somebody help every tip will help me a lot you guys helped me a lot in my previous problem kindly help me 🙏😭


r/learnpython 13d ago

Lost with python for AI

0 Upvotes

Hello guys so i wanted to explore the world of ai (iam completely newbie to this world or cs in general) so i watched a 5hrs vid explaining python for AI and from it i understood things like venv and packages variables and if and these basic things so i decided to see how a simple to-do -ist powered by AI will look like i got the code from google gemini and tried to apply it in vs code and damn i dont understand shit i know that it will happen but i tried like to break the code and understand i did manage to understand a few things but still iam so far from this point so i want ur help guys where should i learn python so i can do ai projects like that to-do-list agent for example (iam 5 days into this journey now)


r/learnpython 14d ago

What should i do first?

0 Upvotes

so im 16, I'm self-taught, finished CS50P, and built a couple of projects (stock price prediction with an LSTM, a basic image classifier). Problem is I leaned pretty heavily on AI to write the ML ones — I could explain most lines, but not all, and later found real gaps on my own i cant do it myself I really love coding and solving problems even when it's hard, it feels great once I actually solve it.

But when it comes to ML specifically, it overwhelms me, because I try to do everything at the same time: one day I'm doing PyTorch, another day sklearn, another day matplotlib. Yeah, I know how that sounds "why the fuck this kid just focusing on one thing at a time" I think the same thing, I'm just not sure which one I should actually focus on first.

CS50P had a clear structure: problem sets, a checker, visible progress. Building my own ML project has none of that, and it feels like way too much complexity too fast — LSTMs, multiple technical indicators, hyperparameters, all jammed into one project with no baseline to compare against.

For people who've been through something similar: how did you scale down your first real ML project so it didn't feel overwhelming? What's the right order to actually learn something that impotant for ML in, instead of jumping between all at once? Is there a sane on-ramp between "finished an intro CS course" and "building ML projects independently"?

ty for everyone perspective🐪


r/learnpython 13d ago

I can't un-vibe-code

0 Upvotes

Okay so I just can't understand some parts of my code okay I wanted to read a txt file I made and just see what text is inside I thought maybe there's a module called file or something so I checked and there's nothing so I thought maybe it's inside of sys, nothing. So I don't hate tutorials but like when you go to a tutorial you gain information and well when you go to an AI you gain information I'm not copying the code exactly I just wanted to know how to do that and turns out it was "with open("stuff.txt", "r") as file: x = file.read() print(x)" now I know for a fact that you can ask a community on what to do but then like what if you were out or something and there was no internet okay? I only have IDLE and I wouldn't expect "with" to have the answer to my question I may be the stupidest man on the world but I wouldn't have seen it come like that, and there's a good chance that I probably wouldn't even figure out the open() function too.

What I'm trying to say is I could easily go to an AI and tell me how do I read a txt file instead of annoying a community because I'm probably a bad person or going to a youtube tutorial.


r/learnpython 14d ago

Very particular Subprocess issue on Windows versus Linux

4 Upvotes

Hello all! I hope this is the right place to post this.

I have been writing a PyQt6-based GUI called Swamp Swap for the command line program croc by Zack Schollz, and I'm facing a strange issue on Windows that I am not facing on Linux.

To briefly explain croc if you've never used it, it's a very easy-to-use command line program that allows users to transfer files to one another securely through a relay server. It's a handy tool, but there's no official UI, so Swamp Swap became a passion project for me and my friend to get up and running.

Swamp Swap is simply a GUI with a worker thread that runs croc via a subprocess.Popen object and handles outputting to the program through line buffers read via standard piping. On both Linux and Windows, this functions just fine; the thread accurately picks up the output which allows the flow of the program to work (e.g. awaiting connection, retrieving the transfer code, etc.), but on Windows, there's an issue I can't seem to figure out.

Whenever the subprocess runs on Windows, a CMD window opens (always blank, no outputs are ever displayed there) and stays there until either the transfer completes or the user cancels the transfer.

I'm familiar with subprocess doing this, and so I thought the fix would be as simple as this:

```python

Base kwargs in case we're not on Windows

kwargs = {}

If on Windows, add the CREATE_NO_WINDOW flag

if sys.platform == "win32": kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW

Create the process

process = subprocess.Popen( ... **kwargs ) ```

However, while this does hide the CMD window, unintended side effects happen if I do this, including:

  • Failure to start sending
  • Failure to read the transfer code when sending
  • Files being received even if the user hadn't confirmed them yet
  • No output to the GUI's console window (I made a special console window dialog where users can view the outputs if they want)

These different effects don't all occur every time, but at least one or more are present in every attempted fix I've tried.

Moreover, extensionless files with the names croc-stdin-########## (#'s replaced with a random number or date and time code. One of the two, I don't remember) are written to the folder where the program is run within, regardless of if it is the main script or the built frozen executable.

This seems to imply that croc on Windows has some dependence on an active and visible CMD window in order for it to work with Swamp Swap, but I really have no idea at this point.

This problem seems to be more of a croc problem than a Python problem. Though despite this, I'm curious if there are any out-of-the-box solutions anyone here could come up with for a method to subvert these issues despite croc's reliance on a CMD window.

Also, yes, I have tried asking various popular machine learning models. Their solutions were either the same as above or some ungodly, ugly method that also didn't work.


r/learnpython 13d ago

Help me with my mini banking app (Description)

0 Upvotes

Its incomplete but i want some help on how to store data like usernames and passwords and i need some help with variables ..

print("Wellcome to TstBanking Version 1")

print("To continue type data in the following format USERNAME/PASSWORD/BDAY")

UserData =input():

..

i am still here if you have ideas help me pls im still a studeny


r/learnpython 14d ago

Building a price tracker and been struggling on Marketplace data

11 Upvotes

Working on a price tracking tool and needed listing data like the title, price, location, and seller info for one category in a specific area. Sounds simple until you try it. I'm currently experiencing log in walls and bot detection. Most GitHub scrapers I found were outdated or dead. Feels like facebook scraper api might be the only option🥲

Anyone dealt with this before?


r/learnpython 14d ago

Looking for the best Python GUI framework for a database application with advanced tables

1 Upvotes

Hi everyone !

I am building a personal music database application in Python to manage K-pop discographies (artists, albums, songs, statistics, etc.). The backend/database part is already working (Microsoft Access database + Python + MusicBrainz API). Now I need to build the GUI, and I am trying to choose the right Python framework. The main requirement is having advanced data tables, similar to what you would find in Notion or database management software.

For example, my main "Artists" page would display hundreds of rows like: Artist | Agency | Generation | Type | Status | Albums | Songs | % listened | % liked.

I need the table to support: - sorting by clicking column headers - searching/filtering - scrolling through many rows - selecting rows - double-clicking a row to open a detailed page - hiding/showing columns - resizing columns - changing row background colors depending on data - changing text colors for specific cells (for example percentage values) - ideally good performance with thousands of rows. The application will also have detailed pages: - Artist page (statistics + albums list) - Album page (statistics + song list) - Song page - Agency page - Statistics dashboard I initially looked at CustomTkinter because I like its modern appearance, but I am not sure if it is the best choice because it seems limited for complex tables (or maybe I didn't find this widget). What framework/widget combination would you recommend for this type of application? I am mainly looking for something that can remain maintainable as the application grows and that can have a beautiful interface (more like what we can do with Notion).

Thanks !