/r/learnpython
Subreddit for posting questions and asking for general advice about all topics related to learning python.
1: Be polite
2: Posts to this subreddit must be requests for help learning python.
3: Replies on this subreddit must be pertinent to the question OP asked.
4: No replies copy / pasted from ChatGPT or similar.
5: No advertising. No blogs/tutorials/videos/books/recruiting attempts.
This means no posts advertising blogs/videos/tutorials/etc, no recruiting/hiring/seeking others posts. We're here to help, not to be advertised to.
Please, no "hit and run" posts, if you make a post, engage with people that answer you. Please do not delete your post after you get an answer, others might have a similar question or want to continue the conversation.
Wiki and FAQ: /r/learnpython/w/index
/r/learnpython
Hello everyone,
I trying to optimise a bit of code I have written. The code works for what I want to do but I am wondering if there is faster way of implementing it. I've attached two methods below that do the same thing. The first uses 6 for loops and the second 4 for loops, where I've removed two loops by broadcasting into 6-dimensional arrays. I thought the second approach might be faster since it uses less for loops, but I guess the memory cost of the broadcasting is too great. Is there something you guys see to improve speed?
First method:
for i in tqdm(range(gridsize)):
for j in range(gridsize):
F_R = F0[i][j]
for u in range(max(0, i - Nneighbours), min(gridsize, i + Nneighbours + 1)):
for v in range(max(0, j - Nneighbours), min(gridsize, j + Nneighbours + 1)):
F_Rprime = F0_rot[u][v]
F_RRprime = F0[i - u + halfgrid][j - v + halfgrid] + F_R@T@F_Rprime
for m in range(dims):
for n in range(dims):
A = slices[i][j][m]
B = slices[u][v][n]
F_RRprime_mn = F_RRprime[m][n]
F_Rr = B*A*F_RRprime_mn
total_grid += F_Rr
Second method:
for i in tqdm(range(gridsize)):
for j in range(gridsize):
A = slices[i, j]
F_R = F0[i, j]
for u in range(max(0, i - Nneighbours), min(gridsize, i + Nneighbours + 1)):
for v in range(max(0, j - Nneighbours), min(gridsize, j + Nneighbours + 1)):
B = slices[u, v]
F_Rprime = F0_rot[u, v]
F_RRprime = F0[i - u + halfgrid][j - v + halfgrid] + F_R@T@F_Rprime
F_Rr = A[:, None, ...] * B[None, :, ...] * F_RRprime[:, :, None, None, None, None]
total_grid += F_Rr
EDIT: For some context the aim to have have dims = 16, gridsize = 101, pixels = 15
I’ve been using/learning with ai to build a desktop app but I am struggling with building the UI I want… I have the exact idea in a Canva made image but not sure how to convert to Python?
Is there a way to do this or?
Edit : forgot the question mark.
Hello everyone, I am currently learning to program with python, but I am trying to execute code and I get an error, do you know why?
I get the following error:
PS C:\Users\FORIMPEX\Documents\PYTHON HOLA MUNDO> python intro.py
C:\Users\FORIMPEX\AppData\Local\Programs\Python\Python313\python.exe: can't open file 'C:\\Users\\FORIMPEX\\Documents\\PYTHON HOLA MUNDO\\intro.py': [Errno 2] No such file or directory
PS C:\Users\FORIMPEX\Documents\PYTHON HOLA MUNDO>
example:
a = 'test'
how can 'a' be used to call a subroutine called test?
hello, I'm trying to decode this QR code (captured via a camera). The original QR code is a version 20 QR code that just encodes the string:
"Some data"
I'm using the qreader library for this. Here's my code:
qreader = QReader(model_size='l')
# Get the image that contains the QR code
image = cv2.cvtColor(cv2.imread("qr_20.jpg"), cv2.COLOR_BGR2RGB)
# I resized the image here as I heard bigger images have trouble processing. But doing so or not doesn't help with decoding
image = cv2.resize(image, (1050, 1050), interpolation=cv2.INTER_AREA)
image = cv2.flip(image, 1)
cv2.imwrite("blurred.jpg", image) # so I can see the end result after resize
# I'm calling detect() first to see if it's actually detecting the QR code, which it does.
detected_text = qreader.detect(image=image)
print(f"=> amount of detections {len(detected_text)}")
print(detected_text[0])
# At decoding, qreader returns "(None,)" , indicating it failed to decode.
decoded_text = qreader.detect_and_decode(image=image)
print(f"=> detected: {decoded_text}")
Anything I'm missing? Thanks!
So I very slowly worked through a Python Github course. It took me a long time. Then I started a Flask course on Udemy. The course didn’t really challenge me to solve coding challenges on my own. Then from there I ordered a Flask book, which arrives tomorrow.
Thing is, I don’t know if a book or course is the ideal way to go. I’m thinking of getting a subscription to RealPython but it’s a lot of money.
Would code wars + youtube be worth a try?
In a previous post, I asked this community for help with an assignment I was struggling with and received some answers that helped me figure out a problem with the teacher's restrictions. However, after turning it in, I didn’t quite do it the way he had anticipated. As a result, he modified the assignment so that I now have to write a program that determines if a ship is between two planets based on its distance traveled at a speed of 150,000 miles per second, within a time interval of 0 to 1 day. The program must be written using only three if statements (he counts elif
as another if
statement). I’m not allowed to use things like lists, indices, or while
or for
loops—just basic if
and else
statements.
I’ve been stumped after days of work. Does anyone have any ideas?
Let me know if you need anything else!
Complete guide for venv
This is my first video on YouTube where I explain VENV Python Virtual Environments in great details
https://youtu.be/HNZgiWSog8Q?si=WBULorTJjQyEFQzZ
Any thoughts or criticism... 🧐🤔
Do you guys recommend getting Linux to run through Windows 11 or making Linux the main os. And what is the differences?
For those who are way over “Day 15” or have completed the whole thing, which day should I have to learn upto in order to make a simple app to submit as a portfolio I am a bit short on time like about 10-12 days I have already completed upto Day 2
Also suggest any platform where I can make and share (maybe Streamlit) maybe something else
Just asking for general advice
Many people start out with python as it is basic..
For someone who aims for full stack development.. What should he do?
Go for js altogether or learn python for backend and js for frontend.... How difficult is it to integrate?
Or just learning js is enough?
Like the header says. I'm good with Tkinter, qt designer and others and I built a calculator in py to apk.
It's been a month since I start learning Python again. And I learn a lot and finally managed to complete 2 projects, a ToDoList Maker and File Manager but in CLI.
ToDoList Maker helped me(or forced me) to learn lots of fundamental build-in stuffs about Python. The CLI File Manager helped me to learn about Curses Programming, but boy, It was so intense, especially because the documentation was suck and there was no big info on the internet. With that said, that means I was [mostly] on my own.
While I was creating that CLI File Manager, I mostly managed to solve the problems by myself. But eventually, I will be stuck at the scrolling page. It seems like it is very easy but it was too complicated for my stupid ass. Even though, I promised myself not to use ChatGPT at all, I broke my promise Because, searching on the internet or re-reading the documentation was just making me more suffer, so I decided to lend a hand from that stupid AI
Anyhow though, the info from ChatGPT was really small. And believe it or not, I managed to extend it and polish it with lots of counter variables. BUT if I didn't use ChatGPT at all, I wouldn't able to extend or polish or even know how to solve. Nope I will not/never 100000 times.
Well that's the fact I hate, I thought programming was about being able to solve problems and I couldn't even find the solution for simple scrolling? Anyway I want to improve it, sorry for beating around the bush.
THANKS IN ADVANCE
I was assigned an automation task at work and in my graduation program we had a semester off Python, so I am RUSTY. I'm struggling through remembering all the functionalities that come with pandas and numpy, it's shameful. I'm not a beginner coder so I don't want a super basic tutorial, but does anyone have recommendations for me to get reacquainted with ETA and DTL tasks in Python?
AssertionError: Class <class 'sqlalchemy.sql.elements.SQLCoreOperations'> directly inherits TypingOnly but has additional attributes {'__firstlineno__', '__static_attributes__'}.
I'm try to use SQL but this error keeps happing when I run the program. I have the most updated version for python and SQL. Thanks
Hey i am a BTech sophomore and solved 300+ leetcode problems I want to build really really good full stack ML projects so for that should i choose FastAPI or Django for my backend?
i created a exe in auto py and it opens the dialogue box and i input the numbers i need to for the program then it shows the output for a split second then closes
I just need help figuring out what I'm supposed to do. A friend of mine wants me to print out some experimental roles for a social deduction game. He found this GitHub resource that supposedly can download all of the tokens from the official site. https://github.com/Tsubashi/botc_tokens
The problem is the instructions for the use of the program assume you are already familiar with how to use Python. I downloaded the latest release of Python and installed it. However, the next step just says:
Once you have Python installed, you can install these scripts using pip
:
pip install botc_tokens
And I have no idea what that means or how to do it.
Can someone please provide a step-by-step guide on how I actually use Python to execute this command? Assume I have zero programming knowledge and need to know literally everything I type or click or whatever. I'm not a complete dumbass with computers by any means, but I can't figure out how to navigate Python to the root directory. It just keeps giving me a syntax error, and the "tutorials" online make my eyes glaze over because they don't make any sense.
Hi! I am working on a basic TicTacToe game in Python and came across an issue in my code.
I initially wrote this:
import numpy as np
input = int(input("How many rows and columns would you like to play with?:"))
row =['_']*input
for i in range(input):
print(row)
This worked correctly and gave me a 3 vertical arrays of '_' which were being used as placeholders for modification later; however when I tried to make my code neater by creating a function it stopped working.
def gamestartup():
input = int(input("How many rows and columns would you like to play with?:"))
row =['_']*input
for i in range(input):
print(row)
gamestartup()
While searching online I saw someone mention that it was bad practice to use an input function inside a function definition. I also found out that the input function was being registered as a variable by Python. How python interprets my input as a variable and gives an error in the 2nd code, but when the code is pasted the same way globally it works fine??
Hello Everyone. So I have learned up to the very basics of Python (such as variables, data types, lists, if else, dictionary, loops, user input, functions, classes, files, and exceptions). I am also fairly comfortable with Numpy, Pandas, and Matplotlib.
Also, I recently discovered Corey Schafer's playlist and found that he covered a lot of topics about Python that constitute a useful skillset (such as Django, Web Scraping, Flask, etc.) and I am quite eager to learn and internalize them.
I, however, find it difficult to work along with only videos and was wondering if some alternative resources cover the same skillset, along which I can work (Personally working along with the tutorial is the way that I find most effective for me).
I would be glad if anyone could share some of such resources. Resources that would get me up to the point where I can start creating projects.
Please feel free to share your resources, advice, and suggestions. I want to keep an open mindset about learning and don't want to constrain myself only to the topics that I specified above.
I keep getting import error when im trying to import a function from another python file. They are in the same directory and there are no typos. The code requires me to read a csv file on one python file in a function then returns a result. Then on another python file it imports the other file's function but whenever i run the main python file it keeps giving me import error. I would like to share the code but i dont know how here.
Can someone give me a dummy explanation for the difference between scripts and programs. Because I was going to learn how to becoming ethical hacker through python but now I'm seeing things like I need Kali Linux python and another programming language. And people use them for different things. So I'm not sure what the best direction would be. Any advice would be greatly appreciated thank you!
Hi,
In a small project I'm working on, I need to check if a SRT caption duration is no longer than 2 seconds.
I'm using pysubparser for this.
Timestamps are given like this: 00:38:01.114000, 00:38:03.242000
(Hours, minutes, seconds, milliseconds)
This is my aproach, which I know is incorrect:
indexStartTimestamp = subtitles[srtIndexChoice].start
indexEndTimestamp = subtitles[srtIndexChoice].end
maxLength = datetime.strptime("00:00:02.00", "%H:%M:%S.%f")
if datetime.datetime(indexEndTimestamp) - datetime.datetime(indexStartTimestamp) > datetime.datetime(maxGifLength):
indexEndTimestamp = indexStartTimestamp + maxLength
As you can see, if the duration is longer than 2 seconds, I try to set the duration max to 2 seconds.
I don't know how to proceed, timestamps are a difficult topic to me and I'm relatively new to python.
Any help and further explanation is highy apreciated. Thanks.
*I don't know how to format correclty code, I tried a couple of times with no success.
I'm a python beginner and I've just finished basics. Can you guys recommend me some projects to build so i can improve my skills and especially make sense of what works in industry?
Thanks :)
I am trying to build a discord bot with discord.py, and I am using the library "discord-ext-voice-recv" to try to make a real-time speech-to-text discord bot.
I recently posted on a problem I was facing with the library "discord-ext-voice-recv", and I managed to solve it, but now here I am again.
I have a bot configured with a command "!join" to join voice chats with the class "voice_recv.VoiceRecvClient" (from the "discord-ext-voice-recv" library). But, I am not managing to detect when someone is speaking.
There are some functions that do that in the library, like:
get_speaking(member: discord.Member | discord.User) -> bool | None
(it gets the speaking state (voice activity, the green circle) of a member.on_voice_member_speaking_start(member: discord.Member)
(basically the same as get_speaking, but it is only active when someone starts talking)The problem is that all of the functions are either non-async, or I can't manage to make it work properly. And I also don't really know who I am supposed to connect the non-async functions with my code at all.
If someone has any suggestions, example codes of similar projects, or anything at all that could help me solve this, I would really appreciate it.
Hello! I am working on my thesis project in python and my project structure is a bit unusual.
Under project/src directory, i divided my scripts and modules based on responsibilities. I consider modules as files containing just function definitions, and scripts as files with calling these functions. My problem is that the scripts are nested in subpackages of src at different depths, so I use import like (import src.subpack1.subpackage11..) but python cannot even find src module when running nested script from project root. Can someone please enlighten me how to make import statements work in all modules at all subpackage levels? I cannot use just one script as I do different things with the functions (i.e plotting in real time, training agent)
Thanks in advance!
Good day, everyone.
After months of learning Python, I've come to the realization that I struggle to think in Python. While I can answer questions related to the language, creating practical applications leaves me feeling blank. Additionally, I find it challenging to apply my knowledge when tackling coding problems on platforms like LeetCode. I'm looking for strategies to enhance my ability to think in Python and apply my skills more effectively.
I have been working on a project that will take real-time data from a Daktronics All Sport 5000 controller and display it on my Windows computer (eventually also on a RaspberryPi) like a scoreboard. Since I'm still very green at Python, this is literally my first deep dive into Python programming, I took an existing project and manipulated it to what I want. What it does now is takes the serial data from the controller with pyserial and using pillow, it creates a PNG with all of the data I want to display. I just edited the pillow data to make it display how I want.
It works, but not as well as I'd like. I can't open the PNG file because it doesn't automatically update, so I have to rely on watching the preview in File Explorer. The problem is that it sporadically doesn't create a PNG, so the preview goes blank for a second or two until a PNG is created. And it doesn't quite update as fast as I'd like. The "skipping" with the PNG generation misses seconds as they are counting down and it's even worse when the clock starts counting down with tenths of a second.
What would be a better way to display this info? I have the scoreboard PNG that acts as the background and the data from the controller is just drawn over the respective fields. Would TKinter be able to make something to do this?
Another goal I have for this is making it executable without going through command prompt. I haven't looked into this process yet, but it's on my to-do list.
Also, as I mentioned earlier, I'd like to use this on a RaspberryPi 3 and display at some point as well.
Any help would greatly be appreciated and I'd be happy to share the project with anyone who's willing to take a look at it or even if this is something you've been looking for.
All I want to do is a bot that, upon joining a call, can detect when someone is talking or stops to talk (basically replicating what discord does to show the lime circle around your icon). I also want to be able to detect what they are saying, but that's for later.
I've tried to use pycord, and I'm currently using discord.py, but I didn't manage to get it work in neither of those.
If someone knows anything that could help me accomplish that (in Python), please share. I've searched around the internet for hours now, and the the only solutions I found were:
TypeError: expected AudioSink not NoneType.
when trying to load channel.connect
with cls=voice_recv.VoiceRecvClient
.And just to give some context, because I guess this idea could be used badly: the goal is to use the STT messages from the bot as input for an LLM, then use the LLM output as input for a TTS. I basically want to make an AI that can talk with people through discord.
So, I'm testing saving files between Pillow and OpenCV, since for some reason saving using Pillow was taking 5 minutes. OpenCV was much faster at (barely) under a minute (50s).
cv2.imwrite("output.webp", image, [cv2.IMWRITE_WEBP_QUALITY, 100])
And
image.save("output.webp", "WEBP", lossless=True, quality=100, method=6)
Are the respective save code I'm using, but here's the result:
Pillow, took 300 seconds (5Minutes) and generated an image about 22 MBs. OpenCV, took 50 sexonds, and generated an image about 11 MBs.
Despite both being lossless webp images, there was clearly a difference between outputs. Why? What caused the difference? Both used the same input (well, the initial image was processed by Pillow and then converted using numpy to something opencv could save, and was a 10kx16k image.)
If the code repo is needed for more context I can provide the link to github, but that should be enough information. Though I welcome any/all suggestions to improve on the script if you do!