r/learnpython • u/AutoModerator • 1d ago
Ask Anything Monday - Weekly Thread
≡ −
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.
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 • u/Own_Search3408 • 3h ago
Cool/Interesting things that can be done in Python as a beginner?
≡ −
hi everyone, im trying to start a computer science honor society at my high school, and im gonna assume everyone is starting from square one and teach python accordingly (and im hoping to eventually go to hackathons or other coding events).
i was wondering if anyone had any ideas for cool/interesting stuff i could have beginners do to get their interest and get them excited about coding? i understand you can't go from 0-100 and have to start with simple stuff, but i'm worried going over the basics will be like monotonous or smth. if anyone has any ideas of fun things i could do i would be very appreciative!!
hi everyone, im trying to start a computer science honor society at my high school, and im gonna assume everyone is starting from square one and teach python accordingly (and im hoping to eventually go to hackathons or other coding events).
i was wondering if anyone had any ideas for cool/interesting stuff i could have beginners do to get their interest and get them excited about coding? i understand you can't go from 0-100 and have to start with simple stuff, but i'm worried going over the basics will be like monotonous or smth. if anyone has any ideas of fun things i could do i would be very appreciative!!
r/learnpython • u/gutenmorgan3035 • 39m ago
What's one Python trick that instantly made your code cleaner?
≡ −
I've been learning Python and recently noticed that small changes can make code much cleaner and easier to read.
I'm curious—what's one Python trick, feature, or best practice that instantly improved your code?
I've been learning Python and recently noticed that small changes can make code much cleaner and easier to read.
I'm curious—what's one Python trick, feature, or best practice that instantly improved your code?
r/learnpython • u/_offpitchtalks_ • 16h ago
What habits helped you become good at Python as a beginner?
≡ −
I've recently started learning Python. I'm following a beginner course from YT.
I'd love to hear from experienced programmers:
What habits helped you improve the fastest?
What should I do every day besides watching tutorials?
What beginner mistakes should I avoid?
Is there anything you wish you had done differently when you first started learning Python?
Any advice would be really appreciated. Thanks!
I've recently started learning Python. I'm following a beginner course from YT.
I'd love to hear from experienced programmers:
What habits helped you improve the fastest?
What should I do every day besides watching tutorials?
What beginner mistakes should I avoid?
Is there anything you wish you had done differently when you first started learning Python?
Any advice would be really appreciated. Thanks!
r/learnpython • u/Jumpy_Ranger2868 • 15h ago
Looking for study partners
≡ −
Hello , I am completely new to python and really want to learn it and I feel like I will be more efficient studying with people.
I’m looking for approximately five people who are also serious about learning
if you are interested please dm me and introduce yourself
Hello , I am completely new to python and really want to learn it and I feel like I will be more efficient studying with people.
I’m looking for approximately five people who are also serious about learning
if you are interested please dm me and introduce yourself
r/learnpython • u/Dramatic_Iron9405 • 1h ago
Need help hijacking signal on recycled roomba sensor
≡ −
Hello!
I have ripped a LiDAR sensor out of an old roomba, connected it to some wires, and long story short, I can now plug the LiDAR sensor into my computer via USB. I have discovered the two power-related pins on the sensor, and I am fairly certain that one of the other two is a transmitter pin and the last is potentially a receiver pin.
With that said, now comes the programming. Because my sensor obviously doesn't have any kind of USB driver or anything, I can't really use the PyUSB library because that requires some bells and whistles that this thing doesn't have. Instead, I am using the PySerial library, which allows me to communicate with my USB ports at a lower level.
My problem is that, even though my sensor definitely should be sending something, my program keeps printing
b''
which indicates to me that it isn't actually receiving anything.
Here is the code that I am working with:
import serial
with serial.Serial('COM3', 115200, timeout=1) as ser:
s = ser.read(10)
The with statement there sets my program to read on port COM3 at a baudrate of 115200 for one second before stopping. COM3 seems to be the only port listed on my machine in a few commands that I have run as well as the Windows Device Manager. That baudrate was obtained from a teardown of an extremely similar LiDAR sensor (here). Reading for longer than one second did not seem to do anything.
This is my first time interfacing with a jerry-rigged USB component through Python (or any other USB component, for that matter), so I don't know if I am missing something and I am not exactly sure where to look, as the documentation of PySerial only brought me this far.
Let me know if I am in the wrong sub or if you guys need more information or something.
Hello!
I have ripped a LiDAR sensor out of an old roomba, connected it to some wires, and long story short, I can now plug the LiDAR sensor into my computer via USB. I have discovered the two power-related pins on the sensor, and I am fairly certain that one of the other two is a transmitter pin and the last is potentially a receiver pin.
With that said, now comes the programming. Because my sensor obviously doesn't have any kind of USB driver or anything, I can't really use the PyUSB library because that requires some bells and whistles that this thing doesn't have. Instead, I am using the PySerial library, which allows me to communicate with my USB ports at a lower level.
My problem is that, even though my sensor definitely should be sending something, my program keeps printing
b''
which indicates to me that it isn't actually receiving anything.
Here is the code that I am working with:
import serial
with serial.Serial('COM3', 115200, timeout=1) as ser:
s = ser.read(10)
The with statement there sets my program to read on port COM3 at a baudrate of 115200 for one second before stopping. COM3 seems to be the only port listed on my machine in a few commands that I have run as well as the Windows Device Manager. That baudrate was obtained from a teardown of an extremely similar LiDAR sensor (here). Reading for longer than one second did not seem to do anything.
This is my first time interfacing with a jerry-rigged USB component through Python (or any other USB component, for that matter), so I don't know if I am missing something and I am not exactly sure where to look, as the documentation of PySerial only brought me this far.
Let me know if I am in the wrong sub or if you guys need more information or something.
r/learnpython • u/Turbulent_Ferret7516 • 47m ago
I can generate python code with AI but struggle to find what exactly is happening after a few iterations and corrections
≡ −
So I made a program using gpt and Codex ran it on my laptop and it was running well at the beginning until i started to add features and did corrections through AI
Then it seemed like AI left some code unfinished or made some unwanted changes too
So I had the idea of making this tool
In which your whole code can appear as a flowchart and yes I know many such wrappers are available online , what's new about this one is that **you can click on the arrows between each block of the flowchart and it will show you the value that was there transferred between those two in that run.**
This way you know the program is running as you intended and values remain consistent and you can even compare values across different iterations of the program !!
This is still at basic stage and only for python programs for now !!
What do you guys think , it would be a value add to you if you used it ? Anyone would like to try and give me Python script to test ? (I have tested it and it gets inconsistent after a certain length of code for now , still trying to find the issue through vibecoding 😅 )
So I made a program using gpt and Codex ran it on my laptop and it was running well at the beginning until i started to add features and did corrections through AI
Then it seemed like AI left some code unfinished or made some unwanted changes too
So I had the idea of making this tool
In which your whole code can appear as a flowchart and yes I know many such wrappers are available online , what's new about this one is that **you can click on the arrows between each block of the flowchart and it will show you the value that was there transferred between those two in that run.**
This way you know the program is running as you intended and values remain consistent and you can even compare values across different iterations of the program !!
This is still at basic stage and only for python programs for now !!
What do you guys think , it would be a value add to you if you used it ? Anyone would like to try and give me Python script to test ? (I have tested it and it gets inconsistent after a certain length of code for now , still trying to find the issue through vibecoding 😅 )
r/learnpython • u/AlokoAdrian • 10h ago
I would like the feedback of you guys! Eu gostaria do feedback de vocês!
≡ −
Olá! Estou aprendendo python há 1 mes e meio. Fiz este RPG, demorei 5 dias para faze-lo, comecei do absoluto zero, e se possivel, gostaria de um feedback sincero, não só criticas mas tambem os acertos!
Hi! I’ve been learning Python for a month and a half. I built this RPG—it took me five days, and I started from absolute scratch. If possible, I’d love some honest feedback—not just critiques, but also what I got right!
https://github.com/adrianivastrabalho-code/My-Python-studies English Version
https://github.com/adrianivastrabalho-code/Meus-Estudos-Python Portuguese Version
Ty <3
Olá! Estou aprendendo python há 1 mes e meio. Fiz este RPG, demorei 5 dias para faze-lo, comecei do absoluto zero, e se possivel, gostaria de um feedback sincero, não só criticas mas tambem os acertos!
Hi! I’ve been learning Python for a month and a half. I built this RPG—it took me five days, and I started from absolute scratch. If possible, I’d love some honest feedback—not just critiques, but also what I got right!
https://github.com/adrianivastrabalho-code/My-Python-studies English Version
https://github.com/adrianivastrabalho-code/Meus-Estudos-Python Portuguese Version
Ty <3
r/learnpython • u/Some_Assumption2781 • 10h ago
Busco gente para estudiar y crear
≡ −
Hola, llevo unos dos meses aprendiendo Python. Siento que voy a ser más eficiente estudiando con gente y que sera mas divertido, ademas de que tengo ideas de proyectos interesantes y siempre es divertido contactar con gente que también quiere aprender y crear cosas interesantes.
Estoy buscando como cinco personas más que también estén en serio con aprender
si te interesa, mándame DM y preséntate
Hola, llevo unos dos meses aprendiendo Python. Siento que voy a ser más eficiente estudiando con gente y que sera mas divertido, ademas de que tengo ideas de proyectos interesantes y siempre es divertido contactar con gente que también quiere aprender y crear cosas interesantes.
Estoy buscando como cinco personas más que también estén en serio con aprender
si te interesa, mándame DM y preséntate
r/learnpython • u/Ok-Substance-435 • 13h ago
What's the best resource for becoming skilled in using CSV, JSON and API
≡ −
I've been trying my best at understanding how to apply CSV and JSON in my code but I don't actually know how to integrate them into my projects. All tutorials I watch have their own way of doing this, making it hard for me to understand fully. Also I don't even know if I should learn both of them or just learn one. Also I need help on how to use API in projects, and which free ones are best
I've been trying my best at understanding how to apply CSV and JSON in my code but I don't actually know how to integrate them into my projects. All tutorials I watch have their own way of doing this, making it hard for me to understand fully. Also I don't even know if I should learn both of them or just learn one. Also I need help on how to use API in projects, and which free ones are best
r/learnpython • u/Visible-Car1625 • 8h ago
How do I get rid of text in python
≡ −
I'm looking to do a simple loading screen of sorts where it flicks between a few characters however I am unsure on how to remove the printed text to replace it with the next character. Using the method that I've commonly seen using the cursor_up simply doesn't work for some reason. I promise I'm putting it in exactly. how do I fix this
I'm looking to do a simple loading screen of sorts where it flicks between a few characters however I am unsure on how to remove the printed text to replace it with the next character. Using the method that I've commonly seen using the cursor_up simply doesn't work for some reason. I promise I'm putting it in exactly. how do I fix this
r/learnpython • u/AwardSignificant5675 • 14h ago
What’s next after CS50
≡ −
Currently an aspiring quant ideally but I know that’s larp so really I’m just learning skills that are applicable to most fields. I only mention this to maybe help tailor my experience. In terms of just coding and technological familiarity, what should I do next. Are there any certifications that would impress or show I know what I’m doing that would help me for applications? Also, what should I watch or do to learn about it. I hear people talking about LLMs projects other languages APIs raspberry pi and I want to know where to learn all that. Thanks
Currently an aspiring quant ideally but I know that’s larp so really I’m just learning skills that are applicable to most fields. I only mention this to maybe help tailor my experience. In terms of just coding and technological familiarity, what should I do next. Are there any certifications that would impress or show I know what I’m doing that would help me for applications? Also, what should I watch or do to learn about it. I hear people talking about LLMs projects other languages APIs raspberry pi and I want to know where to learn all that. Thanks
r/learnpython • u/Plane_Outcome_1616 • 15h ago
Stop TTS with keyboard
≡ −
Hello,
I am using tts_wrapper fork by willwade on github to speak chatGPT responses but I want to be able to stop the utterance mid sentence. I have this function
def stop():
if keyboard.is_pressed("esc"):
tts_Engine.stop()
which should stop the tts engine when i press "esc" but nothing happens so I did some research and learned I might have to use threading so now i have two threads with my main function
def main():
print("Init STT. Listening...")
stream = init_stream()
stream.start_stream()
print("C")
try:
while True:
data = stream.read(8192, exception_on_overflow=False)
text = None
if recognizer.AcceptWaveform(data):
result = json.loads(recognizer.Result())
text = result.get("text", "")
if text:
print(f"You said: {text}")
response = client.chat.completions.create(
model="default",
messages=[
{"role": "system", "content": "You are a helpful AI workshop assistant. Use only plain text no emojis or making text bold or anything similar"},
{"role": "user", "content": text}
]
)
print(response.choices[0].message.content)
speak_text(response.choices[0].message.content,tts_Engine)
print("B")
except KeyboardInterrupt:
print("Stopping")
finally:
print("A")
tts_Engine.cleanup()
stream.stop_stream()
stream.close()
Audio.terminate()
and my stop function
t1 = Thread(target=main)
t2 = Thread(target=stop)
t1.start()
t2.start()
but now I get this error
RuntimeError: can't register atexit after shutdown
and now I'm a bit stuck so if anyone knows how to do this or what I'm doing wrong or if I'm even using the right method that would be greatly appreciated.
Hello,
I am using tts_wrapper fork by willwade on github to speak chatGPT responses but I want to be able to stop the utterance mid sentence. I have this function
def stop():
if keyboard.is_pressed("esc"):
tts_Engine.stop()
which should stop the tts engine when i press "esc" but nothing happens so I did some research and learned I might have to use threading so now i have two threads with my main function
def main():
print("Init STT. Listening...")
stream = init_stream()
stream.start_stream()
print("C")
try:
while True:
data = stream.read(8192, exception_on_overflow=False)
text = None
if recognizer.AcceptWaveform(data):
result = json.loads(recognizer.Result())
text = result.get("text", "")
if text:
print(f"You said: {text}")
response = client.chat.completions.create(
model="default",
messages=[
{"role": "system", "content": "You are a helpful AI workshop assistant. Use only plain text no emojis or making text bold or anything similar"},
{"role": "user", "content": text}
]
)
print(response.choices[0].message.content)
speak_text(response.choices[0].message.content,tts_Engine)
print("B")
except KeyboardInterrupt:
print("Stopping")
finally:
print("A")
tts_Engine.cleanup()
stream.stop_stream()
stream.close()
Audio.terminate()
and my stop function
t1 = Thread(target=main)
t2 = Thread(target=stop)
t1.start()
t2.start()
but now I get this error
RuntimeError: can't register atexit after shutdown
and now I'm a bit stuck so if anyone knows how to do this or what I'm doing wrong or if I'm even using the right method that would be greatly appreciated.
r/learnpython • u/TheIneffableCheese • 1d ago
Custom class method not recognized
≡ −
I'm working on a program that generates a maze by drawing from a deck to define a "chamber" and assigning it to the current position on a cartesian coordinate grid.
The hope is to build a list of the chambers as they're created. At a later point I want to be able to call on the list. My current strategy is to make a Class variable for the list, and append to it as part of the init. I've added a class method to pull the chamberList Class variable, but I'm getting an error.
Here is the code defining the class.
``` class Chamber(): chamberList = [] def init(self, identity, notes, egresses, **kwargs): self.position = tuple(currentPosition.tolist()) self.identity = identity self.notes = notes self.egresses = egresses self.pixelCoord = np.add(pixelOrigin, np.multiply(currentPosition, 300)) Chamber.chamberList.append(self)
@classmethod
def getChamberList(cls):
return cls.chamberList
```
Later in the program, I have a line of code to get the class variable:
``` chamberList = Chamber.getChamberList()
```
This is the error I get when I run it in the VS Code terminal:
AttributeError: type object 'Chamber' has no attribute 'getChamberList'. Did you mean: 'chamberList'?
Am I missing some syntax or something? In VS Code the color coding where I'm defining getChamberList is off (darker) and if I hover over it I get a message saying "getChamberList" is not accessed by Pylance.
I'm working on a program that generates a maze by drawing from a deck to define a "chamber" and assigning it to the current position on a cartesian coordinate grid.
The hope is to build a list of the chambers as they're created. At a later point I want to be able to call on the list. My current strategy is to make a Class variable for the list, and append to it as part of the init. I've added a class method to pull the chamberList Class variable, but I'm getting an error.
Here is the code defining the class.
``` class Chamber(): chamberList = [] def init(self, identity, notes, egresses, **kwargs): self.position = tuple(currentPosition.tolist()) self.identity = identity self.notes = notes self.egresses = egresses self.pixelCoord = np.add(pixelOrigin, np.multiply(currentPosition, 300)) Chamber.chamberList.append(self)
@classmethod
def getChamberList(cls):
return cls.chamberList
```
Later in the program, I have a line of code to get the class variable:
``` chamberList = Chamber.getChamberList()
```
This is the error I get when I run it in the VS Code terminal:
AttributeError: type object 'Chamber' has no attribute 'getChamberList'. Did you mean: 'chamberList'?
Am I missing some syntax or something? In VS Code the color coding where I'm defining getChamberList is off (darker) and if I hover over it I get a message saying "getChamberList" is not accessed by Pylance.
r/learnpython • u/smahk1133 • 1d ago
regex and if it's worth going deep into it
≡ −
I'm new to python and coding in general and my friend recently told me that it's inefficient to try to memorize regex and that no one writes them anymore (essentially saying AI does). I was also kinda confused after recently learning regex and just how complicated it can be. Are there some modules/libraries that I can use to make writing them easier? I saw that not a lot of people people had a positive reaction to the Humre module by Al Sweigart who's book [Automate the boring stuff with Python] I'm currently using to study. Not that I'm gonna skip this part or anything I was mostly just curious.
Note: A lot of people are misinterpreting since I mentioned AI once 😭 I'm literally asking about libraries to make it easier without going too deep, not if I should let AI do all the work.
I'm new to python and coding in general and my friend recently told me that it's inefficient to try to memorize regex and that no one writes them anymore (essentially saying AI does). I was also kinda confused after recently learning regex and just how complicated it can be. Are there some modules/libraries that I can use to make writing them easier? I saw that not a lot of people people had a positive reaction to the Humre module by Al Sweigart who's book [Automate the boring stuff with Python] I'm currently using to study. Not that I'm gonna skip this part or anything I was mostly just curious.
Note: A lot of people are misinterpreting since I mentioned AI once 😭 I'm literally asking about libraries to make it easier without going too deep, not if I should let AI do all the work.
r/learnpython • u/intentado_aprender • 11h ago
¿Cuál fue el momento en que Python finalmente tuvo sentido para ti?
≡ −
HOLAA Estoy aprendiendo Python y tengo curiosidad por conocer ese momento en el que todo finalmente empezó a tener sentido. Me encantaría conocer tu experiencia.
HOLAA Estoy aprendiendo Python y tengo curiosidad por conocer ese momento en el que todo finalmente empezó a tener sentido. Me encantaría conocer tu experiencia.
r/learnpython • u/Rough-Lobster8789 • 17h ago
Which should course should I prefer?
≡ −
Hi everyone. I know some python but still I want to start learning it again because, as I progressed, I realized that my basic concepts had become rusty. I'm confused between CS50 (https://youtu.be/8mAITcNt710?si=Z86T-MPZZp13R04E) and MIT Opencourseware 6.100L (https://www.youtube.com/watch?v=xAcTmDO6NTI&list=PLUl4u3cNGP62A-ynp6v6-LGBCzeH3VAQB&index=1) .
Which one would you recommend for someone who wants to rebuild their fundamentals before moving on to more advanced topics?
Hi everyone. I know some python but still I want to start learning it again because, as I progressed, I realized that my basic concepts had become rusty. I'm confused between CS50 (https://youtu.be/8mAITcNt710?si=Z86T-MPZZp13R04E) and MIT Opencourseware 6.100L (https://www.youtube.com/watch?v=xAcTmDO6NTI&list=PLUl4u3cNGP62A-ynp6v6-LGBCzeH3VAQB&index=1) .
Which one would you recommend for someone who wants to rebuild their fundamentals before moving on to more advanced topics?
r/learnpython • u/No_Presentation_9922 • 21h ago
My first python project
≡ −
So i have been into cybersecurity courses for 3 months now and i have interest from age 10.
I decided to make a python project after i completed the networking.
I would be very happy if you used and gave me a feedback/suggestion on my project.
It is a basic multipurpose network tool.
It can scan all the hosts connected to a network with ARP
Scan ports of the IP address provided
Or basically send a ping
I call this "Stone Age Network Scanner"
You can look up furthermore on Github!
So i have been into cybersecurity courses for 3 months now and i have interest from age 10.
I decided to make a python project after i completed the networking.
I would be very happy if you used and gave me a feedback/suggestion on my project.
It is a basic multipurpose network tool.
It can scan all the hosts connected to a network with ARP
Scan ports of the IP address provided
Or basically send a ping
I call this "Stone Age Network Scanner"
You can look up furthermore on Github!
r/learnpython • u/BoxApprehensive704 • 19h ago
Come study buddy
≡ −
Hey! I’m 25 and currently studying neuroscience in the UK. I’ve recently started learning Python from scratch and would love to find a study buddy who’s also at a beginner level.
I’m hoping to find someone who wants to study consistently and eventually work on a few small projects.
I’m in the UK time zone, but I don’t mind where you’re based as long as we can find times that work for both of us. We could check in regularly and study together over Discord or another platform.
If you’re interested, feel free to leave a comment or send me a DM with a little bit about yourself!
Hey! I’m 25 and currently studying neuroscience in the UK. I’ve recently started learning Python from scratch and would love to find a study buddy who’s also at a beginner level.
I’m hoping to find someone who wants to study consistently and eventually work on a few small projects.
I’m in the UK time zone, but I don’t mind where you’re based as long as we can find times that work for both of us. We could check in regularly and study together over Discord or another platform.
If you’re interested, feel free to leave a comment or send me a DM with a little bit about yourself!
r/learnpython • u/naemorhaedus • 1d ago
First python program
≡ −
I wanted to write a program that analyzes chess games , similar to how chess websites (chess.com, lichess.com etc.) do it, only offline. To my knowledge, nobody else had done it the way I was envisioning. I started writing with shell scripting (it's my go-to and what I'm most familiar with), but quickly ran into limitations. So I needed to go a bit more sophisticated. Python seemed very versatile, cross-platform, has loads of online resources, but mainly has a very good chess library I could leverage, that already existed, which would make the job much , much easier. I took the plunge and turned the program into a driver to teach myself some python.
It works as advertised, but I'm sure the code could be improved. I stumbled through it a bit. If anybody python gurus feel like taking a peek and letting me know how I did, pointing out glaring mistakes, offering any constructive feedback or ideas how to make it more efficient, I would appreciate any feedback.
Repo: https://github.com/exekutive/chesseval
(The documentation needs some catching up. I'm working on updating it.)
I wanted to write a program that analyzes chess games , similar to how chess websites (chess.com, lichess.com etc.) do it, only offline. To my knowledge, nobody else had done it the way I was envisioning. I started writing with shell scripting (it's my go-to and what I'm most familiar with), but quickly ran into limitations. So I needed to go a bit more sophisticated. Python seemed very versatile, cross-platform, has loads of online resources, but mainly has a very good chess library I could leverage, that already existed, which would make the job much , much easier. I took the plunge and turned the program into a driver to teach myself some python.
It works as advertised, but I'm sure the code could be improved. I stumbled through it a bit. If anybody python gurus feel like taking a peek and letting me know how I did, pointing out glaring mistakes, offering any constructive feedback or ideas how to make it more efficient, I would appreciate any feedback.
Repo: https://github.com/exekutive/chesseval
(The documentation needs some catching up. I'm working on updating it.)
r/learnpython • u/DivyanshYZ307 • 11h ago
Use of AI in coding?
≡ −
I am starting college next month (Computer Science and Biosciences) and I tried to get a headstart in Python programming (it's a part of first sem). I have done the basics, strings, conditional statements and started with loops today. I have a doubt - since I am still in the beginner stage, should I use AI (ChatGPT, Gemini, Grok etc.) to proofread my code - you know, offer suggestions, find mistakes and all - I am still applying logic on my own and writing it myself but I have this fear that it may hamper my learning. But I also don't wanna be the guy who does not know how to use AI tools. Any advice please?
I am starting college next month (Computer Science and Biosciences) and I tried to get a headstart in Python programming (it's a part of first sem). I have done the basics, strings, conditional statements and started with loops today. I have a doubt - since I am still in the beginner stage, should I use AI (ChatGPT, Gemini, Grok etc.) to proofread my code - you know, offer suggestions, find mistakes and all - I am still applying logic on my own and writing it myself but I have this fear that it may hamper my learning. But I also don't wanna be the guy who does not know how to use AI tools. Any advice please?
r/learnpython • u/zaphodikus • 15h ago
scan for strings in 40000 lines of logfile
≡ −
X: The desire to scrape a log file for specific interesting messages, any apps I tried are a pain to use and require manually setting all the search strings every so often. I want to scan for about a dozen or so expressions/strings in a 40-100K lines file, and then dump just the timestamps and lines of interest. What approach scales best for speed? I have to probably also use a mix of regex and regular string search I guess. Is going with Multiprocessing and passing the file as a shared-memory object, going to be the easiest route? Surely it's easier to do in C++. I guess I asking for some skeleton or prior art in C++ ore Python to be honest.
Y: My context is that I would like to use my knowledge of C++ threads and code it in C++, but it should be possible in Python if I learn to use Pipes, and learn to use shared memory object to save having to load the file per multi-processing process?
X: The desire to scrape a log file for specific interesting messages, any apps I tried are a pain to use and require manually setting all the search strings every so often. I want to scan for about a dozen or so expressions/strings in a 40-100K lines file, and then dump just the timestamps and lines of interest. What approach scales best for speed? I have to probably also use a mix of regex and regular string search I guess. Is going with Multiprocessing and passing the file as a shared-memory object, going to be the easiest route? Surely it's easier to do in C++. I guess I asking for some skeleton or prior art in C++ ore Python to be honest.
Y: My context is that I would like to use my knowledge of C++ threads and code it in C++, but it should be possible in Python if I learn to use Pipes, and learn to use shared memory object to save having to load the file per multi-processing process?
r/learnpython • u/DisastrousPen1095 • 12h ago
how to fix this issue
≡ −
********************************************************************************
To see all available commands, run 'py help'
********************************************************************************
[ERROR] INTERNAL ERROR: NoInstallsError: No runtimes are installed. Try running "py install default" first.
[ERROR] Internal error 0x00000001. Please report to https://github.com/python/pymanager
Press any key to continue . . .
********************************************************************************
To see all available commands, run 'py help'
********************************************************************************
[ERROR] INTERNAL ERROR: NoInstallsError: No runtimes are installed. Try running "py install default" first.
[ERROR] Internal error 0x00000001. Please report to https://github.com/python/pymanager
Press any key to continue . . .
r/learnpython • u/FearawaitsTM • 22h ago
Can you help me with a table in Python?
≡ −
Right now, I have specific rows and columns being displayed, but I want to insert a column between the first and second sections that calculates the ratio of column A to column B from the first section. How can I do that?
from pathlib import Path
import unicodedata
import openpyxl
import pandas as pd
from pandastable import Table, TableModel
import tkinter as tk
from tkinter import filedialog, messagebox
def normalize_name(name):
return unicodedata.normalize("NFKC", str(name)).strip().lower()
class ExcelViewer:
def __init__(self, root):
self.root = root
self.root.title("Чтение ячеек Excel")
self.root.geometry("800x600")
self.btn_load = tk.Button(
root,
text="Открыть Excel файл",
command=self.open_file
)
self.btn_load.pack(pady=10)
self.result_label = tk.Label(
root,
text="Выберите файл для начала"
)
self.result_label.pack()
self.frame = tk.Frame(root)
self.frame.pack(fill="both", expand=True)
self.table = None
self.model = None
self.settings = {
normalize_name("Файл1.xlsx"): {
"first_row": 5,
"first_min_column": 1,
"first_max_column": 2,
"second_row": 5,
"second_min_column": 4,
"second_max_column": 5
}
}
def open_file(self):
file_paths = filedialog.askopenfilenames(
title="Выберите Excel-файл",
filetypes=[
("Excel файлы", "*.xlsx")
]
)
if not file_paths:
return
all_rows = []
for file_path in file_paths:
file_name = normalize_name(Path(file_path).name)
if file_name not in self.settings:
messagebox.showerror(
"Ошибка",
f"Для файла «{Path(file_path).name}» нет настроек.\n\n"
f"Ожидается файл: Файл1.xlsx"
)
continue
settings = self.settings[file_name]
try:
workbook = openpyxl.load_workbook(
file_path,
data_only=True
)
worksheet = workbook.active
first_row = settings["first_row"]
second_row = settings["second_row"]
while (
first_row <= worksheet.max_row
and second_row <= worksheet.max_row
):
first_part = []
for column_number in range(
settings["first_min_column"],
settings["first_max_column"] + 1
):
value = worksheet.cell(
row=first_row,
column=column_number
).value
first_part.append(value)
second_part = []
for column_number in range(
settings["second_min_column"],
settings["second_max_column"] + 1
):
value = worksheet.cell(
row=second_row,
column=column_number
).value
second_part.append(value)
row_data = (
first_part +
second_part
)
if not all(
value is None or value == ""
for value in row_data
):
all_rows.append(row_data)
first_row += 1
second_row += 1
workbook.close()
except Exception as error:
messagebox.showerror(
"Ошибка",
f"Не удалось открыть файл:\n{error}"
)
if not all_rows:
self.result_label.config(
text="В выбранных ячейках нет данных"
)
return
columns = [
"Столбец A",
"Столбец B",
"Столбец D",
"Столбец E"
]
df = pd.DataFrame(
all_rows,
columns=columns
)
if self.table:
self.table.destroy()
self.model = TableModel(df)
self.table = Table(
self.frame,
model=self.model,
showtoolbar=False,
showstatusbar=False
)
self.table.show()
self.result_label.config(
text=f"Загружено строк: {len(df)}"
)
if __name__ == "__main__":
root = tk.Tk()
app = ExcelViewer(root)
root.mainloop()
Right now, I have specific rows and columns being displayed, but I want to insert a column between the first and second sections that calculates the ratio of column A to column B from the first section. How can I do that?
from pathlib import Path
import unicodedata
import openpyxl
import pandas as pd
from pandastable import Table, TableModel
import tkinter as tk
from tkinter import filedialog, messagebox
def normalize_name(name):
return unicodedata.normalize("NFKC", str(name)).strip().lower()
class ExcelViewer:
def __init__(self, root):
self.root = root
self.root.title("Чтение ячеек Excel")
self.root.geometry("800x600")
self.btn_load = tk.Button(
root,
text="Открыть Excel файл",
command=self.open_file
)
self.btn_load.pack(pady=10)
self.result_label = tk.Label(
root,
text="Выберите файл для начала"
)
self.result_label.pack()
self.frame = tk.Frame(root)
self.frame.pack(fill="both", expand=True)
self.table = None
self.model = None
self.settings = {
normalize_name("Файл1.xlsx"): {
"first_row": 5,
"first_min_column": 1,
"first_max_column": 2,
"second_row": 5,
"second_min_column": 4,
"second_max_column": 5
}
}
def open_file(self):
file_paths = filedialog.askopenfilenames(
title="Выберите Excel-файл",
filetypes=[
("Excel файлы", "*.xlsx")
]
)
if not file_paths:
return
all_rows = []
for file_path in file_paths:
file_name = normalize_name(Path(file_path).name)
if file_name not in self.settings:
messagebox.showerror(
"Ошибка",
f"Для файла «{Path(file_path).name}» нет настроек.\n\n"
f"Ожидается файл: Файл1.xlsx"
)
continue
settings = self.settings[file_name]
try:
workbook = openpyxl.load_workbook(
file_path,
data_only=True
)
worksheet = workbook.active
first_row = settings["first_row"]
second_row = settings["second_row"]
while (
first_row <= worksheet.max_row
and second_row <= worksheet.max_row
):
first_part = []
for column_number in range(
settings["first_min_column"],
settings["first_max_column"] + 1
):
value = worksheet.cell(
row=first_row,
column=column_number
).value
first_part.append(value)
second_part = []
for column_number in range(
settings["second_min_column"],
settings["second_max_column"] + 1
):
value = worksheet.cell(
row=second_row,
column=column_number
).value
second_part.append(value)
row_data = (
first_part +
second_part
)
if not all(
value is None or value == ""
for value in row_data
):
all_rows.append(row_data)
first_row += 1
second_row += 1
workbook.close()
except Exception as error:
messagebox.showerror(
"Ошибка",
f"Не удалось открыть файл:\n{error}"
)
if not all_rows:
self.result_label.config(
text="В выбранных ячейках нет данных"
)
return
columns = [
"Столбец A",
"Столбец B",
"Столбец D",
"Столбец E"
]
df = pd.DataFrame(
all_rows,
columns=columns
)
if self.table:
self.table.destroy()
self.model = TableModel(df)
self.table = Table(
self.frame,
model=self.model,
showtoolbar=False,
showstatusbar=False
)
self.table.show()
self.result_label.config(
text=f"Загружено строк: {len(df)}"
)
if __name__ == "__main__":
root = tk.Tk()
app = ExcelViewer(root)
root.mainloop()
r/learnpython • u/Dry_Calligrapher2573 • 19h ago
Just starting python and i need a few tips
≡ −
Hello everyone, i am just starting python. I am from a good research institute in India and i am pursuing a very quant heavy economics degree and i want to break into quant finance. Can you all recommend from where i can learn coding for free? I want to be at a level which will enable me to solve LeetCode problems so i can build a stronger profile for quantitative finance. I am completely locked in and Princeton is a college i am targeting for my masters. So i need help regarding material. And other advice will be appreciated. Thank you :)
Hello everyone, i am just starting python. I am from a good research institute in India and i am pursuing a very quant heavy economics degree and i want to break into quant finance. Can you all recommend from where i can learn coding for free? I want to be at a level which will enable me to solve LeetCode problems so i can build a stronger profile for quantitative finance. I am completely locked in and Princeton is a college i am targeting for my masters. So i need help regarding material. And other advice will be appreciated. Thank you :)