/r/learnpython

Photograph via snooOG

Subreddit for posting questions and asking for general advice about all topics related to learning python.


Rules

1: Be polite

2: Posts to this subreddit must be requests for help learning python.

3: Replies on this subreddit must be pertinent to the question OP asked.

4: No replies copy / pasted from ChatGPT or similar.

5: No advertising. No blogs/tutorials/videos/books/recruiting attempts.

This means no posts advertising blogs/videos/tutorials/etc, no recruiting/hiring/seeking others posts. We're here to help, not to be advertised to.

Please, no "hit and run" posts, if you make a post, engage with people that answer you. Please do not delete your post after you get an answer, others might have a similar question or want to continue the conversation.


Learning resources

Wiki and FAQ: /r/learnpython/w/index


Discord

Join the Python Discord chat

/r/learnpython

863,712 Subscribers

2

best problem solving

im learning python and im getting excited about it tbh , the problem is is that i need some practice on coding , and i have problems having source of learning , whats the best Channel or source to learn secondly, i need site that provide problem solving like leatcode , i really hope you fan help and thank you

0 Comments
2024/11/10
10:16 UTC

6

Why shouldn't you use an IDE when first starting?

I see this thrown around quite a lot. Why should I make myself suffer?

My first few python scripts I wrote in notepad. Then I switched to VSCODE.

VSCODE can handle virtual environments, can display your working folder so you don't need to keep ALT+Tabbing and you can even install tabnine for AI tab completion. If I'm following a tutorial and write something I don't understand by copying I can even highlight some code and ask tabnine to explain to me what it does.

If I'm writing some python, I forget to put an : at the end of a def or an if line.. why does it matter if VSCODE tells me that? What does it matter that VSCODE makes different things a different colour so it's easier to read? Why do you have to suffer in notepad as some kind of sado-masocistic learning experience?

If technology can take the annoyance out of having to wade through a screen of code to find the missing : or ) why does that matter?

43 Comments
2024/11/10
09:39 UTC

3

Am I ready to learn how to make animations using python?

One of the main reasons I learned Python is to create physics or math animations. The thing is, I don't want to start learning something far above my level and waste my time, which is why I'm asking for advice.

For context, I've learned Python basics (loops, zip/map/filter funcs, list comprehensions, sets and dictionaries, modules and classes, etc.) and explored Matplotlib and Sympy on a basic level.

Is my skillset enough to start learning how to animate? If so, which library should I use? I'm hoping to start with a library that's really to use rather than flexible and useful.

2 Comments
2024/11/10
09:10 UTC

0

who can help me to code in pyton

#pyton

5 Comments
2024/11/10
09:02 UTC

0

Need help with understanding in short what the below Python code says?

candidate_python_test.py - C:/Users/jnevins/Desktop/python/candidate_python_test.py (3.7.9)

File Edit Format Run Options Window Help

import snowflake.connector

from snowflake.connector import DictCursor

import time

import csV

import datetime

import os.path

from os import path

import pandas as pd

from snowflake.connector.pandas tools import pd writer

def readtxt (path to_file):

rows []

myFile open (path to file, 'r')

row myFile.readline().strip()

while row != :

rows.append(row)

row myFile.readline().strip()

return rows

def main():

datetime.date.today().strftime("Ymd") today

credentials path filenamel C:/Users/jnevins/desktop/python/credentials.txt' 'G:/My Drive/TEST FOLDER/PYTHON TEST FILE today .csv'

sql script C:/Users/jnevins/desktop/python/python_test.txt

with open (sql script, 'r') as myfile:

myfile.read() sql

readtxt (credentials path) credentials

OKTA USER credentials [2]

OKTA PASSWORD credentials [3]

SNOWFLAKE ACCOUNT='snowflake'

ctx snowflake.connector.connect(

user=OKTA USER,

password=OKTA PASSWORD,

account='natera

)

CS ctx.cursor()

cs.execute("USE ROLE RCM ANALYST PHI")

cs.execute("USE WAREHOUSE RCM WH")

cs.execute("USE RCM.RCM")

try:

results cs.execute(sql)

column names [i[0] for i in cs.description]

rows results.fetchall()

finally:

cs.close()

newFile open (filenamel, 'w', newline ',encoding="utf-8")

with newFile:

writer csv.writer(newFile)

writer.writerow(column names)

writer.writerows(rows)

time.sleep (5)

main()

8 Comments
2024/11/10
07:54 UTC

2

ModuleNotFoundError

i've been using linux mint recently and i am facing problems when using python

first i had this problem with pip installation. it said something like this is an externally managed environment and packages cannot be installed and also said that you can create venv and do pip installation in the venv but when i tried to create a venv it threw me an error and source venv/bin/activate was not working

but i somehow installed packages with pip install <package-name> --break-system-packages and the installs were done

but i cannot import the packages and i am getting a ModuleNotFoundError

help please

6 Comments
2024/11/10
06:41 UTC

4

I'm learning numpy right now

What is the difference between an array and a list?

10 Comments
2024/11/10
04:46 UTC

2

jupyter notebook not showing cells

as title, my jupyter notebook isnt showing in its usual format of cells after shutting down and rerunning it. code in my notebook is like this now instead of the usual cells " "cells": [

{

"cell_type": "markdown",

"id": "ab7bcdb1-032e-4bcb-b4df-2f2e219e2f5d",

"metadata": {},

"source": [

" HEART DISEASE PROJECT\n",

" "

]"

how do i get to show cells again? very new to this so please help

1 Comment
2024/11/10
04:27 UTC

0

PLEASE CAN SOMEONE HELP ME IM ABOUT TO FLIP SHIT RIGHT NOW!! (Jupyter Notebooks)

For the past three hours I have been trying to upload some csv files for my project. 4 days ago I was able to get it to work but I had problems at first. Now today I can't upload anything at all. No matter if I get the file path from jupyter. No matter if I copy down the file path from finder. Literally nothing works. I've watched about 6 youtube videos and I asked ChatGPT4 and I've been try to troubleshoot but nothing is working.

I am using a MACBOOK.

Yes I ran the cell that contained all my imports.

Day #1: First I uploaded the csv by copying the name of the file and adding csv. This didn't work for some reason EVEN THOUGH thats how I've been uploading every single csv I have been given for my class.

Input:
ow_ob_95_23 = pd.read_csv( 'OF_OW_OB_DataSet_1995_2023.csv', nrows= 30)

The next thing I did was, I copied the path from file in jupyter.

Input:

ow_ob_95_23 = pd.read_csv('OF__FIN_24/OF_OW_OB_DataSet_1995_2023.csv', nrows= 30)

AND THIS WORKED!!! until it didn't.

Later that night I went to work on my project some more and when I ran the code again, I was receiving error messages stating that my file is not defined/no file or directory I was playing around and I decided to try my old way of loading a file:

ow_ob_95_23 = pd.read_csv( 'OF_OW_OB_DataSet_1995_2023.csv', nrows= 30)

AND THIS WORKED!!! until today.

Today I've tried:

ow_ob_95_23 = pd.read_csv('OF_OW_OB_DataSet_1995_2023.csv', nrows= 30)

ow_ob_95_23 = pd.read_csv('OF__FIN_24/OF_OW_OB_DataSet_1995_2023.csv', nrows= 30)

file_path = '/Users/myname/Downloads/OF__FIN_24/OF_Cardio_BMI_NA.csv'

ow_ob_95_23 = pd.read_csv('/Users/myname/Downloads/OF__FIN_24/OF_Cardio_BMI_NA.csv', nrows= 30)

If anyone knows why this is happen PLEASE let me know!!!! THANK YOU

9 Comments
2024/11/10
03:23 UTC

2

Opencv + Harvester + DALSA Linea GigE

Hello. I'm having a problem acquiring images from Harvester, which in turn will use Opencv to display and record the images. Has anyone used these two libraries together and managed to use them on a DALSA Linear camera? I really need some help on this topic. I can send settings (acquisitions and triggers) but when I get to the buffer it's empty.

0 Comments
2024/11/10
02:20 UTC

4

Input not working in VSC

I was trying to do a homework and after one change in the code suddenly input doesnt work and it worked perfectly before as I was experimenting with the code. After I deleted every other line its still not working.

I can’t attach an image so I’ll try to explain what it shows: when I run it, python REPL only displays the actual line of code

9 Comments
2024/11/10
00:00 UTC

6

Looking for a tool to analyze a large Python project and determine fan-in and fan-out of specific functions

Hi everyone! I’m working on a large and complex Python project (thousands of lines of code), and I need a reliable solution to analyze the fan-in and fan-out of specific functions. My main goal is to understand the dependencies of certain functions and trace which other functions call them or are called within them.

So far, I’ve tried a few tools, including static analysis tools like Understand and PyCG, but I’m running into compatibility and accuracy issues, especially due to Python’s dynamic nature. Some tools struggle with implicit or dynamic calls, which limits complete visibility into dependencies.

Ideally, I’m looking for a tool that:

  1. Supports large-scale projects.
  2. Can generate an accurate call graph (or something similar) showing fan-in and fan-out for selected functions.
  3. Handles indirect and dynamic calls commonly found in Python.
  4. Offers a way to export data or visualize dependencies.

Does anyone have experience with tools that are suited for this type of analysis in Python? I’m open to both open-source and commercial solutions if they’re worth it. Any recommendations would be greatly appreciated!

Thanks in advance!

1 Comment
2024/11/09
22:52 UTC

31

Python Loops

Completely stuck on the concept of loops. Ive looked through all the recourses possible to get a grasp of it but i just cannot get my mind to understand it!

Someone that has tips to cure this illness of mine?

47 Comments
2024/11/09
20:28 UTC

7

Improving huffman decompression

Im trying to improve the computational speed of this huffman, for small input hex strings its fine but the bigger the input string is the time increments considerably

with a large enough string speed(example below) goes up to x50 1ms vs 55ms+

Im wondering if im doing anything bad and theres any way of speeding the process up, i tried for hours everything that come to my mind and im not sure how to improve further from here any suggestions are welcome

Code

expected output:
Total execution time: 1.04 milliseconds

19101-0-418-220000000|19102-0-371-530000000

But if you try with a bigger string it gets extremely slow, id like to improve the performance i tried cythoning it but didnt improve it by any mean, if anyone has any idea of what i can be doing wrong

With this second input hex it takes 55ms

big hex string

5 Comments
2024/11/09
19:56 UTC

2

Non Cohesive pdf image extraction as Cohesive

Hi there. I am extracting images from pdf using pymupdf library. Some pdfs have images that are actually non cohesive cutouts assembled together to be a visually complete image. Users might upload these pdfs and I need a way to process the image as one complete image from a given page. Note that when a pdf is formed lets suppose from a word document. Then if a person manually suppose copy paste an image from software like visio or any other flowchart software, the pdf automatically makes these images converted to 100s of pieces visually looking like a 1 image, but on inspecting it in pdf software or python extraction, the reality comes to light

0 Comments
2024/11/09
19:34 UTC

4

help find index error

import random

MAX_LINES = 3 MAX_BET = 100 MIN_BET = 1

ROWS = 3 COLS = 3

symbol_count = { 'A': 2, 'B': 4, 'C': 6, 'D': 8 }

def get_slot_machine_spin(rows, cols, symbols): all_symbols = [] for symbol, symbol_count in symbols.items(): for _ in range(symbol_count): all_symbols.append(symbol)

    columns = []
    for _ in range(cols):
        column = []
        current_symbols = all_symbols[:]
        for _ in range(rows):
            value = random.choice(current_symbols)
            current_symbols.remove(value)
            column.append(value)
            
        columns.append(collumn)
        
    return columns
    

def print_slot_machine(columns): for row in range(len(columns[0])): for column in columns: for i, column in enumerate(columns): if i != len(colums) -1: print(column[row], '│') else: print(column[row])

def deposit(): while True: amount = input('What would you like to deposit? $') if amount.isdigit(): amount = int(amount) if amount > 0: break else: print('amount must be greater than 0') else: print('please enter a number')

return amount

def get_number_of_lines(): while True: lines = input('enter the number of lines to bet on (1-'+ str(MAX_LINES) +')? ') if lines.isdigit(): lines = int(lines) if 1 <= lines <= MAX_LINES: break else: print('enter a valid number of lines') else: print('please enter a number')

return lines

def get_bet(): while True: amount = input('What would you like to bet on each line? $') if amount.isdigit(): amount = int(amount) if MIN_BET <= amount <= MAX_BET: break else: print(f'amount must be between ${MIN_BET} - ${MAX_BET}.') else: print('please enter a number')

return amount

def main(): balance = deposit() lines = get_number_of_lines() while True: bet = get_bet() total_bet = bet * lines

    if total_bet > balance:
        print(f'you do not have enough to bet that amount. Your current balance is: ${balance}')
    else:
        break
    
print(f'you are betting ${bet} on {lines} lines. Total bet is equal to ${total_bet}')

slots = get_slot_machine_spin(ROWS, COLS, symbol_count)
print_slot_machine(slots)

main()

8 Comments
2024/11/09
18:56 UTC

4

Which Framework To Choose

I am spring boot dev but now I want to learn python web development framework. I want it for personal projects (not scalable). So which is best framework?
I am thinking of FastAPI

2 Comments
2024/11/09
18:43 UTC

2

Desperately need assitance to install PySimpleGUI!

Hello guys,

I have an assignment due tomorrow midnight and it includes doing stuff with PySimpleGUI. Problem is, I can't get it installed and I've tried everything. I am on a newer macbook and use VS Code.

What I do is open the computer terminal and install the gui. When I check if it is installed it says it is. The versions are all matched and everything! Then when I enter VS Code and import the gui as sg and print it, it says "name "sg" is not defined"??

As I have spent so long trying to fix this, the only thing in the process I can see an issue with is the placement of the interpreter.. the computer terminal says one thing but in VS Code it always recommends /usr/bin/python3 - which does not match with the placement of the gui but that doesn't come up as an option.

I've seen all the videos, read all the websites, used up my free chats with the homie chatgpt and I'm still lost.. don't even know if this group is about stuff like this - if not, please guide me in the right direction.

Thank you lads

9 Comments
2024/11/09
18:22 UTC

1

Can't download Python, getting error code 0x80070005 anyone can help?

I'm trying to download python on my pc (windows 10) and i'm getting this error and can't download it because of it.
can anyone help me? I have no idea what to do so it works, I tried to search for solutions online but couldn't find anything that works, this is the error log i get:

[3E24:1210][2024-11-09T18:13:01]i370: Session begin, registration key: SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{e9b7c837-5066-4f10-851a-69179f987b18}, options: 0x7, disable resume: No
[3E24:1210][2024-11-09T18:13:01]e000: Error 0x80070005: Failed to create cache directory: C:\Users\Jordan\AppData\Local\Package Cache\{e9b7c837-5066-4f10-851a-69179f987b18}\
[3E24:1210][2024-11-09T18:13:01]e000: Error 0x80070005: Failed to create completed cache path for bundle.
[3E24:1210][2024-11-09T18:13:01]e000: Error 0x80070005: Failed to cache bundle from path: C:\Users\Jordan\AppData\Local\Temp\{B5CC49E9-C569-48BA-BDFE-986845D17078}\.be\python-3.12.7-amd64.exe
[3E24:1210][2024-11-09T18:13:01]e000: Error 0x80070005: Failed to begin registration session.
[3E24:1210][2024-11-09T18:13:01]e000: Error 0x80070005: Failed to register bundle.
[3E24:1210][2024-11-09T18:13:01]i399: Apply complete, result: 0x80070005, restart: None, ba requested restart:  No
11 Comments
2024/11/09
18:19 UTC

24

Completely new to Python and seeking advice

Hey all i am currently looking to learn python I have 0 coding experience and would like any advice on how to make this journey of learning easy and fun :) Would really appreciate recommendations on resources and apps to use Thank you

23 Comments
2024/11/09
18:04 UTC

7

(Pygame module) How do i reduce the height of the window while running?

https://preview.redd.it/367lpexlxwzd1.png?width=822&format=png&auto=webp&s=9ee7c34091deb907a591116f52bbfa974e2b2d3d

Id like to make it so that the height of the window reduces by a given amount of pixels over a given amount of time. I've tried this through a subroutine and through putting a nested while loop in the running loop. No errors when run, on the left program it prints "three" (indicating that subroutine is indeed being called) and the window works fine at 1280x720 60fps, but no change is seen,

2 Comments
2024/11/09
17:43 UTC

3

cross_encoder/Marco_miniLM_v12 takes 0.1 seconds in local and 2 seconds in server

Hi,

I've recently developed a Reranker API using fast API, which reranks a list of documents based on a given query. I've used the ms-marco-MiniLM-L12-v2 model (~140 MB) which gives pretty decent results. Now, here is the problem:

  1. This re-ranker API's response time in my local system is ~0.4-0.5 seconds on average for 10 documents with 250 words per document. My local system has 8 Cores and 8 GB RAM (pretty basic laptop)

  2. However, in the production environment with 6 Kubernetes pods (72 cores and a CPU Limit of 12 cores each, 4 GB per CPU), this response time shoots up to ~6-7 seconds on the same input.

I've converted an ONNX version of the model and have loaded it on startup. For each document, query pair, the scores are computed parallel using multithreading (6 workers). There is no memory leakage or anything whatsoever. I'll also attach the multithreading code with this.

I tried so many different things, but nothing seems to work in production. I would really appreciate some help here. PFA, the code snippet for multithreading attached,

def __parallelizer_using_multithreading(functions_with_args:list[tuple[Callable, tuple[Any]]], num_workers):

"""Parallelizes a list of functions"""

results = []

with ThreadPoolExecutor(max_workers = num_workers) as executor:

futures = {executor.submit(feature, *args) for feature, args in functions_with_args}

for future in as_completed(futures):

results.append(future.result())

return results

Thank you

1 Comment
2024/11/09
17:39 UTC

21

This is my first game

Please enjoy

This is my first game Please send ideas on how to improve it

https://www.programiz.com/online-compiler/4yAbWnouxdc5n

8 Comments
2024/11/09
17:15 UTC

5

Recommendations for Free Python Learning Resources?

Hi everyone! 👋

I’m starting my Python journey and would love some guidance on free resources. I already know about Bro Code on YouTube and W3Schools. Do you have other favorite free sites, channels, or courses that really helped you grasp the basics (or beyond)?

Any tips on structuring my learning would also be really appreciated. Thanks a ton! 😊

2 Comments
2024/11/09
16:40 UTC

3

i am getting a strange error. what do i do?

Traceback (most recent call last):

File "/home/chingus_pingus/Desktop/cs_hw/main.py", line 37, in <module>

data_en(id,sub,topic,ques,mark,difficulty)

File "/home/chingus_pingus/Desktop/cs_hw/funcs.py", line 31, in data_en

cursor.execute("INSERT INTO ques values (%s,%s,%s,%s,%s,%s);",(id,sub,top,ques,mark,diff))

File "/home/chingus_pingus/.local/lib/python3.12/site-packages/mysql/connector/cursor_cext.py", line 345, in execute

prepared = self._connection.prepare_for_mysql(params)

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "/home/chingus_pingus/.local/lib/python3.12/site-packages/mysql/connector/connection_cext.py", line 878, in prepare_for_mysql

result = self._cmysql.convert_to_mysql(*params)

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

_mysql_connector.MySQLInterfaceError: Python type builtin_function_or_method cannot be converted

10 Comments
2024/11/09
16:07 UTC

2

Learning python through competitive programming

hey i am new to python .. i know c++ , c
i just wanted to know about some website that will give me easy problems to solve problem with python and di dont know what happened to my codeforce .. it saying runtime error while doing with python

1 Comment
2024/11/09
16:03 UTC

5

I am coding a Tic Tac Toe bot and need input

My current version is incredibly basic. It uses a random number generator for numbers that correlate with the 9 spaces on the board. It keeps generating new numbers until it finds an unoccupied space. It works, but is very basic and has no strategy. Its immpossible to lose against.

I want to make it have strategy and not as easy to beat. Im thinking about taking my code block that I used for checking the board for wins, and slightly tweaking it to allow for the bot to see potential wins and block them. I think this could work. I also am considering that I could use this method to make the bot try to get it's own win.

The one problem is that while I want the bot to have a fighting chance, I dont want it to be impossible. My thought is that I give it a 2/3 chance to use a strategy on a given turn using a random numger generator and a boolean variable. Would this potentially work? Is there a different way I should be doing it?

8 Comments
2024/11/09
15:13 UTC

5

Help Regarding the statistics module

Hello,

I just new to the stastics module and was trying out some stuff while reading the documentation .

Intrestingly , I did these thing
>>> data = [1,2,3,4,5]

>>> s.median(data)

3

>>> s.mode(data)

1

now my question is regarding the mode of the data

as far as i know (crrct me if im wrong) , mode (which refers as most repeating element of a given set ), in this case should be nomode (since no repetition )

but i get 1 as output

can anyone tell me what is 1 symoblising here??

IK its a shitty question , might help me understand a bit !

3 Comments
2024/11/09
14:02 UTC

1

Error: Python packaging tool ‘setuptools’ not found

I’m trying to write my first python project, I’m a complete beginner, it’s a simple web scraper following the video below by Corey Schafer. He’s using Sublime but I wanted to get used to an IDE so picked PyCharm (might be a mistake).

I’m trying to install some interpreters, beautiful soup and requests as per video. I keep getting the setuptools not found error. Yet in terminal I put ‘pip show setuptools’ and it says it’s there. Also if I put ‘pip show beautifulsoup4’ it also says it’s there.

What am I doing wrong?

https://youtu.be/ng2o98k983k?si=sphQC3ZNLl89wAHP

5 Comments
2024/11/09
13:51 UTC

3

Atomic operations

I have a program with

  • A Producer thread (reads data from a socket, updates a shared dictionary, multiple times a second)
  • A Monitor thread (polls the length of the dictionary and if it changes notifies the UI)
  • A few other Customer threads that occasionally get information from the dictionary, remove items from it, etc

Right now, I'm protecting all access to the shared dictionary with a mutex. I'm concerned that the Monitor thread might be frequent enough to occasionally block the Producer. Are either of these two solutions atomic:

  1. Monitor thread calls len(the_dict) without locking
  2. Producer thread updates a count integer variable inside its lock, and Monitor thread reads count without the lock. Of course, any changes by the Consumer threads would also update count inside the lock
5 Comments
2024/11/09
13:44 UTC

Back To Top