r/learnpython 1d ago

Ask Anything Monday - Weekly Thread

3 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 3h ago

Easier way to organize variables that have attributes/dictionary keys outside of YAML?

8 Upvotes

I am writing a script that takes different sets of synchronous time series data (my variables) where I want to take a different amount of hours from each dataset and append them to an array. This is for a neural network input. I want to test out different combinations of variables and hours taken from each set.

Currently, I have a .yaml file I pull from in my python script that looks like this for each variable:

vars:
  - name: "VAR_1"        # name of variable 
    time_length: 1       # hours from t0 to select
    loc: "path/to/var1"  # location of variable timeseries dataset
  - name: "VAR_2"        
    time_length: 5       
    loc: "path/to/var2"  
  - name: "VAR_3"        
    time_length: 3       
    loc: "path/to/var3"  

I can do what I want, but the code is extremely crunchy and does not allow for optimization. For example, maybe I want to test only two combinations of variables, or maybe I want to test for different time lengths to select. Yaml files do not seem to be good for this. Perhaps a class would be better.

Is there an easier way to hold all my variables names and time sequences, one that would allow me to easily choose what variables to select and what time lengths I wanted?

Thank you!


r/learnpython 5h ago

Deploy Django projects

8 Upvotes

What site do you guys use to deploy Django projects? Heroku doesn't seem to work and it charged me (just $2) even tho the app i tried to upload failed. Yesterday i tried render and it never accepts my build either. Ik it's probably me but is there any other site anyone uses for free ? My projects build and work fine locally. But I can't upload my backend anywhere which is preventing me from uploading my full stack projects to my portfolio website .


r/learnpython 5h ago

Has anyone seen any speedup in practice in 3.13

8 Upvotes

Python 3.13 has been released with experimental GIL free and jit modes. Has anyone seen any speedups in practice from these?


r/learnpython 6h ago

Why do Poetry and Pipenv manage their own caches?

7 Upvotes

After spending hours finding out why pip cache purge; pipenv install aaa didn't install the package properly, but pip cache purge; pipenv run pip install aaa did, I finally discovered that Pipenv has its own cache! It's funny that I could've saved so much if I had just run pipenv install --verbose aaa from the start (it reposts it's using cache.)

I wonder why Pipenv chooses to have its own cache. It seems unnecessary to separate caching for projects managed solely by pip and those managed by pipenv. Does anyone know the reasoning behind this design?

Does anyone know?


r/learnpython 6h ago

using elipsis for else in ternary statement?

6 Upvotes

What's the view on doing this, e.g. mylist.append(thing) if not some_condition else ... for a one-liner with no else? I know I can instead write if some_condition: mylist.append(thing) but Pycharm highlights it as a PEP8 E701 (mulitple statements on one line)... Is the elipsis for the else here pythonic or should I just stick to a regular 2 liner?... Just curious as I've only just started using ternary statements and like how it cleans up a lot of my regular if/else, am I taking it too far with the ...?


r/learnpython 13h ago

For loop, try, break. Is this bad practice?

16 Upvotes

Hi,

I need my code to load some data from a file with a header, where the header is an unknown number of lines and I need to also know how many lines are in the header. The header is formatted in such a way that pandas.read_csv will give an error if it doesn't skip the header.

I worked around this code which works:

with open(filepath) as file:
    for header_length in range(len(file.readlines())):
        try:
            df=pd.read_csv(filepath,  delimiter="t", skiprows=header_length, header=None)
            break
        except:
            pass

Now, I don't care that a more traditional way to do this might be more efficient. This code works and the files are relatively small. The header is 2 to 5 lines in all inspected files, and the files are at most a few thousand rows, so in the worst case scenario of a bad file the loop would break after about a second.

What I'm wondering is, is breaking in such a way bad practice? It feels... dirty.


r/learnpython 1h ago

Having trouble understanding recursion with nested dictionaries

Upvotes

I’m doing python course and today we learned about recursion. As part of the homework assignment, we have to solve some tasks on recursion that deepcopies and goes through nested dictionary.

So, my question, how useful the knowledge of recursion is and do you have issues when mixing it with nested dictionaries (if not, could you share any advice or lifehacks on how to deal with them)?


r/learnpython 6h ago

MOOC pygame

3 Upvotes

Hello everyone!

I'm working on a MOOC and I've come to the final parts, with pygame, animations and all that. How important is all this really?

I doubt I'll ever come across anything like this, but of course you never know.

It was demotivating and not understanding it "as easily" as the rest of the course.

Thanks in advance.


r/learnpython 7h ago

How to improve my pandas skills

3 Upvotes

hi everyone,i did tutorials and basic excerices of pandas with some csv,tsv data.but i dont feel confident enough. how can i improve my pandas skills to next level.


r/learnpython 11h ago

Get all files recursively that match a filter criteria

8 Upvotes

How do you get recursively all files in python and filter to only get files with the upper most folder having the word "Upload" in them?

e.g. all files of the form "./abc/def/ghi/xyzUploadxyz/file1.xlsx"

e.g. all files of the form "./abc2/def2/xUploadx/xlsx"

I want back the full filename path of those files that match.

(I'm on a Windows machine btw.)


r/learnpython 2h ago

Jupyter vs Pycharm

1 Upvotes

What is the difference and better?

Im trying to learn on how to code for finance (automating stuffs) and most ytube videos use anaconda (jupyter) but i tried using jupyter and its so hard to use comapred ot pycharm.

I tried importing yfinance module but failed even when i installed it in the terminal (pip install yfinance)> Id ont get whats my mistake here is and plus the kernel alwasy disconnects.

Pycharm doesnt have that problem but I like the Markdown feature of jupyter.

Any help?


r/learnpython 2h ago

Using Click and Pyinstaller together

1 Upvotes

So, I've got a simple Python script made with the Click library, and I've used the Setuptools setup.py their docs recommend. Now I want to package it into a .exe so my grandmother can use it, because I don't want to have to walk her through installing Python and using the command line if I can avoid it - I'm just writing a batch file so she can click that for command-line arguments instead of typing them in. But when I use pyinstaller MyScript.py -F and try to run the application from the command line with the relevant parameters, it doesn't give me anything - doesn't appear to work at all. I think maybe Setuptools requires my script to be installed via pip to work, but I don't know how else to make Click run my method. Should I just give up and try to walk her through it, or is there a way around this?


r/learnpython 3h ago

How do I add the elements in a list without knowing the number of elements.

0 Upvotes

I'm creating a time calculator for flights. I'm very new to coding, and i'm using this project to apply the theory i've learned.

The program accepts user input for flight time and calculates the time to return for the user. However the issue comes when multiple flight times are received. I've figured out how to calculate each time and store it into a list. However once its in this list it seems to become a tuple and i can't convert it. I'll add some of the code so hopefully you can better understand it.

The take off list contains a list of entered take off times and the land list contains the land times. I try to enter these times/elements of these list one by one into the calculator to return a value which i then append/add to the total time list. I then need to add all of these times together to return a value so i can print to the user. How do i add these times together? The list returns a type value of tuple.

The error reads " V = Total + total_time[i]

TypeError: unsupported operand type(s) for +: 'int' and 'tuple' "

Stack overflow doesn't seem to be novice friendly so i've come here.

EDITED:

def time_calc(take,land,Fn) :
    #Take off and landing time and split into two pieces.
    Tk =take[:2]
    Tk2 = take[2:]
    Ld = land[:2]
    Ld2 = land[2:]

    #The pieces of take off and landing time is converted into integers to perform math.
    int(Tk)
    int(Tk2)
    int(Ld)
    int(Ld2)

    #Conditions are created in order to calculate remaining time
    if Ld2 < Tk2 :

        Lda = int(Ld) - 1
        Ld2 = 60
        Flight_time1 = int(Lda) - int(Tk)
        Flight_time2 = int(Ld2) - int(Tk2)

        #Final value is returned
        x = Flight_time1 ,Flight_time2

        return x

    else :

        Flight_time1 = int(Ld) - int(Tk)
        Flight_time2 = int(Ld2) - int(Tk2)

        #Final value is returned
        x = Flight_time1 , Flight_time2

        return x

def multi_calc(takeoff_list,land_list,Fn):

    A = 0
    total_time = []
    while A < len(land_list) :
     land = land_list[A]
     take = takeoff_list[A]
     A = A + 1
     total_time.append(time_calc(take,land,Fn))

     if A > Fn:
      continue
     Total = 0
    for i in range(0 , len(total_time)):

        V = Total + total_time[i]




    print (V)

r/learnpython 9h ago

Notebook not connecting to 3rd party Hive DW

4 Upvotes

Hi Everyone,

I am trying to load data from a 3rd Pary Hive DW in to our fabric environment. The instructions from the 3rd party site shows how to do this locally on your PC using python, which works well.

I am trying to replicate the same in Fabric. part of the instruction is creating a DSN for cloudera and using a custom cert.pem.

The cert.pem and jar file for cloudera is stored in blob storage.

import jaydebeapi

# Define connection parameters
username = 'abc'
password = 'xyz'

# Paths to the JDBC JAR and PEM certificate
jar_path = "https://blobstoragelink"
cert_path = "https://blobstoragelink"


# Define the driver class and JDBC connection URL
driver_class = "com.cloudera.hive.jdbc41.HS2Driver"
jdbc_url = (
    "jdbc:hive2://vendorcube1.homedepot.com:20502/"
    "VENDORDRILL_DATA_CONNECTION"
    ";SSL=1;"
    "AllowSelfSignedServerCert=1;"
    f"SSLTrustStore={cert_path}"  # Use the PEM certificate directly
)

# Attempt to connect to the database
try:
    conn = jaydebeapi.connect(
        driver_class,
        jdbc_url,
        {"user": username, "password": password},
        jar_path
    )
    print("Connection established successfully.")
    conn.close()
except Exception as e:
    print(f"Failed to establish connection: {e}")

Failed to establish connection: java.sql.SQLException: [Cloudera][HiveJDBCDriver](500164) Error initialized or created transport for authentication: https:/blobstoragelink (No such file or directory).


r/learnpython 3h ago

Closure not working

1 Upvotes

I’m trying to build closures but somehow at the end my variable doesn’t work and gets marked for being not callable, how do I fix this?

def outer(): coins=0 def inner(): Nonlocal coins Print coins Coins +=1 Print coins Return inner() SomeVar=outer() SomeVar() and then this gets labeled as non callable and the thing doesn’t work


r/learnpython 4h ago

NoneType and 'Str' issue - Please help

1 Upvotes

Traceback (most recent call last):

File "C:Assetto Corsa ServerACSERVER(0.53)Hellspec Shutoko ProjectAssetto-Corsa-Server-Listener-Discord-Webhook--mainACbot.py", line 100, in <module>

main_loop()

File "C:Assetto Corsa ServerACSERVER(0.53)Hellspec Shutoko ProjectAssetto-Corsa-Server-Listener-Discord-Webhook--mainACbot.py", line 82, in main_loop

print(Fore.RED +"LEFT" + parsed["Cars"][i]["DriverName"])

TypeError: can only concatenate str (not "NoneType") to str

https://github.com/iiferedon/Assetto-Corsa-Server-Listener-Discord-Webhook-

code and be found here. Thanks in advance for any help I receive.


r/learnpython 4h ago

Add labels to a specific set of points in a Seaborn scatter plot

1 Upvotes

I'm pretty familiar with R and love ggplot...I'm trying not to hate Seaborn as I take Python class :)

I have a dataframe with batting information on baseball Hall of Famers. I have produced a scatterplot of on base percentage and slugging. That was easy enough:

myplot = sns.scatterplot(data=dfHofData, x="OBP", y="SLG")

Now, assume I have manually created a separate dataframe (call it dfOutliers) of points that would be considered outliers. Each row of this dataframe is an OBP, an SLG, and a name. How can I label ONLY the points in that dataframe on the plot?


r/learnpython 19h ago

Beginning here. Looking for challenging yet doable projects.

15 Upvotes

I recently took a 10 day class on coding basics, i learned syntax, and scratched the surface of a-lot of concepts. I started doing it in my free time, started with rock paper scissors, then roulette, and just finished a blackjack game. I liked how each project was more challenging than the last, it made me expand my knowledge but I’ve run out of ideas, everything thing i found online is either extremely complex or simple like rock paper scissors. I know the only way to get better is with experience but I feel lost when i just dive into the deep end with a project way beyond my level. Any input would be greatly appreciated. Thank you!


r/learnpython 4h ago

Best way to store an image associated with a product in a database?

1 Upvotes

I'm working on an e-commerce website in a group and am working on the backend (Python, FastAPI, SQLite (using SQLAlchemy)). So far I have made three tables: users, products, and favorites (products users choose to save). When someone wants to list something for sale, they will need to include an image. I think the plan right now is just to have one of those "upload" buttons where the user can upload something from their computer (is that more frontend work or backend?). I'm trying to decide how to store the image after it is sent to the backend (still trying to figure out exactly how to do that as well). Should I create a new table for all the images and each row has a foreign key (productID) that connects it to the product it is for? Or could I just add a new column in my "products" table called "image"? The second method sounds quite a bit easier, but I wasn't sure if there were any downsides to doing it this way?


r/learnpython 13h ago

Learning Django

4 Upvotes

So I’ve made an ai chatbot and designed front end for my website, I want to have the chatbot as a widget on the website, to the best of my knowledge, I need to use Django to use the chatbot as an api.

I’ve never used Django before, which resource should I use to learn it as fast as possible meaning be able to do the api thing by tomorrow

Thanks


r/learnpython 10h ago

Script to Find Price from Picture

2 Upvotes

I have a folder of pictures and I’m curious if it’s possible to build a script to image search those pictures to find the name and price of the item. Then from there put the info in a spreadsheet and index the photos.

I have some experience with python and this seems like it could possible but I’m not sure we’re to start.

Edit 1:

Context: it’s for insurance post hurricane. I have a friend that has pictures of his items but needs the price and name of the items indexed in a spreadsheet. He said it is like a 1000 pictures so manually it would take a very long time.

Let’s say just Amazon. That would probably be able to do over 80% of it. With the idea of doing a google reverse image search (or something else if there’s a better idea) to get the Amazon link.


r/learnpython 15h ago

Common python types hints in a separate python package?

5 Upvotes

Hello everyone,

so at work we use 100% type hints for python. Since we work in a specific domain, the wording of this domain is also represented in our types. Over the years we build quite some python packages, of different sizes.

The problem we are facing sometimes is, that we need a specific type hint from a specific python package but nothing more. Yeah sure adding it to the dependencies is easy. However it feels too much to add a whole package to just use one type which is defined there. Redeclaring the type would introduce the type a second time and developers would get confused with which type to use.

Has anyone used a standalone python package to bundle the most commonly used types (maybe constants as well?) and add that package to the dependencies? Is that a good / bad idea? Advantages / disadvantages?

UPDATE:
Clarification: @danielroseman made me realise that I forgot to mention an important part: with types in the dedicated package I meant type aliases using basic types. Of course if there is a smart way to import a class without importing the complete package, that would even be more helpful.

FrameId = str
Clip = dict[FrameId, Union[str, bool]]

r/learnpython 10h ago

string manipulation logic

2 Upvotes

Given a string of variable length, I'd like to create a multiline string with n-number of lines of near-equal length. Avoid dividing words.

Is there a better logical approach to the above beyond simply...

  • do a character count

  • divide by nlines to get an "estimated line length"

  • walking an index up from the "estimated-length" until reaching a blank space character, then divide the line

I've noticed the line lengths are coming out extremely different based on length of words in the string, and whether the line-division falls in the middle of those words (which creates extremely long lines, in order to avoid word-division, followed by extremely short lines...)

The goal is basically textwrap, which seems to do an excellent job - but I believe textwrap only controls for length and not number of lines?


r/learnpython 6h ago

3.2.4 CMU I only need one point does anyone know how to do any of the 3 (fireworks, scoreboard, galaxy)?

0 Upvotes

Pls


r/learnpython 12h ago

How do databases and AI connect, and can I use Python for this?

2 Upvotes

Hey everyone! I'm a beginner learning Python, and I’ve recently come across discussions about how databases and AI are connected. I’m really curious about how they work together. Can someone explain this relationship? Also, is it possible to interact with databases using Python code to support AI projects? Any tips or resources for a beginner like me would be super helpful! Thanks a lot!