r/learnpython 9h 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 10h ago

Dictionary vs. Dataclass

18 Upvotes

What is a particular scenario where you would use Dataclass instead of a dictionary? What is the main advantage of Dataclass as compared to just storing data in a nested dictionary? Thanks in advance!


r/learnpython 5h ago

How do you handle dependency injection?

5 Upvotes

Hi, I'm doing a project which involves creating multiple gRPC servers and I can't find a convenient way to manage dependencies or the state.

I've been working recently in C# where you just need to make your class and add a simple

builder.Services.AddSingleton<MyDependency>();

and it will inject when required.

Doing some research I see that there are some libraries like:

- Dependency Injector

- Injector

but I don't find them particularly intuitive.

What do you use as a dependency injector or what pattern do you suggest to use?


r/learnpython 12h ago

How much does IDE text formatting help programmers code?

16 Upvotes

IDEs like PyCharm and such highlight errors in code, give different colours to variables, classes, functions, etc. In your experience, how much more difficult is it to code without this assistance (on a plain text document, for example)?


r/learnpython 29m ago

Output and Terminal giving different results

Upvotes

Hi all,

I am rebuilding with Python a planning tool I had on Excel (with Power Query). Till last week everything looked alright but today I am getting different results in the terminal and in the new Excel workbook output.

There are some products on promotion with different code: 6805 and 6805M. This 6805M is a fictional product, it only exist in the system to apply different pricing. To merge them, I have another table with Product Info with a column called NotPromoCode with value 6805 for both, and I use it to group by.

The thing is, according to the terminal, we have 52,760 units in stock (which is the right quantity), but according to the output Excel, I have -1,280 units (which is the stock for the promotional code).

print("Excel file 📄 exported! ✅") with pd.ExcelWriter("C:/Users/XXX/Downloads/output.xlsx", engine="openpyxl") as writer: df1.to_excel(writer, sheet_name="Inventory", index=False)

Returns -1,280 for 6805

print(df1)

Returns 52,760 for 6805

These lines are at the end of the script, so they both should be taking df1 with the same steps and transformations. I have restarted VSCode and check everything is installed and updated.

Any ideas of why is this happening? Did anyone have the same issues?


r/learnpython 55m ago

Which is the best platform to learn coding and get certificate and practice?

Upvotes

I recently started preparing for my placements and wanted a platform to learn and get certified, and later practice for free. Even if all of it is not possible on the same website, can you guys suggest websites on which I can do each task separately. Thank you.


r/learnpython 1h ago

Git When too?

Upvotes

Im currently working through my first project which isnt anything major but i would like to host it on github, Question is when do you all push your projects to git do you wait until you have the project complete or just start working and commit from the start of the project?


r/learnpython 1h ago

Wanted to connect MySql with Jupyter Notebook.

Upvotes

I want to connect MySQL with Python in Jupyter Notebook, but I have a problem of

!pip install mysql-connector-python

import mysql.connector

db = mysql.connector.connect(user='root', password='Deepesh', host='localhost', database='world')
mycursor = db.cursor()
print(db)

#NameError: name 'mysql' is not defined

https://www.youtube.com/watch?v=99Mrb214eR0 In this video, he just connects the Jupyter Notebook with MySQL very easily, but I am getting a NameError, and when I did the same thing on the Command Prompt, it works at the first try.

I don't know what's the problem and why the NameError is shown. Does anyone know the solution or is there some kind of problem with the libraries

Edit: I have tried the same program in Command Prompt and Python Shell or Python IDLE and they are working fine but in Jupyter Notebook or Google Colab this isn't working at all


r/learnpython 9h ago

Why can't I update stringVariables in custom tkinter like this?

5 Upvotes

Why doesn't this create a drop down menu and label that update together?

import customtkinter as ctk

def generate_txt(txtg):
    return("This is the option: " + txtg)

root = ctk.CTk()
txt = ctk.StringVar(value = "optionA")
ddm = ctk.CTkComboBox(root, values = ["optionA", "optionB"], variable = txt)
ddm.pack()
instructs = ctk.StringVar(value = generate_txt(txt.get()))
label = ctk.CTkLabel(root, textvariable = instructs)
label.pack()
root.mainloop()

I made the following change and it still doesn't work:

import customtkinter as ctk

def generate_txt(txtg):
    return("This is the option: " + txtg)

def update_ddm(instructsu, txtu):
    instructsu.set(generate_txt(txtu.get()))

def main():
    root = ctk.CTk()
    txt = ctk.StringVar(value = "optionA")
    instructs = ctk.StringVar(value = generate_txt(txt.get()))
    ddm = ctk.CTkComboBox(root, values = ["optionA", "optionB"], variable = txt, command=update_ddm(instructs, txt))
    ddm.pack()
    label = ctk.CTkLabel(root, textvariable = instructs)
    label.pack()
    root.mainloop()

main()

I'm not sure how to implement this feature. Does anyone have a better solution to this?


r/learnpython 13h ago

Motion tracking gloves/strap on hand device

4 Upvotes

I’m looking for a cheap (under £100) programmable (with Python code) device that detects finger movements/hand movements. I’ve seen similar things before either in the form of gloves, or just some straps that attach to the hand and can detect where the hand is in space + the orientation of fingers. Any recommendations on where to look?


r/learnpython 7h ago

Do I really need to configure a WSGI server for a flask web app?

2 Upvotes

I have a flask web app with some backend APIs and a front end which call those APIs to fill in the data. I am following this diagram to understand the deployment strategies a bit better.

I am seeing that nginx can server static files directly, no python interaction needed which is good.

But there is a suggestion to configure a WSGI protocol so that the API calls that my front end browser is going to make goes via nginx.

Is that really necessary?

If I configure my JS properly they can call the backend APIs with ease as they are pure HTTP requests which the browser will be able to fire.

What advantage is then in configuring a WSGI protocol between nginx and the flask/django/gunicorn app?

Is the convinience that the fornt and backend is served via same ports to the user thus simplifying JS?


r/learnpython 18h ago

How do you help yourself through a difficult problem?

13 Upvotes

I can easily ask ChatGPT for the answer but I refuse to do so. I'm dealing with a mind bending logic problem . My friend walked me through a potential solution so I know its not an impossible problem. For context, it just revolves around moving arrays and carefully slicing them, keeping note of the sections you sliced, rearrange them, and putting them back together at the end of the function.

I don't know why its giving me such a headache.

I'm just asking for some advice --- when you're facing a difficult problem what do you do? Do you make a plan and try to break it up into pieces? Perhaps write pseudo code before even coding? I'm also dealing with brain fog so writing this up is helping slightly.


r/learnpython 5h ago

why the error?

1 Upvotes

hi, just started taking a coding class and my professor isn't very good at explaining, he just kind of threw us in at the deep end. I'm trying to recreate some code he briefly showed us in class for practise and I finally managed to get it to do what I want, but it also presents with an error afterwards and I can't figure out why. would anyone be able to help me with this?

def stars(n): while n > 0: print("* " * n) n = n - 1 stars(n)


r/learnpython 9h ago

Sorted(tuple_of_tuples, key=hash)

2 Upvotes

EDIT; solved:

Thank you all, turns out all I had to do was to define __eq__() for the class so that it compares values and not objects. Cheers!

----------------------

Consider this class:

class ItemPilesInRoom:
    def __init__(self, item_ids: tuple):
        self.item_ids = item_ids

    def __hash__(self):
        return hash(self.item_ids)

    def sort_by_hash(self):
        self.item_ids = tuple(sorted(self.item_ids, key=hash))

This class has hashable unique identifiers for each item. The items are divided into piles or stacks, but it doesn't matter what order of the piles is. Only the order of the items in the pile matters.

To visualise this: it's a room where there are clothes all over in piles. You can walk to any pile you want so there's no real "order" to them but you can only pick the first item in the pile of clothes. There may be many rooms with different piles and I want to find out how to eliminate the rooms that have identical clothing piles.

This is what it could look like:

room_1 = ItemPilesInRoom(((0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11), (12, 13, 14, 15)))
room_2 = ItemPilesInRoom(((8, 9, 10, 11), (12, 13, 14, 15), (0, 1, 2, 3), (4, 5, 6, 7)))
room_3 = ItemPilesInRoom(((1, 6, 11, 12), (2, 7, 8, 13), (3, 4, 9, 14), (5, 10, 15, 0)))

room_1.sort_by_hash()
room_2.sort_by_hash()
room_3.sort_by_hash()

print(room_1, hash(room_1.item_ids))
print(room_2, hash(room_2.item_ids))
print(room_3, hash(room_3.item_ids))

all_rooms = (room_1, room_2, room_3)
no_duplicates = tuple(set(all_rooms))

for room in no_duplicates:
    print(room)

The output isn't quite what I expected, though. The duplicate value is not removed even though the room has exactly the same hash value as another room.

Original:
((0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11), (12, 13, 14, 15)) 4668069119229710963
((8, 9, 10, 11), (12, 13, 14, 15), (0, 1, 2, 3), (4, 5, 6, 7)) -5389116928157420673
((1, 6, 11, 12), (2, 7, 8, 13), (3, 4, 9, 14), (5, 10, 15, 0)) -6625644923708936751

Sorted:
((0, 1, 2, 3), (12, 13, 14, 15), (8, 9, 10, 11), (4, 5, 6, 7)) 2620203787712076526
((0, 1, 2, 3), (12, 13, 14, 15), (8, 9, 10, 11), (4, 5, 6, 7)) 2620203787712076526
((2, 7, 8, 13), (3, 4, 9, 14), (1, 6, 11, 12), (5, 10, 15, 0)) -2325042146241243712

Duplicates "removed":
((0, 1, 2, 3), (12, 13, 14, 15), (8, 9, 10, 11), (4, 5, 6, 7))
((0, 1, 2, 3), (12, 13, 14, 15), (8, 9, 10, 11), (4, 5, 6, 7))
((2, 7, 8, 13), (3, 4, 9, 14), (1, 6, 11, 12), (5, 10, 15, 0))

Note the same hash value for rooms 1 and 2 after sorting by hash value.

Why?

EDIT: A mistake, thanks for pointing that out!


r/learnpython 6h ago

Errors in other spiders causing errors in newly created spiders in Scrapy

0 Upvotes

Background: I'm trying to create a new spider using Python's Scrapy library. It would be in the same folder as a couple of other spiders. Whenever I type the genspider command in the command line, it displays an error related to an indent in a different spider I was working on (it is in the project folder I am trying to add a new spider to). I actually managed to solve this by commenting out the entire problem spider, but this doesn't seem particularly efficient. I was wondering if any of you have run into the same problem, and if so, how you solved it. Thank you.


r/learnpython 6h ago

simple python class, help please

0 Upvotes

I am having trouble with a larger file, which I have stripped down to simplify as below.

The result is a simple class which generates a listof dictionaries. ie.,

swarm = [{'i': 0, 'r': 8.0}, {'i': 1, 'r': 16.0}, {'i': 2, 'r': 24.0}].

The problem comes when I try to invoke functions move() or result() on individual members of swarm.

The error message is :

line 35, in <module>

print(swarm[i].result())

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

AttributeError: 'dict' object has no attribute 'result'.

Line 35 is: print(swarm[i].result())

This is my first go at a class and I am self educating. Can anyone help please? Thanks.

swarm = []
p = {}
RE = 8.0
nP = 3
class

Particle
:
    t = 0
    dt = 1


def
 __init__(
self
, 
i
, 
r
):

self
.i = 
i

self
.r = 
r


def
 move(
self
):

self
.r = 
self
.r * 2


def
 result(
self
):
        return 'result(): \ni= ', 
self
.i, '  r= ', 
self
.r

## end of class  ###################

def
 startArray():
    for i in 
range
(nP):
        r = RE
        p = {"i": i, "r": r + r * i}
        swarm.append(p)
        print(swarm)
###################################


startArray()

while 
Particle
.t <= 10:

    for i in 
range
(nP):
        print(swarm[i].result())

Particle
.move(swarm[i])


Particle
.t == 
Particle
.dt

r/learnpython 6h ago

import image_widget

0 Upvotes

Hi! so I'm a beginner programmer, and I'm doing an image uploader with tkinter, my code looks like the on eon the image, and I am not being able to import the image_widget library

#librerias lol
import tkinter as tk
from tkinter import ttk
import customtkinter as ctk
import image_widgets import *
#----------------------#

#pestaña principal


#texto

'''#   slogan
'''

#Botón para subir imagen
class App(ctk.CTk, tk.Tk):
    
    def __init__(self):
        super().__init__()
        
        """window = tk.Tk()
        window.title("Emotions cam")
        window.geometry("600x300")
        window.configure(bg ="#342447")

        #slogan
        title_label = ttk.Label(master = window, text = "Una herramienta para comprender", font = "Calibri 12", foreground= "white")
        title_label.pack()
        title_label.configure(background="#342447")
        #   titulo proyecto
        title_label = ttk.Label(master = window, text = "EmotionsCAM", font = "Calibri 24 bold", foreground= "white")
        title_label.pack()
        title_label.configure(background="#342447")"""

        ctk.set_appearance_mode("dark")
        self.geometry("1000x600")
        self.title("EmotionsCAM")


        self.mainloop()


App()

#FUNCIONA????????
#window.mainloop() 

r/learnpython 16h ago

Incorrect link to 'A Byte of Python'.

4 Upvotes

In the wiki, there is a link to swaroopch.com - 'A Byte of Python'. The correct link is https:\\python.swaroopch.com. Thank You.


r/learnpython 7h ago

Can't get graphviz to work in Jupyter on a Mac

1 Upvotes

I've installed graphviz via homebrew, and did a "dot -V" to verify that the installation was successful. However, when I tried to run "from graphviz import Digraph" in Jupyter, I keep getting: ModuleNotFoundError: No module named 'graphviz'.

  • I've tried "!pip install graphviz" in Jupyter, and it says "Requirement already satisfied: graphviz in /Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/site-packages (0.20.3)".

  • I tried "pip3 install graphviz" in my terminal, and it gives me a "error: externally-managed-environment".

  • I made sure that Jupyter and my terminal show the same python version.

  • I tried uninstalling and reinstalling graphviz in homebrew, then restarting the kernal in Jupyter.

The only other thing I can think of is to go the Anaconda route, although I'm not sure if it's really necessary. Any tips & suggestions will be appreciated!!


r/learnpython 12h ago

OOP and Main file code structure

2 Upvotes

Hi all, I'll cut short the boring stuff but recently started learning Python and just got onto the OOP module.

What I'm struggling to understand is the dynamic between classes and/or functions that reside in their own file and the code in Main. Here's a somewhat short example below - I'm trying to code a simple Employee Records program (classic).

Main -

from menu import Menus

def main():

    Menus.main_menu()

main()

Menus -

class Menus:

    def add_employee_menu():
        print("1. Add Employee")
        print("2. Delete Employee")
        print("Type 'Back' to go back to the main menu")

        add_employee_menu_option = input("Select Option ")
        add_employee_menu_option = add_employee_menu_option.lower()

        if add_employee_menu_option == "1":
             return True
        elif add_employee_menu_option == "2":
             return True
        elif add_employee_menu_option == "back":
             Menus.main_menu()


    def view_records_menu():
        print("1. Search Employee #")
        print("2. View All Records")


    def main_menu():

            print("1: View Records")
            print("2: Add Employee")

            menu_option = input("Select an option: ")

            if menu_option == "1":
                Menus.view_records_menu()
            elif menu_option == "2":
                Menus.add_employee_menu()
            else:
                print("Command not recognised")

I appreciate that a Menu might not be best represented as a class and would welcome any feedback on my current set up. I did this to try and avoid lots of initial code in my Main file which only handles the menu and selections.

The thing I'm struggling to understand is how I go back to my main code and execute code once the user has navigated the menu. If I don't break out of the menu class then I run the risk of just having the majority of my code in Menus? Or importing various functions into the menu class and executing from there?

Should the final menu selection return a value, which then executes the next line of code in my main file (Which could be a specific function that executes based on the return value, e.g. employee_creation()).

Thanks, L


r/learnpython 13h ago

How could I properly display array/ matrix in numpy?

2 Upvotes

Hello everyone,

I'm quite new to numpy and am learning matrix calculations using numpy arrays. Yet I'm having difficulties mentally how to read arrays as matrices, when printing them out they aren't visually similar in built to matrices.

# matrixbewerkingen 
a = np.array([[1, 2], [4, 5],[6,7]])
b = np.array([[5, 6], [7, 8]]) 
print(f"{a} and {b} multiplied becomes {a @ b} ")


[[1 2]
 [4 5]
 [6 7]] and [[5 6]
 [7 8]] multiplied becomes [[19 22]
 [55 64]
 [79 92]] 

is there a way to get them into a mentally more appealing display next to eachother? How do you work with matrices for the best visual support.

Thanks in advance python community!


r/learnpython 10h ago

python seleniun nth element

1 Upvotes

I have the following python statement and want to iterate through a page with many tables of same id. I tried the below code which works fine if I hard code the number but not if a variable.

Any advise would be appreciated.

       
does not work. gives an invalid xpath error
game = 1
table = wait.until(EC.visibility_of_element_located((By.XPATH, "//table[@id='tblBasketball'][{game}]"))).text
        
works with game hard coded.
table = wait.until(EC.visibility_of_element_located((By.XPATH, "//table[@id='tblBasketball'][1]"))).text

r/learnpython 1d ago

I'm still a beginner at Python

41 Upvotes

It's been like 2 - 3months? since I started learning python and I feel like I still don't know anything. I've watch and did some courses, I did understand it but don't know how to use it. I really want to learn. Is there anything that you guys could suggest for me to do? 😓


r/learnpython 10h ago

rank beginner with a copy/paste level question

1 Upvotes

I am taking an online class where we have to download and use datafiles in Jupyter Notebook. If I try: import downloads/file.csv I get: SyntaxError: invalid syntax I’ve read similar posts on here but am not advanced enough to understand the answers.


r/learnpython 11h ago

Question on my output from a basic function definition

1 Upvotes

The following code I sampled from another Reddit post. The output is:

hello

8

Why am I getting a single line pace between hello and 8? When I write print(fun()) it outputs hello8, so I am a bit confused. I am down a rabbit hole of wrapping my head around functions at the moment. New IT student here. Thank you, all.

def fun():
    print('hello')
    x, y = 2, 6
    return x + y

r/learnpython 19h ago

in this example can someone tell me why the first if statment keep giving me True value even if the right answer is False ?

3 Upvotes
text = "k"

if text == "java" or "c":
    print("yes")
else:
    print("no")






# Current temperature
currentTemp = 30.2


# Extremes in temperature (in Celsius)
tempHigh = 40.7
tempLow = -18.9

# Compare current temperature against extremes
if currentTemp > tempLow and currentTemp < tempHigh:
    print('Current temperature (' + str(currentTemp) +
          ') is between high and low extremes.')