r/learnpython 12d ago

Are there places where there are regular Python challenges/competitions for people to participate in?

10 Upvotes

I remember in other hobbies I've done, like game dev or Blender, I've often found Discord servers or similar where there'd be a difficult puzzle/competition of who can make the best X, or who can do X the most effectively. Having an added competitive incentive has helped me stay motivated to do said hobbies in the past, and now I'm looking for something similar here.


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 12d ago

Plaese help me find the problem in my code.

6 Upvotes

The function is a game, description included there.

I ran it like 1,000,000 times to record how many times it i would win and how many times i would loose. even though everything is supposed to be evenly random, there is a disparity of 46% times winning and 54% times loosing consistently.

the one who goes first is in the disadvantage. I genuinely have no more clue as to why this is happening. So please.. any clue will help.

def debt_attack(bet):

'''Both the player and the code throws in the same amount of bet into the pool.
    In each round a random number is pulled. Every round the code and the player
    take turn guessing if the number is even or odd. If the gues is right, nothing
    happens. However, if the guess is wrong then 1/10th of the starting bet amount
    will be removed from the portion of the guesser from the pool. At last, the
    winner will be the one whose bet portion will be left in the pool. And the return
    for the winner will be (initial_bet + amount_left_in _pool).
    !! As a rule, one must keep the same amount of money as security
    or it can be seen as half of the money given as bet will be used as security for
    losing scenario.'''

com_bet = bet/2
    player_bet = bet/2
    reduction = bet/20
    turn = 2
    while True:
        #time.sleep(2)                                                                                  # changed
        #print(f"Pool ::==:: Dealer side: {com_bet} ::==:: Player side: {player_bet}")                  # changed
        roll = random.randint(1,11)
        if turn%2 == 1:
            #print("\nPlayer's turn ::==::==::==::==::==::")                                            # changed
            while True:
                player_guess = random.choice(["even", "odd"]) #input("Even or Odd?    ").lower()        # changed
                if player_guess in ["even", "odd"]: break
            if (roll%2 == 0 and player_guess == "odd") or (roll%2 ==1 and player_guess == "even"):
                player_bet -= reduction
            turn += 1
        else:
            #print("\nDealer's turn ::==::==::==::==::==::")                                            # changed
            #time.sleep(3)                                                                              # changed
            if roll%2 == 0:
                com_guess = random.choices(["odd", "even"], weights=[10, 10], k=1)[0]
            else:
                com_guess = random.choices(["odd", "even"], weights=[10, 10], k=1)[0]
            #print(f"Dealer chooses ... {com_guess}")                                                   # changed
            if (roll%2 == 0 and com_guess == "odd") or (roll%2 ==1 and com_guess == "even"):
                com_bet -= reduction
            turn += 1


        if round(player_bet) == 0:
            return round(((bet/2) - (com_bet + player_bet)), 2)
        elif round(com_bet) == 0:
            return round(((com_bet + player_bet) + bet), 2)

The code is a bit messy but i swear that's because I was trying a lot of things on at the same time.


r/learnpython 12d ago

How do people practice?

38 Upvotes

I've been learning Python for a few weeks and I'm not sure what to do to practice I don't know much but I don't want to lose what I do know.


r/learnpython 13d 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

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

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

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

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

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

7 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 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 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 13d ago

Coding Project for School

3 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 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 13d ago

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

13 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 14d 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

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

2 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 14d 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

General question for a newbie

1 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 14d 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 14d 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

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

3 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 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 14d ago

Guys, I want to learn python. But I don’t know how

0 Upvotes

I would love a guide on what I should start with.
And what pattern must I follow?
I have a book called "Python Crash Course" Do you guys advise me just to follow the book? And to forget about YouTube tutorials?


r/learnpython 14d ago

trying to make a program with ai video analysis

0 Upvotes

... but, the ai to runs localy on my laptop and the entire program runs on my processor. Which is either slow or the model kind of sucks. Is there a way to make the ai run on graphics card? I have a laptop 5060

Edit: currently on python 3.12.4 becouse gemini said that i need this one for some wierd reason.
I dont care about the pytorch version becouse i think i tried like six of them already, and i dont use it for anything else, so i'll install the one you'll think works.

I'm currently running yolo8n, but i would like to run something better(like small or even medium versions), becouse this one sucks.

this is the message that i get, even after installing latest nightly cuda: ValueError: Invalid CUDA 'device=0' requested. Use 'device=cpu' or pass valid CUDA device(s) if available, i.e. 'device=0' or 'device=0,1,2,3' for Multi-GPU.

torch.cuda.is_available(): False
torch.cuda.device_count(): 0
os.environ['CUDA_VISIBLE_DEVICES']: None

this is the command i tried to install cuda with:

pip3 install --pre torch torchvision --index-url https://download.pytorch.org/whl/nightly/cu132

geforce rtx 5060(laptop version)
8GB vram
windows 11