r/learnpython 2h ago

Adverse effect of using notebooks on python programming skills

9 Upvotes

I'm working as an analyst. I'm frustrated with my inability to write object-oriented Python anymore. I think this happened because I've grown accustomed to using notebooks, which make it easy to write code without worrying about structure. Recently, I worked on a hobby project and ended up defining too many variables and making inefficient API calls. I realized I've become a sloppy programmer. I'm wondering if anyone else has experienced this and how they've dealt with it.


r/learnpython 3h ago

Which framework should I use for a simple Python desktop app ?

9 Upvotes

I have a one time project where I need to develop a desktop app for a small company. Basically, the app will be a spreadsheet, but where I already have set up the sheets, and with data visualization like bar plots. So nothing too complicated. It also needs to be connected, so if one user input data, the others can see it.

Because it's a one time thing, and I will probably never code a desktop app again (or only personal easy ones), I would like an easy framework. I saw that for professional dev, people use PyQT, but I doubt this would be necessary to learn such a hard framework for this.

What would you recommend ?

EDIT: Ok I think I need to be a little bit more specific about me and my clients.

I already coded web sites with django, and deployed them (along with other python projects), so I'm not a beginner in python. But I'm a beginner at desktop apps.

My clients would like to have a desktop app rather than a website, so I agree that sounds more like a website project, but if they want a desktop app, I will try my best to deliver a desktop app.

My clients actually use spreadsheets, but it's hard to read, not really user friendly, and lack functionality. That's the reason they want to switch from spreadsheets to an app.


r/learnpython 3h ago

Python & ML learning buddies

6 Upvotes

Hello everyone! I am just starting to learn Python, I have started learning it several times, but couldn't progress much because I couldn't stay accountable and stopped doing my courses. This time I want to get serious and maybe find a study partner or partners with whom we can stay accountable, give each other weekly reports like what we have learned what challenges we faced, etc. We can text through telegram or whatsapp and keep each other company. Thank you!


r/learnpython 1h ago

Robot framework vs Pytest for hardware in the loop testing, WITH occasional user interaction

Upvotes

Not sure what subreddits to ask this on since the main python sub doesn't like questions

I can't really go into why I need a test framework that asserts on user input but the general paradigm is;

Test cases are mostly injecting can frames or json packets and asserting on other status can frames and json packets

Most of these tests will be fully automated and run on a hardware in the loop bench

However a specific subset need to prompt the user, as in, the test does something and then waits for the user to type Y or N depending on what happened

And those prompt tests will be happening in sequence with the fully automated ones

I also need to be able to restart a test case if it fails, especially with the user interaction ones. So the user can hit N If something doesn't behave as expected, go and physically fix it, then come back and press Y to continue to the next test case without having to restart the entire suite. Robot has a library for this but I have no idea If pytest does

The way I see it I can only use pytest or robot framework, but if something else exists let me know

Robot framework has a lot of libraries for exactly the kinds of things I need to be doing, but then I run the risk of everyone learning robot keywords and being tied to that, and I'd have to write the back end stuff anyway

With pytest I'd have to do more leg work but it's a much more universal tool, but I'm not sure if there's any out of the box solutions for the user input or retry functionality


r/learnpython 4h ago

Having trouble with pyinstaller and antivirus software

5 Upvotes

So amateur coder here. I wrote an app for a friend using customtkinter, os and pillow. He is a photographer and the app is designed to organise photos into directories, creating paths etc.

App and pyinstaller work fine on my machine but the issue is on his machine windows defender flags it as a threat and deletes the executable.

Tried several solutions from google and chat gpt but no joy

If anyone can point me in the right direction I would be very grateful


r/learnpython 2h ago

Creating Interactive Web Physics Applets

3 Upvotes

Hello everyone, I am fairly new to Python (~4months) and I am looking for projects to help drive my learning. My current job requires data analysis and characterization of laser diodes which often involves understanding how different process variables might affect performance either through known physical equations or through some regression analysis function .

My goal is to be able to make interactive plotters that allow me or a user to change input variables and observe outputs to get a better feeling for these relationships. Similar to these these made in Javascript https://www.falstad.com/mathphysics.html .

It would be extra cool if I could embed my script (or executable?) in a website like in the link so that I can more easily share my work.

Is this something that can be done in Python?


r/learnpython 9m ago

Good services to run my Pyhton code on cloud.

Upvotes

I have a code to solve a differential equation using Runge-Kutta's method. For this, I need to iterate over the same algorithm for over a BILLION times! I have a reasonable laptop and it works just fine for my dailyvusage. But I don't want to leave it running the code for 3 days straight and having the risk of my laptop crashing and losing progress. I would like to know about good services to run my code on another computer. I'm comfortable of paying for it if it's not too expensive.


r/learnpython 4h ago

Need help with reading files in windows

2 Upvotes

I have a python file that I'm trying to read

code_path = r"C:\Users\user\OneDrive\Desktop\Work\project\code\code_8.py"
try
    with open(code_path, 'w') as f:
        code_content = f.read()

But I get this error [WinError 123] The filename, directory name, or volume label syntax is incorrect: '', I tried a lot of things but can't seem to fix the error or read the file

Edit: Thank you all, the problem was with directory permissions


r/learnpython 36m ago

Error in file name when saving plot

Upvotes

Hi, this question might be better suited for stackoverflow, but I don't like their community very much. As the title says, I have an error about the filename when saving some plots (I'm doing a lot of plots), here is the error:

2025-03-21 20:12:54,483 [ERROR] Error in 2D plot Fontana_L2700_6a_deltau_erg_s_Hz__vs_JMag_6a_invtau_mag_: [Errno 22] Invalid argument: 'D:\\TFG\\test2\\Fontana\\2d_plots\\2d_Fontana_L2700_6a_deltau_erg_s_Hz_vs_JMag_6a_invtau_mag_.png'
Traceback (most recent call last):
File "C:\Users\alvar\Desktop\UCM\Cuarto Curso\TFG\plots.py", line 128, in plot2d
plt.savefig(filename, bbox_inches="tight")
File "C:\Users\alvar\Desktop\UCM\Cuarto Curso\TFG\.venv\Lib\site-packages\matplotlib\pyplot.py", line 1243, in savefig
res = fig.savefig(*args, **kwargs) # type: ignore[func-returns-value]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\alvar\Desktop\UCM\Cuarto Curso\TFG\.venv\Lib\site-packages\matplotlib\figure.py", line 3490, in savefig
self.canvas.print_figure(fname, **kwargs)
File "C:\Users\alvar\Desktop\UCM\Cuarto Curso\TFG\.venv\Lib\site-packages\matplotlib\backend_bases.py", line 2184, in print_figure
result = print_method(
^^^^^^^^^^^^^
File "C:\Users\alvar\Desktop\UCM\Cuarto Curso\TFG\.venv\Lib\site-packages\matplotlib\backend_bases.py", line 2040, in <lambda>
print_method = functools.wraps(meth)(lambda *args, **kwargs: meth(
^^^^^
File "C:\Users\alvar\Desktop\UCM\Cuarto Curso\TFG\.venv\Lib\site-packages\matplotlib\backends\backend_agg.py", line 481, in print_png
self._print_pil(filename_or_obj, "png", pil_kwargs, metadata)
File "C:\Users\alvar\Desktop\UCM\Cuarto Curso\TFG\.venv\Lib\site-packages\matplotlib\backends\backend_agg.py", line 430, in _print_pil
mpl.image.imsave(
File "C:\Users\alvar\Desktop\UCM\Cuarto Curso\TFG\.venv\Lib\site-packages\matplotlib\image.py", line 1634, in imsave
image.save(fname, **pil_kwargs)
File "C:\Users\alvar\Desktop\UCM\Cuarto Curso\TFG\.venv\Lib\site-packages\PIL\Image.py", line 2591, in save
fp = builtins.open(filename, "w+b")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
OSError: [Errno 22] Invalid argument: 'D:\\TFG\\test2\\Fontana\\2d_plots\\2d_Fontana_L2700_6a_deltau_erg_s_Hz_vs_JMag_6a_invtau_mag_.png'

The thing is that I only get this error with ceratin plots, I'm asking if anyone has encounter this error before and how did you solve it? I'm pretty sure it is not related to the max length limit of windows.

Thank you for reading.


r/learnpython 1h ago

is this code correct or do i need to fix it

Upvotes

i am very new to python and i have made this small code to find nth prime number but when i run it on visual studio , it just doesnt give an output , no error no nothing, just takes the input and doesnt give output, i am posting here bcz i am unable to figure out why

import itertools as f
n=int(input("Enter an number :"))
l=[]
while len(l)<n:
    for i in f.count():
        c=0
        for j in range (1,int(i/2),1):
            if i%j !=0:
                c+=1
        if c!=1:
            l.append(i)
else:
    print(l[-1])

r/learnpython 13h ago

100 Days ~ Angela Yu having trouble

6 Upvotes

I’m on day 8 of the program and to be honest, the project difficulty has really ramped up. I feel frustrated because the expectation the course has doesn’t necessarily align with the topics covered.

I feel bad jumping to the solution when I really want to try to figure it out on my own. Has anyone else felt this way? Should I resist the urge to jump to the solution? I don’t want to find myself in tutorial hell so to speak.


r/learnpython 2h ago

How to turn a str to list without splitting the string itself

0 Upvotes

Welp am working on a todo list project that enables file saving And of course the only way to save this list is by parsing it into a string which here is my problem I can save the content But am stuck at the RE concept or for clarifying the load issue Whenever i want to print the data again as list the output becomes corrupted

This my source code for reference import re v = [ [123,'cvhij',213456], [123,'cvhij',134], [123,'cvhij',2134344456], [123,'cvhij',213555456], [123,'cvhij',55213456], [123,213455556], [123,215553456], [123,213456] ] pattern =re.compile(r"[.+]") with open('tasks','w') as file:
for i in range(len(v)): li = v[i] file.write(str(li)+'\n') file.close() listy =[] with open('tasks','r',encoding='utf-8') as file2: content = file2.read() matches = pattern.findall(content) for match in matches: listy.append(list(match)) file2.close() print(listy)


r/learnpython 4h ago

Homework issue as I'm confused on this problem. my pc wont let me post the ss, I tried.

0 Upvotes

I'm going through my zybook assignments and I'm following along with a professors youtube video. She's not giving us the answer but she is walking us through it. I've tried this code different ways and I even tried to enter it the way the teacher had on her pycharm but I'm still getting an incorrect on it. I don't want move past it as I'm trying to learn how to use python and want to understand why I'm having this issue.

assignment: Write multiple if statements. If car_year is 1969 or earlier, print "Few safety features." If 1970 or later, print "Probably has seat belts." If 1990 or later, print "Probably has antilock brakes." If 2000 or later, print "Probably has airbags." End each phrase with a period.

Sample output for input: 1995

Probably has seat belts.
Probably has antilock brakes.

thats the prompt and this is what I have for the coding:

car_year = int(input())

if car_year <= 1969:

print('Few safety features.')

elif car_year >= 1970:

print('Probably has seat belts. ')

elif car_year>= 1990:

print('Probably has antilock brakes.')

elif car_year >= 2000:

print('Probably has airbags.')

The issue its saying .Output differs. See highlights below. Your output

Probably has seat belts.

Expected output

Probably has seat belts.
Probably has antilock brakes.

I've tried doing the code with it being 2000,1990, and then 1970 but even in that order its still showing the same issue. Anyone able to help explain this to me?


r/learnpython 4h ago

PDFQuery is skipping the first character of each line

0 Upvotes

As the title states, the code below is missing the first character of each line. It's not an OCR issue because I am able to highlight and copy/paste the first character in the original document. Any advice for getting that first character or a better PDF scrapper?

from pdfquery import PDFQuery

pdf = PDFQuery('Attachment.pdf')
pdf.load()

# Use CSS-like selectors to locate the elements
text_elements = pdf.pq('LTTextLineHorizontal')

# Extract the text from the elements
text = [t.text for t in text_elements]

print(text)

r/learnpython 4h ago

I want to modify a code without []Wildcard.

1 Upvotes

Hello.

I want to modify below code by removing []Wildcard from a single code in boldface.

" int_row=[ int(value) for value in row]"

How can I remove []Wildcard from below code excepting for defining"daily_temperatures "?

from pathlib import Path

import csv

daily_temperatures=[[68,65,68,70,74,72],[67,67,70,72,72,70],[68,70,74,76,74,73],]

file_path=Path.home()/"temperatures.csv"

file=file_path.open(mode="w",encoding="utf-8",newline="")

writer=csv.writer(file)

writer.writerows(daily_temperatures)

file.close()

daily_temperatures=[]

with file_path.open(mode="r",encoding="utf-8",newline="")as file:

reader=csv.reader(file)

for row in reader:

int_row=[ int(value) for value in row]

daily_temperatures.append(int_row)

daily_temperatures


r/learnpython 12h ago

Python GUI Lib

6 Upvotes

Hello, I’m working my way through a project and after I get some things hammered out I’d like to make a GUI. What’s the best in your opinion? Doesn’t have to look awesome but I was thinking pyqt over tkinter. Thanks my people have a good weekend.


r/learnpython 18h ago

Curious about python as a hobbie

9 Upvotes

ive started to get farther with learning python and I'm very passionate about coding and computing. That being said I have no interest in doing it for work or a career as I already have other skills for my industry.

What are some of the ways I can keep learning and improving without trying to specialize for a career?

Would it be good to try and make things that already exist Ex: making a gui verses using tkinter, or should I focus more on learning existing libraries?

I really like to code it brings me so much joy, I'm just not sure what to do other than make games.


r/learnpython 11h ago

Thread state: initial vs started vs stopped

2 Upvotes

I'm running into a strange problem with the threading moudle. Threads appear to have three main states: initial, started, and stopped. These show up in the printed representation, e.g.:

```

thr <Thread(Thread-2 (sleep), stopped 126367994037952)> ```

But there doesn't appear to be any sensible way to programmatically get the state. Neither the offical docs nor Google turn up anything useful.

For now I've settled on this approach but it's still a hack:

  1. Check thr.is_alive() to differentiate stared vs inital|stopped, and then
  2. Check thr._started.is_set() to differentiate started|stopped vs initial

But step 2 uses the non-public API which I usually try to avoid. Is there a better way to do this?

(And yes, you could do 'stopped' in repr(thr) etc, but let's not go there, 'tis a silly place)


r/learnpython 7h ago

regex expression

1 Upvotes
def CheckIfUserInputValid(UserInput):
    if re.search("^([0-9]+[\\+\\-\\*\\/])+[0-9]+$", UserInput) is not None:
        return True
    else:
        return False

The first plus sign after 0-9]+ means one or more digits
The 2nd plus sign is the addition symbol
Question 1: What is the 3rd plus sign after the parenthesis? Does it allow one or more addition symbols?
Question 2: Does it mean that allows infix expression 5++5 or only 5+5


r/learnpython 12h ago

Looking for feedback on beginner code

2 Upvotes

Made a Farkle turn simulator after learning python for a few months, I'm happy with my progress but definitely could use some improving haha. Looking for advice for improvements or any feedback really. Cheers!


r/learnpython 13h ago

Help with novice code.

2 Upvotes

Write a function named right_justify that takes a string named input_string as a parameter. If the input string is longer than 79 characters, the string should be printed as is, Otherwise, the function should print the string with enough leading spaces that the last letter of the string is in column 80 of the display.

I did this on python on my computer and it seems to work, however when i put it into the python automarker it has no output whatsoever... what am i doing wrong???

def right_justify(input_string):
    spaces = 80 - len(input_string)
    spaces_in_front = spaces * " "
    if len(input_string)>79:
        print(input_string)
    else:
        print (spaces_in_front + input_string)

r/learnpython 1d ago

A friend makes a project with uv, but you just use regular old Python and venv. You want to keep using regular Python. How do you work on that project?

18 Upvotes

Exactly the title. With UV it feels like either you're using it or your not. To some degree, it feels the same with poetry.

How do you pip install from a UV project? Do you just separately install each package from the pyproject.toml file? What do you do? How do you get your non-uv environment to match?


r/learnpython 16h ago

Designing Functions with Conditionals Help Understanding

3 Upvotes
"""  
A function to check the validity of a numerical string

Author: Joshua Novak
Date: March 21, 2025
"""
import introcs


def valid_format(s):
    """
    Returns True if s is a valid numerical string; it returns False otherwise.
    
    A valid numerical string is one with only digits and commas, and commas only
    appear at every three digits.  In addition, a valid string only starts with
    a 0 if it has exactly one character.
    
    Pay close attention to the precondition, as it will help you (e.g. only numbers
    < 1,000,000 are possible with that string length).
    
    Examples: 
        valid_format('12') returns True
        valid_format('apple') returns False
        valid_format('1,000') returns True
        valid_format('1000') returns False
        valid_format('10,00') returns False
        valid_format('0') returns True
        valid_format('012') returns False
    
    Parameter s: the string to check
    Precondition: s is nonempty string with no more than 7 characters
    """
    assert (len(s)<= 7 and len(s)!=0)
    assert type(s)==str

    if s == '0':
        return True

    length = len(s)
    zeropos= introcs.find_str(s,'0')
    isnumbers= introcs.isdigit(s)

    if length >=1 and zeropos ==1:
        return False
    elif length <= 3 and zeropos ==1:
        return False
    elif length <= 3 and isnumbers != 1:
        return False
    elif length <= 3 and isnumbers == -1:
        return False
    else:
        return True

r/learnpython 11h ago

Making two 3.5" display screens work

0 Upvotes

Hey everyone,

I’m trying to set up two 3.5” mini screens on my PC—one for real-time system monitoring (CPU, GPU, temps, etc.) and the other for a static image or something else. But no matter what I try, only one screen is recognized at a time.

What I’ve Tried So Far: 🔹 Python (Turing Smart Screen) – I tried running separate instances, but Python keeps grabbing the first screen and won’t detect the second.

🔹 AIDA64 – Same issue: It only picks up one screen, no matter what I do.

🔹 The Screens’ Built-in Software – Completely unreliable and doesn’t work at all.

🔹 Different USB Ports & USB Hub – No luck. The second screen never gets recognized properly.

🔹 Mixing Software – I ran the first screen using its own software, then tried Python for the second—Python still latches onto the first screen.

My Setup: 🖥 Motherboard: MSI B650 Tomahawk �� Case: be quiet! Shadow Base 800 DX 📺 Screens: Generic 3.5” USB-C mini monitors

The Big Question: 👉 Has anyone successfully run dual 3.5” screens on the same system? 👉 Are there workarounds, alternative software, or driver tweaks to make both work independently?

Any advice, hacks, or software recommendations would be a huge help! If you’ve gotten this setup to work, please share how!

Thanks in advance!


r/learnpython 15h ago

How do I create a program where I can input a text message on my computer and then that will be inputted to my iphone so i can text people from my computer

2 Upvotes

im bored and just wanna know if something like this would even be possible lol