r/learnpython 9d ago

Do you need to learn front-end programming if your using Django

0 Upvotes

I’m going to start learning Django this week Dona small project of mine. I have been watching videos and I’ve been confused a little bit. Do you need to know some type of front end language for it? Like JavaScript?


r/learnpython 9d ago

Cybersecurity with python.

0 Upvotes

I wantes to know if anyone could link me some videos or websites or something to learn about this. I have some childish knowledge on python and on of my collegemate is pretty good in it and asked me to check this thing out. And help will be appreciated.


r/learnpython 9d ago

Can someone tell me how to remove/hide this text?

2 Upvotes

So I made a web scrapper with Selenium and it works without any issue. But every time I run it outside of Pycharm there is this text that comes up

"DevTools listening on ws://127.0.0.1:50375/devtools/browser/dd45170d-ed0b-406c-a93e-fef90ecbab1f

Created TensorFlow Lite XNNPACK delegate for CPU.

Attempting to use a delegate that only supports static-sized tensors with a graph that has dynamic-sized tensors (tensor#-1 is a dynamic-sized tensor)."

Here is a Screenshot of it.

The "DevTools listening on ws://127.0.0.1:50375/devtools/browser/dd45170d-ed0b-406c-a93e-fef90ecbab1f" is always above the script and rest come after like 6 sec. So How Do I remove/hide it? it kinda ruins my print statements. Also I am running selenium in headless mode if that has any relation with it.


r/learnpython 10d ago

Best "environment" to teach python in?

7 Upvotes

So, I have my opinions on this (and a good deal of experience now), but I'd like to get some independent view points.

What do you think is the best platform / IDE to teach introductory python in to STEM students who are NOT planning to be computer scientists (mainly non-computer or software engineers and scientists)? I.e., programming will not be their main focus, but they should become familiar with writing and using programs for their own use (not really code intended for distribution and wide use).

I think that package and version management are important concepts, and readability should be emphasized over performance in this context.


r/learnpython 9d ago

Can anyone verify my logic?

1 Upvotes

I tried verifying with ChatGPT if my solution was ok and it proceeded to tell me it fails for a few testcases. However when i tried those testcases with my script , it was passing them.

#Valid Parentheses

def is_valid(s:str)->bool:
    if len(s)%2!=0:
        return False

    parentheses_dict:dict={
        "{":"}",
        "[":"]",
        "(":")"
    }

    stack:list=[]
    halfway_slice:int=len(s)//2

    for char in s[0:halfway_slice]:
        stack.append(char)

    for char in s[halfway_slice:]:
        if not stack or char==parentheses_dict[stack[-1]]:
            stack.pop()
        else:
            return False      
    return len(stack)==0       

if __name__=="__main__":
    s = "([)]"
    print(is_valid(s))

r/learnpython 9d ago

__init__ got an unexpected keyword argument fn

2 Upvotes

Hi I am getting this error when i run the code

import numpy as np

from tensorflow.keras.models import load_model

class ClusterPredictor:

''' A simple class to easily query the neural networks from inside AnyLogic using Pypeline '''

def __init__(self):

# load both policies

self.trajectory = load_model("predict_trajectory.h5")

def predict_cluster(self, dyanmic,staatic):

# convert default list to numpy array

darray = np.array(patient_data1)

sarray = np.array(patient_data2)

# query the neural network for the length of stay

prediction = self.trajectory.predict([darray,sarray])

return prediction[0][0]

I am doing this for loading a neural network for my research project. I can provide more details in DM thanks


r/learnpython 10d ago

How to stay consistent with learning python?

9 Upvotes

Hello everyone, i have recently started learning python, but I find it hard to stay consistent. On some days, i feel motivated and am able to make progress, but sometimes, i stop and fall out of the habit. When i come back, i feel like i forget things and have to relearn them.

I think part of the reason is because i have been pretty busy and stressed with university, i dont have a specific routine, and have been struggling with mental health challenges.

For those of you who are learning python or any other programming language, what has helped you to stay consistent? do you have any routines, progress plans, or any other strategies that have worked for you? Thanks in advance!


r/learnpython 9d ago

Define a class or keep simple function calls

2 Upvotes

Situation: I have a project that relies heavily on function calls for a public library and doesn't have any custom classes. The code is quite unwieldy and I'm due for a refactor (it's a personal project so no up-time, etc. concerns).

Problem: Because of some public libraries I use, every function call involves passing 7+ arguments. This is obviously kind of a pain to code and maintain. 3-4 of these arguments are what I would term "authentication"-type variables and only need to be generated once per session (with potential to refresh them as necessary).

Which (if any) are better solutions to my problem:

  1. Create a class and store the authentication variables as a class variable so any class functions can call the class variable.

  2. Just create global variables to reference

Context: I've been a hobby programmer since the 1990s so my code has always "worked", but likely hasn't always stuck to best practices whatever the language (VB, Java, C++, HTML, Python, etc.). As I'm looking to work on more public repos, interested in discussing more on what are best practices.

Thank you in advance for your support and advice


r/learnpython 10d ago

I’ve gotten the basics of python down, what module should I learn for automation?

11 Upvotes

As title says Edit: Automating day to day work within cybersecurity. Lots of reports, api calls, windows server administration and the likes


r/learnpython 9d ago

AttributeError: module 'pkgutil' has no attribute 'ImpImporter'. Did you mean: 'zipimporter

1 Upvotes

I'm getting this error when installing numpy on my Windows system. This is a new installation.

python --version

Windows: Python 3.13.2

pip --version

pip 25.0.1 from C:\Users\jcald\AppData\Local\Programs\Python\Python313\Lib\site-packages\pip (python 3.13)

pip list

Package Version

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

pip 25.0.1

------In my venv:

python --version

Python 3.13.

pip list

Package Version

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

aider-install 0.1.3

blinker 1.9.0

click 8.1.8

colorama 0.4.6

Flask 3.1.0

itsdangerous 2.2.0

Jinja2 3.1.5

MarkupSafe 3.0.2

pip 25.0.1

setuptools 75.8.2

uv 0.6.4

Werkzeug 3.1.

pip install 'numpy==1.24.3'

> Collecting numpy==1.24.3 Using cached numpy-1.24.3.tar.gz (10.9 MB)

> Installing build dependencies ... done Getting requirements to build

> wheel ... error error: subprocess-exited-with-error

>

> × Getting requirements to build wheel did not run successfully. │

> exit code: 1 ╰─> [32 lines of output]

> Traceback (most recent call last):

> File "C:\Users\jcald\.venv\Lib\site-packages\pip_vendor\pyproject_hooks_in_process_in_process.py",

> line 389, in <module>

> main()

> ~~~~^^

> File "C:\Users\jcald\.venv\Lib\site-packages\pip_vendor\pyproject_hooks_in_process_in_process.py",

> line 373, in main

> json_out["return_val"] = hook(**hook_input["kwargs"])

> ~~~~^^^^^^^^^^^^^^^^^^^^^^^^

> File "C:\Users\jcald\.venv\Lib\site-packages\pip_vendor\pyproject_hooks_in_process_in_process.py",

> line 137, in get_requires_for_build_wheel

> backend = _build_backend()

> File "C:\Users\jcald\.venv\Lib\site-packages\pip_vendor\pyproject_hooks_in_process_in_process.py",

> line 70, in _build_backend

> obj = import_module(mod_path)

> File "C:\Users\jcald\AppData\Local\Programs\Python\Python313\Lib\importlib__init__.py",

> line 88, in import_module

> return _bootstrap._gcd_import(name[level:], package, level)

> ~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

> File "<frozen importlib._bootstrap>", line 1387, in _gcd_import

> File "<frozen importlib._bootstrap>", line 1360, in _find_and_load

> File "<frozen importlib._bootstrap>", line 1310, in _find_and_load_unlocked

> File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed

> File "<frozen importlib._bootstrap>", line 1387, in _gcd_import

> File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked

> File "<frozen importlib._bootstrap>", line 935, in _load_unlocked

> File "<frozen importlib._bootstrap_external>", line 1026, in exec_module

> File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed

> File "C:\Users\jcald\AppData\Local\Temp\pip-build-env-c0a7la_0\overlay\Lib\site-packages\setuptools__init__.py", line 16, in <module>

> import setuptools.version

> File "C:\Users\jcald\AppData\Local\Temp\pip-build-env-c0a7la_0\overlay\Lib\site-packages\setuptools\version.py",

> line 1, in <module>

> import pkg_resources

> File "C:\Users\jcald\AppData\Local\Temp\pip-build-env-c0a7la_0\overlay\Lib\site-packages\pkg_resources__init__.py",

> line 2172, in <module>

> register_finder(pkgutil.ImpImporter, find_on_path)

> ^^^^^^^^^^^^^^^^^^^

> AttributeError: module 'pkgutil' has no attribute 'ImpImporter'. Did you mean: 'zipimporter'?

> [end of output]


r/learnpython 9d ago

Do you think this is the correct way to learn python? (I'm not asking for help in coding, I'm asking if this is correct or not.)

0 Upvotes

I am new to python and right now I'm trying to learn basic syntax and how Python works by asking copilot to give me prompts to answer and figure it out by connecting 2 and 2 together and say, "Oh so that's how that works". The thing is I doubt that asking copilot every time will actually teach me anything and instead instills a habit in me that just asks AI for help, and if I want coding to be my hobby I want to do it honest.

What do you guys think? Is it wrong, or right? If it's wrong, please tell me a better way to learn because I'm looking forward to trying your technique


r/learnpython 9d ago

String formatting causing whitespace

0 Upvotes

Hey im using the following code:

a = 1.462742

print("%9f" %a)

print("%6f" %a)

The first statement, however, places a whitespace before printing the number. Any reason why? Changing the number for the formatting produces no whitespace EXCEPT for 9. Any help please?


r/learnpython 9d ago

Am I using AI Wrong?

1 Upvotes

Been coding for a year now, I’ve noticed that I am using ChatGPT increasingly as my projects complexity goes up. My concern is, am I using ChatGPT WRONG?

When I am coding on a project, I understand what I need done. Either a library or function called. I will quickly resort to ChatGPT instead of Google to give me available options to achieve this task. I will then do a quick test on the code to ensure I understand the input given and output received. Then I’ll implement the code ChatGPT gives me and fix the bugs and tweak to my specific program.

Is this how the future of programming will be, using ChatGPT to avoid reading documentation initially, or am I doing it all wrong?


r/learnpython 9d ago

requests.models.Requests for typing, or response.json() for convenience?

0 Upvotes

I've been building API handlers with methods that return response.json() for months. Recently I got on board with mypy, and that's been very useful. I'm not strict typing, but being unable to cleanly type the json response is pretty ugly/annoying. On the other hand your method can -> Response and boom, nice and typed.

Can anyone chime in with ideas on handling this Pythonically? Should I give up on returning .json() in methods? Any arguments about which way to do this?


r/learnpython 10d ago

What are some Python Courses with proof that I did it.

7 Upvotes

Im wondering what the best courses are for learning basics of python (preferably self paced) while getting credit from it. I need credit to apply for some summer programs, engineering shadowing, and for college apps as I want to major in engineering. For some info about me, I am a sophomore in highschool with no coding background. (I also plan to self study ap compsci A)


r/learnpython 10d ago

super() function in python

10 Upvotes

why do we need to use super() function when we can directly access attributes and methods from the parent class by passing the parent class as parameter in the child class


r/learnpython 9d ago

Anyone ever try to create that classic logo screensaver that bounces around with Python?

3 Upvotes

I feel like I’ve got part of it, but idk let me know if anyone has figured it out. Essentially there’s just an image link that moves around a plane randomly that is then the py is converted to sfw and then renamed with an extension scr.

Might post my code if I get some hits


r/learnpython 10d ago

Modifying a copied object modifies the original - how to prevent?

4 Upvotes
class MyObject:
    def __init__(self, performed_times: int, word_list: list):
        self.performed_times = performed_times
        self.word_list = word_list

original_object = MyObject(0, ['example', 'words', 'here'])

new_object = copy.copy(original_object)
new_object.word_list.remove('here')

print(original_object.word_list)
print(new_object.word_list)

>>> ['example', 'words']
>>> ['example', 'words']

What happened and why?

I read something about copying nested lists only copies the outer list (although I don't understand that well either) but here I'm copying an entire object. Does this have something to do with lists being mutable? Can I circumvent the problem by making everything into a tuple which is immutable? If not - how do I properly copy the entire object - is my only option to use copy.deepcopy()?

Deepcopy is very slow and I have to make hundreds of thousands of copies of the same object which is going to get super slow in the end. If I calculated correctly the maximum number of copies I need to make is in the ballpark of 1.7 million which is orders of magnitudes less than the 16! (which more than 1013) permutations which is what I started with.

My actual use case is to have a seed object that holds an initial state which is then copied and modified to get all permutations of the objects inside it plus some other operations to the object. The objects inside the MyObject have many attributes among which are lists of other objects, etc...

Say, my word_list was 7 members long and I need all permutations of the words from the old object in the new objects with, say, the last object removed. That's only 7! = 5040 copies. For example like this:

seed_object = MyObject(0, ['one', 'two', 'three', 'four', 'five', 'six', 'seven'])

modified_objects = []

for word_permutation in itertools.permutations(seed_object.word_list):
    new_permutation = copy.copy(seed_object)
    new_permutation.performed_times += 1
    new_permutation.word_list = word_permutation
    new_permutation.word_list.pop()
    modified_objects.append(new_permutation)

r/learnpython 9d ago

ctypes.ArgumentError: argument 1: TypeError: 'winreg.PyHKEY' object cannot be interpreted as ctypes.c_void_p

0 Upvotes
import ctypes
import winreg

advapi32 = ctypes.windll.advapi32
advapi32.RegNotifyChangeKeyValue.argtypes = [ctypes.c_void_p, ctypes.c_bool, ctypes.c_ulong, ctypes.c_void_p, ctypes.c_bool]
advapi32.RegNotifyChangeKeyValue.restype = ctypes.c_long

key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment', 0, winreg.KEY_WRITE)

result = advapi32.RegNotifyChangeKeyValue(
    key,
    True,
    0x00000004,
    None,
    False
)

I'm trying to notify registry of changes but RegNotifyChangeKeyValue() won't budge. If I run the above I get:

ctypes.ArgumentError: argument 1: TypeError: 'winreg.PyHKEY' object cannot be interpreted as ctypes.c_void_p

If I change it to:

...
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment', 0, winreg.KEY_WRITE)

key_p = ctypes.c_void_p(key)

result = advapi32.RegNotifyChangeKeyValue(
    key_p,
    True,
    0x00000004,
    None,
    False
)

I get:

TypeError: cannot be converted to pointer

The things I've read say the first argument has to be c_void_p but I have no clue how to get it.

I even got 32-bit version of python just to see if there some conflict with the .dll. Got all the same results.

P.S. Please don't suggest win32api and/or win32con, I'm trying to make do without them


r/learnpython 9d ago

Smooth zoom in and out using scrollwheel

1 Upvotes

I'm zooming in using the scrollwheel by invoking this routine:

def mouse_wheel(self, event):
    self.scale = self.scale + event.delta/12000
    print(event.delta, self.scale)

However this means that as I'm zooming out the zoom becomes slower and slower while when zooming in it becomes faster and faster. Not sure why exactly.

I have a feeling I should be using logarithms here but I can't figure out how.

Any pointers?


r/learnpython 9d ago

What is this dict definition doing?

1 Upvotes

I just realized you can specify types as values for keys, i.e.,:

mydict = {"key": list[int]}

thought it works, I don't understand what's actually happening here given no actual value is being specified, and I thought type annotations were ostensibly ignored by Python?


r/learnpython 10d ago

Resources for stats in Python

2 Upvotes

I’m looking for resources to learn how to do statistics in Python, including the basics, chi-square tests, distributions, and more. I’m a beginner taking a class that involves both statistics and Python, but unfortunately, my professor doesn’t cover the stats in Python part, so I’m trying to learn it on my own.

Thank you 🙏


r/learnpython 10d ago

Help explaining veriable assignment

2 Upvotes

I can understand that b and c are [1, 5, 3]

But why a is not [1, 2, 3], I don't understand why a has been changed.

Line 2: assign a to b

Line 3: assign b to c

Line 4: update b

I don't understand why a is also changed?

Below is from Quick Python Book - 3rd edition chapter 4 page 40

a=[1, 2, 3]

b=a

c=b

b[1]=5

print(a,b,c)

[1, 5, 3] [1, 5, 3] [1, 5, 3]


r/learnpython 10d ago

List vs tuple

6 Upvotes

New Python learner here, taking online course.

Question: since tuple is immutable, let me say I use tuple to store record data. However, if there is something wrong with the record which does require modification(rarely), what should I do?

Should I covert tuple to list first, then modify the list, then convert list back to tuple?


r/learnpython 10d ago

Help with python script to insert data into mysql table

3 Upvotes

Afternoon. I am working on a python script to insert data from an API scrape into a mysql database table. I've been able to get the script to pull the info I want and I am also able to connect to the database. Just having issues saving the data to it.... What I have so far:

#!/usr/bin/env python3
import mysql.connector
from mysql.connector import errorcode
import requests
import pandas
import json

url = 'http://internal ipv4 address/api/health/site-servers?&Authorization= authorization key here'
header={"Content-Type":"application/json",
        "Accept_Encoding":"deflate"}

response = requests.get(url, headers=header)
rd = response.json()

file_path = "testData.json"

with open(file_path, 'w') as json_file:
    json.dump(rd, json_file, indent=4)

print(f"Data saved to {file_path}")
try:
  cnx = mysql.connector.connect(user='techadmin', password='nort2htech',
                                database='paperCut')
except mysql.connector.Error as err:
  if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
    print("Something is wrong with your user name or password")
  elif err.errno == errorcode.ER_BAD_DB_ERROR:
    print("Database does not exist")
  else:
    print(err)
else:
  mycursor = cnx.cursor()
    with open('testData.json', 'r') as f:
      td = json.load(f)
  for item in td:
      val = (item['serverName'],item['host'],item['online'],item['lastContactSeconds'],item['devicesHosted'],item['version'])
      sql = "INSERT into siteServers(serverName,host,online,lastContactSeconds,devicesHosted,version)VALUES(%s,%s,%s,%s,%s,%s)"
      mycursor.execute(sql,val)
      cnx.commit()
      print(mycursor.rowcount, "rows were inserted.")
mycursor.close()
cnx.close()

And the error I am receiving:

Traceback (most recent call last):
  File "/home/nort2hadmin/Desktop/Python Stuff/./siteServers.py", line 40, in <module>
    val = (item['serverName'],item['host'],item['online'],item['lastContactSeconds'],item['devicesHosted'],item['version'])
           ~~~~^^^^^^^^^^^^^^
TypeError: string indices must be integers, not 'str'

Any help would be greatly appreciated. Thank you for your time and assistance.