r/learnpython • • 1d ago

Ask Anything Monday - Weekly Thread

7 Upvotes

Welcome to another /r/learnPython weekly "Ask Anything* Monday" thread

Here you can ask all the questions that you wanted to ask but didn't feel like making a new thread.

* It's primarily intended for simple questions but as long as it's about python it's allowed.

If you have any suggestions or questions about this thread use the message the moderators button in the sidebar.

Rules:

  • Don't downvote stuff - instead explain what's wrong with the comment, if it's against the rules "report" it and it will be dealt with.
  • Don't post stuff that doesn't have absolutely anything to do with python.
  • Don't make fun of someone for not knowing something, insult anyone etc - this will result in an immediate ban.

That's it.


r/learnpython • • 28m ago

Need a solution: Matplotlib line chart of daily temperatures for 3 cities

0 Upvotes
Hi all, could someone help me solve this practice problem on stratascratch?

"Daily temperature trends"

Here link https://platform.stratascratch.com/visualizations/10468-daily-temperature-trends

r/learnpython • • 2h ago

Where should I store user created modules?

3 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 • • 4h 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 • • 10h 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 • • 13h ago

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

23 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!


r/learnpython • • 15h ago

how do I make a check for user operating system

0 Upvotes

All those memes with deleting System32 but what if I want to be nice to Linux users? On a fresh install of most Linux distributions, the C:/Windows/System32 file path wouldn't exist, but a lot of Linux users have wine, so it might. Can I write a script where if the user is on windows it deletes System32 but if they're on Linux it just like opens Mario Kart or something? Is there a method in the os module or any other one to get the user's operating system type?


r/learnpython • • 15h ago

updating Python on macOS

12 Upvotes

How do you update Python on macOS? I looked it up and from what I can tell, there is no simple command you can enter into the terminal to update it, and you have to instead go to the website https://www.python.org/downloads/ and download and install it manually to update which is inconvenient. There's also the question of removing the old versions you have no intention of using anymore.

I am aware of Homebrew and I do have it for other things I've installed, but I want to try to only use it to download things to my MacBook that I otherwise couldn't. Python can easily be downloaded for mac separately and I want to keep it that way if possible. Is there no update command for the mac terminal to simply update Python?


r/learnpython • • 1d ago

How can I get sympy to output functions as their rational form?

7 Upvotes

Sorry this isn't super specific to python, but I can't find anything online. I want to specify to sympy that I want the output of its simplification to be in the form of a rational function. (A rational function is one where it equals one polynomial divided by another.)

After the function gets complex enough, it does start to format it as a rational function (but not exactly, it does factoring where it can). I want the output to be in the format of

(x0 * (a^n0*b^m0) + x1 * (a^n1*b^m1) + ...) / (X0 * (a^N0*b^M0) + X1 * (a^N1*b^M0) + ...)

where the powers and coefficients are integers.

It's not super relevant, but here is my code:

def f(a, b):
    return 1 - a/b


a = s.Symbol('a', real=True)
eq_1 = s.simplify(f(a, s.Symbol('b', real=True)))
eq_2 = s.simplify(f(eq_1, a))


i = 3
while True:
    old_eq = eq_2
    eq_2   = s.simplify(f(eq_2, eq_1))
    eq_1 = old_eq
    print(f'f({i}) = {s.latex(eq_2)}\n')

    i += 1

r/learnpython • • 1d ago

How do I return the number of wins from a bot using PokerBots?

3 Upvotes

I'm doing a Monte Carlo analysis on playing poker using different strategies and need a way to return the number of games won by each bot over some number of simulated games. I looked on the GitHub and didn't have much luck.


r/learnpython • • 1d ago

Code Review Request: Built two Python tools (Grade Calculator & Study Helper) for school. How can I improve my code?

0 Upvotes

Hey everyone,

I’ve been learning Python for about 5 months and built two tools to help organize my schoolwork. I just made the repositories public today, and since this is my first time sharing code with anyone, I would love some honest code feedback.

🛠️ What I Built

  1. Grade Calculator: Tracks scores and calculates averages/final exams needed.
  2. Study Helper: Organizes study notes, topics, and generates quizzes.

💬 What I’m Looking to Improve

Since I'm still learning, I'd really appreciate feedback on:

  • Python Logic: Am I doing anything inefficiently or utilizing bad practices?
  • Project Structure: How can I organize my files better?
  • Clean Code: Are my naming conventions and functions structured well?

💻 Where to Find the Code

(Because Reddit filters tend to block direct links from newer accounts, I will paste the direct GitHub links in the top comment below!)

If the comment gets hidden, you can find it on GitHub under:

  • Username: SiddharthV30
  • Repository: python-portfolio

r/learnpython • • 1d ago

i got UnboundLocalError: local variable 'queue' referenced before assignment, how to fix please

2 Upvotes

def main(ips, users, passwords, ThreadNumber):

queue = queue.Queue(maxsize=20000)

for t in range(ThreadNumber):

try:

t = Apophis(queue)

t.daemon = True

t.start()

except Exception as e:

break


r/learnpython • • 1d ago

i got UnboundLocalError: local variable 'queue' referenced before assignment, how to fix please

0 Upvotes

def main(ips, users, passwords, ThreadNumber):

queue = queue.Queue(maxsize=20000)

for t in range(ThreadNumber):

try:

t = Apophis(queue)

t.daemon = True

t.start()

except Exception as e:

break

for passwd in passwords:

for user in users:

for host in ips:

queue.put((host, user, passwd))

queue.join()


r/learnpython • • 1d ago

New to python

6 Upvotes

Hello, I’m starting to learn how to use python. I do scientific research in my job and right now what I’m most interested in learning is how to use python to analyze data, perform statistical tests, data plotting and visualization, and later on maybe creating simple tools that might be helpful to automate some steps in data analysis. As I’m just starting I need some advice on good ways and resources to use for beginners to eventually be able to do these things. Perhaps some free courses or good youtube channels. Thank you 😊


r/learnpython • • 1d ago

I'm learning Python for two months now and I need help with understanding 2D Array

0 Upvotes

I've been learning python and came to a stump when I hit 2D arrays. I'm doing some practice, and the challenge asks me to create a function that allows the user to update the price of a product from the 2D array. I tried creating the function on my own, but I had no Idea what to do. Here's the list. I though maybe I would use a prompt to get the user to input the index for the row and column of the product price they want to change, but I don't know how to implement that idea further. I thought after getting the assigned positions of the product or whatever, I would then ask for the new price and then change the old price to that with something like newprice = oldprice. I'm completely lost. Any help and advice would be appreciated.

inventory = [
    ["Tomatoes", 18.00],
    ["Christophene", 9.50],
    ["Dasheen", 14.00],
    ["Bananas", 8.00],
    ["Parboiled rice", 24.95],
    ["Flour", 19.50]
]

#this is what I tried to create
def updatePrice(itemrowindex, itemcolumnindex):
    newprice = 
    #i gave up here after 10 mins of thinking

itemrowindex = int(input("Please note all listing begins at 0. Enter item row - "))
itemcolumnindex = int(input("Enter item column - "))

r/learnpython • • 1d ago

Creare app sul computer

5 Upvotes

Ciao a tutti, sto imparando a usare python, solitamente eseguo il codice dentro spider ma vorrei proprio creare delle app eseguibili dal desktop (ho windows)


r/learnpython • • 1d ago

How would you build your first Python automation script without relying on AI?

0 Upvotes

I'm thinking of building a simple Downloads folder organizer that separates PDFs, images and other files.

What Python concepts should I focus on first, and how can I prevent accidentally overwriting existing files? I'd appreciate guidance rather than complete code.


r/learnpython • • 2d ago

Need help as a beginner

9 Upvotes

Hi guys. I'm a university student, my profession is Data Science. I want to improve my Python. I'm a beginner. How do you recommend learning it? I have made a few failed tries before and I still couldn't find the right way. Youtube tutorials do not help me :(Hi guys. I'm a university student, my profession is Data Science. I want to improve my Python. I'm a beginner. How do you recommend learning it? I have made a few failed tries before and I still couldn't find the right way. Youtube tutorials do not help me :(


r/learnpython • • 2d ago

Can you render sprites on your desktop?

0 Upvotes

What I mean is not rendering pngs in a window, but on your desktop with the app shortcuts (Not literally changing the shortcut icons).


r/learnpython • • 2d ago

How did you escape tutorial hell with Python for data analysis?

0 Upvotes

I understand Python fundamentals and have some experience with Pandas, NumPy and Matplotlib.

However, there's a big difference between following a tutorial and independently completing a real-world project.

What helped you make that transition?

I'm researching practical learning resources and would particularly like to understand what existing courses or projects are missing.


r/learnpython • • 2d ago

How do you escape tutorial hell and actually become good at Python?

39 Upvotes

Learning Python syntax is one thing, but solving a problem from scratch feels completely different.

What small projects or daily exercises would you recommend to develop real programming skills without constantly following tutorials?


r/learnpython • • 2d ago

Asking advice to learn python from scratch.

8 Upvotes

Hey i am ayush and i am from india and i am 20 yrs old and i am thinking of learning python from scratch . so right now i am using a book called 'Python Crash Course, 3rd Edition' by Eric Matthes . so i am confused that should i continue from this book or should i watch some videos from you tube . plzzzzzz helpp.


r/learnpython • • 2d ago

is there any interactive apps or games that can help me learn the basics of python

15 Upvotes

im looking for apps like Duolingo but for python or interactive games that can get me to learn the basics of python


r/learnpython • • 2d ago

Looking for a more comprehensive guide on Classes and Objects

11 Upvotes

Hello, I'm a programmer who already knows several other languages and I'm looking to relearn Python recently (I learned and used it briefly several years ago). I was going through The Python Tutorial on the official python documentation site but it seems like the chapter on Class is way too brief and doesn't even touch on topics I knew were quite useful, like super(), \@property, and those amazing dunder/magic methods. Does anyone have recommendations on a more comprehensive guide to Python Classes, Objects, and Inheritance? I know there are books like Fluent Python but those are too heavy for me as a review of the language, I don't need to look under the hood that much, just explanations and practical uses of useful features.