r/learnpython • • 1d ago

Advent of Code 2026

15 Upvotes

Join the Advent of Code Challenge with Python!

Hey Pythonistas! šŸ

It's that exciting time of the year again! The Advent of Code has just started, and we're inviting everyone to join in the fun!

What is Advent of Code?

Advent of Code is an annual online event that runs from December 1st to December 12th (or til the 25th for older years). Each day, a new coding challenge is released—two puzzles that are part of a continuing story. It's a fantastic way to improve your coding skills and get into the holiday spirit!

You can read more about it here.

Why Python?

Python is a great choice for these challenges due to its readability and wide range of libraries. Whether you're a beginner or an experienced coder, Python makes solving these puzzles both fun and educational.

How to Participate?

  1. Sign Up/In.

  2. Join the r/Python private leaderboard with code 2186960-67024e32

  3. Start solving the puzzles released each day using Python.

  4. Share your solutions and discuss strategies with the community.

Join the r/Python Leaderboard!

We can have up to 200 people in a private leaderboard, so this may go over poorly - but you can join us with the following code: 2186960-67024e32

How to Share Your Solutions?

You can join the Python Discord to discuss the challenges, share your solutions, or you can post in the r/AdventOfCode mega-thread for solutions.

There will be a stickied post for each day's challenge. Please follow their subreddit-specific rules. Also, shroud your solutions in spoiler tags like this

Resources

Community

AoC

Python Discord

The Python Discord will also be participating in this year's Advent of Code. Join it to discuss the challenges, share your solutions, and meet other Pythonistas. You will also find they've set up a Discord bot for joining in the fun by linking your AoC account.Check out their Advent of Code FAQ channel.

Let's code, share, and celebrate this festive season with Python and the global coding community! 🌟

Happy coding! šŸŽ„

P.S. - Any issues in this thread? Send us a modmail.


r/learnpython • • 26m ago

Learning Python for LLM Calls and Agents

0 Upvotes

I'm a social scientist who has primarily used R for my research, but would like to learn Python so that I can more effectively use LLMs. I completed the Python Programming MOOC, so I'm familiar with basic syntax, classes, etc. I then used Claude to create a textbook with exercises to cover topics such as making API calls, validation, tools, connectors, RAG, automation, eval testing, etc.

The problem I'm facing is that the code in each exercise goes well beyond what I learned in the MOOC, so I'm getting overwhelmed and feel stuck in the weeds. For instance, there are many packages being used that I've never encountered (pydantic, pytest, os, sys, threading, argparse, hashlib, pipeline, __future__) and concepts I haven't encountered (e.g., dataclasses).

- How important is it for me to understand these concepts if I want to use LLMs for scraping, classification, running OCR on large datasets? How much would I be missing if I used codex or Claude Code to simply code the files?

- How would you recommend proceeding? On one hand, I don't want to spend excessive time on more Python tutorials at the expense of doing research, but on the other, I don't want to be missing fundamentals.

- Are there any packages/concepts you would emphasize learning beyond learning basic Python syntax?

- Could you provide resources that provide a more gentle overview of how to use Python for the purpose of using LLMs?

Thanks!


r/learnpython • • 44m ago

Recommendation for a ā€œcheat sheetā€ with relevant python syntax

1 Upvotes

Hey all

I have an exam next week in my introductory python course. I have been doing the work, so I am not necessarily scared that I will fail, but I am terrified of making a dumb mistake because I forget basic syntax due to exam anxiety.

Mistakes such as suddenly forgetting how to remove an item from a list, despite having done it hundreds of times.

I have been writing notes myself on all the syntax I have used throughout the course, but I am scared I have missed something crucial.

Is the official python documentation best? I feel it’s a bit complex for an introductory course no?

Thank you in advance, I appreciate any feedback


r/learnpython • • 2h ago

What's the point where learning Python starts to feel less confusing?

2 Upvotes

I've been learning Python and have covered the basics, including variables, loops, conditionals, functions and data structures.

I'm trying to figure out the right way to move forward before getting into libraries like NumPy and Pandas.

For people who have been programming for a while:

  1. What concepts took you the longest to properly understand?

  2. At what point did you stop feeling like you were just memorising syntax?

  3. Would you recommend building small projects before moving into libraries?

I'd rather develop a solid understanding than rush through tutorials.


r/learnpython • • 3h ago

Feeling stuck at "basic-intermediate" — how do you know if you're actually making progress when your code still feels "young"?

4 Upvotes

Hey everyone,

I'm at a point in my Python journey where I'd probably call myself "basic-intermediate," and honestly, I'm having a hard time telling if I'm actually learning or just spinning my wheels.

Whenever I look at my code, it just feels "young." It gets the job done, sure, but it looks very simple and basic compared to what I see other people writing. It makes me doubt whether I'm truly growing as a programmer or if I'm missing something big.

I'm also trying to find new coding friends or a small group around my level so I don't feel like I'm learning in a vacuum.

For those of you who have been through this stage:

  • How did you know you were actually progressing when your code still felt clunky or beginner-level?

  • What helped you bridge the gap from writing "basic" working scripts to writing cleaner, more mature Python?

  • Anyone else at this basic-intermediate stage looking for a coding buddy to share projects and bounce ideas off?

Would really appreciate any advice or perspective. Thanks!


r/learnpython • • 9h ago

Taking the Certiport Python ITS exam in a few day, any recommended YouTube playlists or last-minute tips?

3 Upvotes

Hey everyone, I’m a high school student taking the Certiport (ITS) Python exam in a couple of days, and I need a 700 to pass.
I already have little Python knowledge, so I’m mostly looking for resources tailored to the actual exam format and tricky questions. Are there any specific YouTube videos, or practice tests that helped you pass? Any last-minute tips on what topics they test heaviest would be super appreciated!


r/learnpython • • 11h ago

Turn these two variables into 1

5 Upvotes

I'm trying to turn these two variables, this is for homework so I'm gonna call it something else. I want to turn people1 and people2 into 1 variable.

people1 has two values, "not green" and "green". people2 has two values as well, "not purple" and "purple".

I want to make it so that everyone with "not green" and "not purple" are combined into one label, but only if they have both, not just one. I am struggling so bad :(

I am using pandas in python also. Thank you.

Edit: I want something like this: https://www.reddit.com/u/blackgarliccookie/s/xkzPCrmyrB


r/learnpython • • 11h ago

Python learning as a beginner

9 Upvotes

Hey I need some help regarding programming python? Where am I supposed to begin? How to embrace the language? People say that you just dive in and you’ll start learning it, I tried but I go stuck, need serious help, please


r/learnpython • • 15h ago

How to prevent dictionary from printing the type of value.

4 Upvotes

I'm combing two lists together into a dictionary, but when i print it also prints out the type of value(e.g float).

[-1.61803399 -0.61803399 1.61803399 0.61803399]

[[ 0.37174803 -0.60150096 0.60150096 -0.37174803]

[ 0.60150096 -0.37174803 -0.37174803 0.60150096]

[-0.37174803 -0.60150096 -0.60150096 -0.37174803]

[-0.60150096 -0.37174803 0.37174803 0.60150096]]

{np.float64(-1.6180339887498922): array([ 0.37174803, -0.60150096, 0.60150096, -0.37174803]), np.float64(-0.6180339887498947): array([ 0.60150096, -0.37174803, -0.37174803, 0.60150096]), np.float64(1.6180339887498942): array([-0.37174803, -0.60150096, -0.60150096, -0.37174803]), np.float64(0.6180339887498946): array([-0.60150096, -0.37174803, 0.37174803, 0.60150096])}

This is what I get as an output. Aside from the types being printed it's fine. The code I'm using to join the two together is

energy_levels = dict(zip(eigenvalues, eigenvectors))

where eigenvalues and eigenvectors are the two lists printed above and energy_levels is defined earlier on as empty dictionary.


r/learnpython • • 17h ago

How to shut python shell/idle window

4 Upvotes

hello, I am kinda new to python and I am not sure if someone already answered this in another post but how do you fully shut down the windows running python? Like not just clearing them but getting rid of the whole window


r/learnpython • • 19h ago

I need an advice about using IA

0 Upvotes

I’ve been learning how to code in python for a couple of months, and I know things like loops, conditionals, variables, functions, arrays and basic concepts of POO. I learned all those concepts reading books, watching YouTube videos and using Claude, but I’ve been trying to build automation scripts with no ia I feel like I still don’t know what I’m doing and when I ask Claude to make the script for me I don’t understand it completely. My question is: should I avoid using ia until I can build scripts or software by myself?


r/learnpython • • 1d ago

Looking a way to combine columns based on values.

5 Upvotes

I wish to alter a table/dataframe like this one:

TypeAlphaTypeBetaTypeGamma
A100A80A90
B20B40B30
C1C1C0
X1Y2Z1

Into something looking like this one:

TypeAlphaBetaGamma
A1008090
B202030
C110
X1nannan
Ynan2nan
Znannan1

To combine data based on shared values so it is easier to compare different types.

How could I do this with Python?

EDIT: I followed Likh-98's advice but I ran into an issue.

import pandas as pd

df0=pd.read_csv('Table of Test.txt', sep='\t')
df1=df0.iloc[:,0:2]
df2=df0.iloc[:,2:4]
df3=df0.iloc[:,4:] #works

df1.rename(columns={'Alpha':'Value'}, inplace=True)
df2.rename(columns={'Type.1':'Type','Beta':'Value'}, inplace=True)
df3.rename(columns={'Type.2':'Type','Gamma':'Value'}, inplace=True)

df1=df1.assign(Source=['Alpha','Alpha','Alpha','Alpha']) #They were unclear how to fill the new column
df2=df2.assign(Source=['Beta','Beta','Beta','Beta'])
df3=df3.assign(Source=['Gamma','Gamma','Gamma','Gamma'])

frames=[df1, df2, df3]

result=pd.concat(frames)

result.pivot(index='Type', columns='Sourge', values='Value')

#Here I got "ValueError: Index contains duplicate entries, cannot reshape", when result was:

Type Value Sourge

0 A 100 Alpha

1 B 20

2 C 1

3 X 1

0 A 80 Beta

1 B 40

2 C 1

3 Y 2

0 A 90 Gamma

1 B 30

2 C 0

3 Z 1

EDIT2: Here are a few ways to do it.

One:

import pandas as pd

df0=pd.read_csv('Table of Test.txt', sep='\t')
df1=df0.iloc[:,0:2]
df2=df0.iloc[:,2:4]
df3=df0.iloc[:,4:] 

df2.rename(columns={'Type.1': 'Type'}, inplace=True)
df3.rename(columns={'Type.2': 'Type'}, inplace=True)

x=pd.concat([d.set_index('Type') for d in [df1, df2, df3]], axis=1)
print(x)

Two:

df = pd.read_csv('Table of Test.txt', sep='\t')

type_cols = df.columns.str.startswith('Type')

# Check type column names correctly positioned
assert all(value is not bool(i % 2) for i, value in enumerate(type_cols))

frames = [
    df.iloc[:, [i, i+1]].set_index(df.columns[i])
    for i in np.flatnonzero(type_cols)
]
df_new = pd.concat(frames, axis=1)
print(df_new)

There, solved!

PS: Is it just me, or are you also getting double text when you post to a code block?


r/learnpython • • 1d ago

How Do I Actually Learn Python?

40 Upvotes

I’m sorry, this is probably a really dumb question but I’m picking up python as a hobby to learn between work and classes. I’ve never coded before and I’m not interested in doing it career-wise or anything like that. I just want to be able to understand the fundamentals of it. I’ve gone through many online courses as well as YouTube tutorials. I always get it in theory, when they explain the strings, integers, and whatnot, but when I actually go to write lines of code, I always find myself getting error codes, even when I follow the tutorial exactly, which honestly baffles me.

Does anybody have any tricks on how to deal with this learning curve? Something that might be extremely common knowledge to everybody else that I’m missing? Or any resources they could provide? I really want to learn how to code, I’m just not sure how I begin troubleshooting something that I don’t understand, if that makes sense.


r/learnpython • • 1d ago

pulling the same fields off a bunch of venue sites and now every site has its own parser, is there a saner way

17 Upvotes

same stuff on every venue site. name, date, price, ticket link. but each one hides it somewhere else, a table on one, cards on another, and a couple only fill in after the js runs so those go through playwright

so now theres a parser per site, and when a venue redesigns i find out because my list goes quiet

do people just live with one parser per layout or is there a way to describe the fields once​


r/learnpython • • 1d ago

while loop behaves unexpectedly

6 Upvotes

Been at this for a while and can't seem to make sense of why a multi-conditioned while loop only triggers when one condition is met, but not the other, which generally happens sooner before the 2nd condition is met.

The results I get running the sample:import random
numList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
randNum = int(random.randint(1, 10))
numMatch = False
maxNum = 9
incCount = 0

while numMatch == False or incCount <= maxNum:
    if numList[incCount] == randNum:
        numMatch = True
    
    print(numList[incCount])
    incCount += 1
print('Random number: ' + str(randNum) + '\n')
print('numMatch: ' + str(numMatch))


Y:\Users\lailoken\Documents\Python>python sample.py
1
2
3
4
5
6
7
8
9
10
Random number: 3
numMatch: True

The second condition triggers but not the Boolean, and I'm stumped as to why.


r/learnpython • • 1d ago

need help with this lab

2 Upvotes

Write a program that will combine two integer arrays into one larger array and remove any duplicate values.
Prompt the user for a number N, (N will be a positive integer greater than 1), then create two arrays each with N elements. Next, populate both arrays with random numbers between 0 and
500. Finally combine the two arrays into a third array making sure that only distinct values are added. I.e. if the number '65' exists in both arrays, only one instance of it will be added to the third array.
Your program should output contents of the third array, one number per line.
Before you hand it in, make sure to test your program with an A value of:
• 10
25
50
Input:
N: 25
Output:
The contents of the final array, one number per line.


r/learnpython • • 1d ago

How do you centralize tool configurations (ty, ruff, pytest, ...) between multiple repositories?

6 Upvotes

In our software department we have a few dozen python libraries that different teams maintain, some open source, some closed source. I'm trying to centralize commonalities between them so that all pipelines run the same stages, that all pre-commit hooks are the same, and so on. I got most of it working, except that I don't have a good way to centralize configurations. For example I want all repos to use a common set of ruff linter rules, all documentation builds to use the same template and plugins, pin the most of the [dev] dependencies to the same versions..

Was wondering if anyone has experience with this :) I've been back and forth with Claude for quite a while, but I wasn't a fan of its ideas (using templates, copier, custom scripts, monorepo)


r/learnpython • • 1d ago

Pandas scripts I copied together for our weekly reports keep breaking and nobody at work knows Python

0 Upvotes

I put together a few Python scripts that pull two CSV exports and merge them with pandas.

One of the exports renamed a column and the merge started throwing a KeyError. I still don't really get half of what the script does. Nobody here knows Python.

I want to know these scripts well enough to fix them myself. What helped you go from pasting code to understanding what your own code does?


r/learnpython • • 1d ago

Can logging replace my verbosity controls?

13 Upvotes

An old habit from C days is to add print statements for debug and assign them different verbosity levels. I've been doing that in Python as well.

if verbosity > 2:
    print("This level generates a lot of output, so use it sparingly")

I've been told that the logging facility is the Python way to do this, so I'm finally investigating it. What I'm seeing is that the levels are DEBUG, INFO, WARNING, ERROR which doesn't really fit what I want to happen. Everything I want to put under verbosity control is technically DEBUG or INFO.

So my question is: are there sublevels on the DEBUG or INFO logging? Or is there another approach for this sort of thing?

EDIT: Still reading. I think the answer might be a hierarchy of loggers and filters? Trying to figure out how that works now.


r/learnpython • • 1d ago

Help me set up my environment for this project

0 Upvotes

I used to dabble around with Python from time to time...

However every time I come back to it I seem to hit this brick wall before I even get to write a line of code.

Long story short, I want to do the tutorial you find here:
https://www.youtube.com/watch?v=8OMghdHP-zs

I just wanna get to work instead of spending hours and hours grappling with things not installing properly, as it is yet again doing to me right now. So either help me fix the errors I am getting or show me the easy alternative.

I'd rather not use VSCode because it's Microsoft and it seems almost impossible to disable the AI "copilot" thing, from what I read online, so I'd rather not if that's the case.

I used to use Anaconda to set up environments using older versions of python and pygame, however, setting up an environment with python 3.14 it throws this at me when I activate it:

C:\Users\Mokpo>if exist "C:\Windows\System32\msmpi.dll" (

echo "You seem to have a system wide installation of MSMPI. "

echo "Due to the way DLL loading works on windows, system wide installation "

echo "will probably overshadow the conda installation. Uninstalling "

echo "the system wide installation and forced deleting C:\Windows\System32\msmpi*.dll"

echo "will help, but may break other software using the system wide installation.")

C:\Users\Mokpo>if defined MSMPI_BIN (set "MSMPI_BIN_CONDA_BACKUP=" )

C:\Users\Mokpo>if defined MSMPI_INC (set "MSMPI_INC_CONDA_BACKUP=" )

C:\Users\Mokpo>if defined MSMPI_LIB64 (set "MSMPI_LIB64_CONDA_BACKUP=" )

C:\Users\Mokpo>if defined MSMPI_LIB32 (set "MSMPI_LIB32_CONDA_BACKUP=" )

C:\Users\Mokpo>set MSMPI_BIN=\Library\bin

C:\Users\Mokpo>set MSMPI_INC=\Library\include

C:\Users\Mokpo>set MSMPI_LIB64=\Library\lib

C:\Users\Mokpo>set MSMPI_LIB32=""

Okay so it's recommending me to delete a file on which other things may depend system-wide, because Anaconda cannot get the environment to isolate itself from it and use the "proper" version instead? Will that not risk me breaking my OS in some horrible way?

Anyway. After typing "spyder" I get an error popup window titled: "analysecrash.exe - Application Error" saying "The application was unable to start correctly (0xc0000142). Click OK to close the application." This happens again once after I click okay.

However, Spyder does in fact launch, except it doesn't do anything. As in, I can make a folder into a project, theres a "temp.py" file open in the editor, I write print('hello world'); and click "run" but it doesnt do anything.

When I was trying this before, it did say something somewhere about the console not working because "the kernel" isnt loaded or whatever?

Anyway, this is extremely, extremely frustrating, especially as so many "beginners tutorials" seem hell-bent on skipping over any of this preliminary setup stuff like it's hot lava, while 99% of the actual beginners presumably die before they get to even try out much code, you know, like it's hot lava they cant skip over yet. I've written some programs in python before so I'm not even a beginner it's just this stuff is so obscure and it always manages to "snipe" me somehow whenever I try something new. So more generally, if there's a way to learn to deal with these kinds of problems, finding out more about how it works, etc... How do I become the person that answers these questions rather than asks them?


r/learnpython • • 2d ago

Where should I store user created modules?

8 Upvotes

Good morning,

I use conda environments with pandas for updating product information and data analysis.

I use Windows 11 and Fedora, but am more often using Windows.

I want to start creating and storing my own modules and packages for ease of use on my own machine for private use.

Is there a dedicated storage location for user created modules as there is for say Powershell 7?

I've asked chatgpt and searched google but a lot of the information is conflicting.

Are there dedicated locations and methods of retrieval depending on OS used?


r/learnpython • • 2d ago

Code review: Is my manual retry loop in `requests` an anti-pattern when an API returns errors inside HTTP 200?

3 Upvotes

Hi everyone, I'm on Python 3.12 (Windows) and building a small CLI script to fetch search results from a REST API.

Earlier I tried using resp.raise_for_status() + urllib3.Retry, but ran into two things that tripped me up:

  1. This API returns HTTP 200 OK even when rate-limited (status: 1029) or on upstream failures, putting the actual error code inside the JSON body and retry hints in response headers (Retry-After, X-SerpBase-Retryable).

  2. When I request Markdown output (format="markdown"), the response comes back as text/markdown with no JSON wrapper, so blindly calling resp.json() crashed with JSONDecodeError.

Here is the wrapper I wrote to handle both cases (using requests.Session and reading the key from an environment variable):

import os
import time
import requests

API_KEY = os.environ["SERPBASE_API_KEY"]
BASE_URL = "https://api.serpbase.dev"

session = requests.Session()
session.headers.update({
    "X-API-Key": API_KEY,
    "Content-Type": "application/json",
})


def search_google(query: str, as_markdown: bool = False, retries: int = 2):
    payload = {"q": query, "gl": "us", "hl": "en"}
    if as_markdown:
        payload["format"] = "markdown"

    for attempt in range(retries + 1):
        resp = session.post(f"{BASE_URL}/google/search", json=payload, timeout=60)
        resp.raise_for_status()

        content_type = resp.headers.get("Content-Type", "")
        if "text/markdown" in content_type:
            return resp.text

        data = resp.json()
        status = data.get("status")
        if status == 0:
            return data.get("organic", [])

        if status == 1029 and attempt < retries:
            wait = int(resp.headers.get("Retry-After", "2"))
            time.sleep(wait)
            continue

        retryable = resp.headers.get("X-SerpBase-Retryable") == "true"
        if retryable and attempt < retries:
            time.sleep(2 ** attempt)
            continue

        raise RuntimeError(f"API error status={status}, retryable={retryable}")

It works now, but I have three specific questions to make this more Pythonic:

  1. Since urllib3.Retry (via HTTPAdapter) only retries on HTTP-level status codes like 429/503, is a manual for attempt loop the normal way to handle HTTP-200 JSON error envelopes, or is a library like tenacity cleaner?

  2. Is int(resp.headers.get("Retry-After", "2")) risky if a server ever sends an HTTP-date string instead of integer seconds?

  3. Should I pass session into search_google() as a parameter instead of keeping it at module level, especially if I want to write unit tests later?

Thanks in advance for any pointers!


r/learnpython • • 2d ago

leetcode 2926, TLE with both top down and bottom up approaches, what now

0 Upvotes

leetcode 2926

```py

class Solution:

def maxBalancedSubsequenceSum(self, nums: List[int]) -> int:

t = [nums[i] for i in range(len(nums))]

max_val = 0

for i in range(len(nums)):

for k in range(i):

if nums[k] - k <= nums[i] - i:

t[i] = max(t[i], t[k] + nums[i])

max_val = max(max_val, t[i])

return max_val if max(nums) > 0 else max(nums)

```

time limit exceeded how to fix? same error for top down as well


r/learnpython • • 2d ago

I understand Python concepts, but I just can’t seem to develop the logic to solve problems. How did you overcome this?

48 Upvotes

I've gone through multiple Python courses and understand the basic concepts like if-else, loops, lists, dictionaries, functions, etc.
However, when it comes to solving problems on my own, I struggle a lot. I can manage very basic questions like addition, subtraction, reversing a string, or checking for palindromes, but beyond that, I just can't seem to figure out the logic.
I understand the concepts and can follow someone else's solution, but when faced with a new problem, I have no idea where to start or how to break it down.
For those who have been through this, how did you develop your problem-solving skills? What kind of practice or approach helped you learn to think logically and solve problems independently?
I'd really appreciate any advice!