/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
I am reading data from excel, and when I am writing it to excel one of the columns SE has gibrish data, when I print data in python it displays fine.
Value in excel [<JIRA User:displayName='Last, Name1', key='fname1',name='FName1'>,<JIRA User: displayName='Last, Name2',key='fname2',name='FName2'>]
I need displayName in different columns or comma separated there can be multiple of these. How can I get this done?
My Challenge:
I’m currently exploring ways to programmatically transform images into videos and apply various effects to make the final output more engaging and lively. My goal is to find a solution that efficiently handles this process with a wide variety of high-quality video effects.
While I’ve experimented with some existing tools, I haven’t found a solution that fully meets my needs in terms of speed, flexibility, and the diversity of available effects.
What I’ve Tested So Far: 1. MoviePy: I gave MoviePy a shot, but found it to be too slow, particularly when dealing with more complex video creation tasks and effects. The processing times made it impractical for my use case. 2. FFmpeg: This tool offers a range of capabilities, but I’ve found it difficult to grasp fully, especially when trying to implement more intricate effects. Additionally, FFmpeg’s built-in effects are relatively limited compared to what I’m aiming for.
What I’m Looking For:
I would like to incorporate the powerful video effects available in Adobe Premiere Pro directly into my Python program. Premiere Pro’s extensive range of high-quality effects is exactly what I need, but I’m unsure if there’s a feasible way to access and control these effects programmatically.
I’m interested in any potential solutions, such as APIs, plugins, or alternative tools that could bridge the gap between Python and professional video editing software like Premiere Pro. I’m also open to suggestions for other libraries or tools that provide a rich variety of effects while maintaining good performance.
Any insights, suggestions, or experiences you could share would be greatly appreciated!
I was trying to implement this method to calculate area of a shape by putting random dots and then calculating the ratio of dots that fall inside the shape. The program doesn't show any error but the blue dots I expected it to draw aren't being drawn and the area is wrong too, I guess... I wanted to consider 1 pixel as 1 unit.
import pygame
import random
# Initialize Pygame
pygame.init()
outside_points=[]
inside_points=[]
screen_width = 600
screen_height = 600
rect_height = 400
rect_width = 400
font = pygame.font.SysFont("Arial", 30)
# Set up the window
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Area calculation')
# Define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
# Game loop
running = True
clock = pygame.time.Clock()
# Fuctions
def random_coordinate(screen_x, screen_y):
x = random.randint(0,screen_x)
y = random.randint(0,screen_y)
return(x,y)
def check_coordinate(coordinate):
if coordinate[0] > rect_width / 2 and coordinate[0] < 600 - rect_width / 2 and coordinate[1] > rect_height / 2 and coordinate[1] < 600 - rect_height / 2:
return 1
else:
return 0
def draw_and_add_coordinates():
coordinate = random_coordinate(screen_width,screen_height)
pygame.draw.circle(screen, BLUE, coordinate, 1 )
if check_coordinate(coordinate)==1:
inside_points.append(coordinate)
else:
outside_points.append(coordinate)
def calculate_stuff():
global text_surface, text_rect
draw_and_add_coordinates()
count_out = len(outside_points)
count_in = len(inside_points)
total_points = count_in + count_out
ratio = count_in/total_points
area_of_rectangle = int(600*600 * ratio)
output_text = str(area_of_rectangle)
text_surface = font.render(output_text, True, (0, 255, 0)) # White color
text_rect = text_surface.get_rect(center=(400, 550)) # Center the text
while running:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
for i in range(10000):
calculate_stuff()
screen.fill(BLACK)
pygame.draw.rect(screen, WHITE,(screen_width/2-rect_width/2, screen_height/2-rect_height/2, 400, 400)),
# Draw game objects here
screen.blit(text_surface, text_rect)
# Update the display
pygame.display.flip()
# Control frame rate
clock.tick(60)
# Clean up
pygame.quit()
Hi everyone,
I'm currently trying to set up 2FA, but from the tutorials and guides I'm watching, I can't seem to figure out how to install it via pip using `pip install pyotp` and then import it in PyCharm—it just doesn't seem to work.
I'm on macOS and have checked through the terminal, but that's only confusing me more at this point. Any help would be greatly appreciated! (Please be kind; I’m super new to this.)
hi i am new to python. we had a quiz question and the result that i waited to see was different. i think i read at somewhere that two lists become the same but i wasnt sure. the code is below. can you explain what is going on at the background. list1=[1,3] list2=list1 list1[0]=4 print(list2)
output is 4,3
Hi, so im currently doing python mooc 2024, up to part 5. IS it normal to feel like some days i have good days where i feel like im understanding and days that feel liek im not?
I just feel like its in and out my head sometimes
I’m programming in python for a while now and have made some decent things. I have one particular project that’s working really well for me. I’m no wondering how do I become better? I feel like I can make the software more efficient, use more advanced ways, etc. But how do you get better when you’re already reasonably well?
I have tried the following
and none of these work it still prints <class '__main__.r'>
class r:
def __str__(self) -> str:
return "yes"
def __repr__(self) -> str:
return "no"
def __unicode__(self):
return "maybe"
r.__repr__ = lambda: "shit"
print(r)
edit extra context:
this is for a streamlit app where I'm passing a list of uninitiated classes to a select widget where the user can select which class to use in a pipeline.
I can't initiative them because some need init arguments that the user chooses.
for now I have made an work around that uses a dictionary where user selects key and then the class gets taken out of the dict
Hi,
I need to extract both tables and text from a PDF.
The PDF file I’m working with contains multiple tables along with accompanying text. The text often provides additional context for the tables, with some references pointing to content on subsequent pages. Because of this, I need to process the entire PDF as a cohesive document.
Here’s where the challenge arises: Camelot does a great job extracting tables, but it only provides limited metadata—specifically, the page number and bounding box (bbox) coordinates that specify the table’s location on each page. Unfortunately, this isn’t sufficient for text extraction, as Camelot doesn’t handle non-tabular content. Other libraries, like pdfplumber and PyMuPDF, do offer text extraction along with associated metadata, but they use different scaling and coordinate systems for bounding boxes. This results in mismatches, making it difficult to align text and tables accurately across libraries.
Do you have any suggestions or ideas on how I could extract text from the PDF, ideally while continuing to use Camelot as the primary tool? Any advice would be greatly appreciated.
Thank you!
According to what I had researched, in programming a client is an entity that requests a service from another entity. For example, when we use our PC to enter reddit we are a client that communicates with the Reddit server.
But in the guide to the web-scrapping sub-reddit there is something called httpx and requests, which apparently are clients of python. But I don't understand.
What is httpx? And how can it be a client if supposedly when entering a page the client is us?
Hi i am currently learning python. I messed up my coding test recently for a data science internship. Any Suggestions preparing for them? Any websites i can practice? Really want one get an internship for summer.
I have a multiple linear regression model predicting Y for X1 and X2. I’ve got a script that runs without error, but no surface is drawn; where am I going wrong?
fig = plt.figure(figsize=(12, 9)) ax = fig.add_subplot(projection='3d') ax.scatter(df.eval(X1), df.eval(X2), df.eval(Y), color='blue') X_Plot = np.asanyarray(train[[X1]]) Y_Plot = np.asanyarray(train[[X2]]) Z_Plot = train_y_ ax.plot_surface(X_Plot, Y_Plot, Z_Plot, cmap=cm.coolwarm) #Doesn't work ax.set_xlabel(f'{X1_Mask}') ax.set_ylabel(f'{X2_Mask}') ax.set_zlabel(f'{Y_Mask}') plt.show()
To get proficient in Python for data science and machine learning within six months, a structured plan with clear weekly goals and portfolio projects is essential. Here’s a detailed breakdown with step-by-step study areas, resources, and project ideas:
requests
library.Absolute beginner here, currently trying to understand virtual environments. I am using Arch linux and whenever I try to install a python library using pip install it says that the environment is externally managed and I should use pacman -S. So my question is if arch already has a environment ready and a way to install libraries in it then why should I use pip and why should I create another venv in the first place.
Hi all, i'm doing analysis on large pcap file. For dev purposes, I would like to add a field to each packet, allowing me to do other operation a lot easier (it would be less efficient to refer to a map with a packet ID and the field)
I see the scapy.packet does have a comment method, but I couldn't find much element on that. I want my pcap field to be "rewritten" with a specific meta field, is that something achievable ? Perhaps it's more of a network capture related question than python but as I use python to manipulate these, and that scapy seems pretty powerful, I wanted to know if I should search deeper or surrender and use that external map
thank you very much !
I try to run the following code on a Mac-Computer:
import asyncio
from shazamio import Shazam
import os, sys
import pprint
path = os.path.abspath(os.path.dirname(sys.argv[0]))
fn = os.path.join(path, "Tinashe Ft. Tyga - Nasty XXX - (A.D. Twerk Edit Dirty-).mp3")
async def main():
shazam = Shazam()
out = await shazam.recognize(fn) # rust version, use this!
pprint.pprint(out)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
on one computer it works fine without any problems but on the other Mac-Computer i get this error:
Traceback (most recent call last):
File "aiohttp/connector.py", line 1098, in _wrap_create_connection
File "asyncio/base_events.py", line 1081, in create_connection
File "asyncio/base_events.py", line 1111, in _create_connection_transport
File "asyncio/sslproto.py", line 528, in data_received
File "asyncio/sslproto.py", line 188, in feed_ssldata
File "ssl.py", line 944, in do_handshake
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1122)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "checkMusic.py", line 101, in <module>
File "asyncio/base_events.py", line 642, in run_until_complete
File "checkMusic.py", line 28, in main
File "shazamio/api.py", line 584, in recognize
File "shazamio/api.py", line 597, in send_recognize_request_v2
File "shazamio/client.py", line 57, in request
File "aiohttp_retry/client.py", line 158, in __aenter__
File "aiohttp_retry/client.py", line 119, in _do_request
File "aiohttp/client.py", line 663, in _request
File "aiohttp/connector.py", line 563, in connect
File "aiohttp/connector.py", line 1032, in _create_connection
File "aiohttp/connector.py", line 1366, in _create_direct_connection
File "aiohttp/connector.py", line 1335, in _create_direct_connection
File "aiohttp/connector.py", line 1100, in _wrap_create_connection
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host amp.shazam.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1122)')]
[PYI-1342:ERROR] Failed to execute script 'checkMusic' due to unhandled exception!
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.
Deleting expired sessions...none found.
Is there any workaround regarding this CERT-Error so i can get the script running on any Mac-computer?
If I am trying to fetch a Django model from my psql db using a property that doesn't exist, I want my IDE to warn me about it before I deploy it to my server.
I've been trying to pip install intuit-oath package that is clearly in PyPi but get not found errors for linux and windows. Intuit is notoriously not responsive to developers so I have to ask elsewhere. Is there any way to debug this like finding out why it can't find a version for my systems.
Hi I don't want to go into to much detail unless someone knows the answer, but am running into an issue need to get this project done. When I am trying to run the game it says the ship image is "not in working directory", but it is in fact in the directory already. When I run the game the screen is black as well as the window crashes. Anyone every done this? It's a popular project in "Python Crash Course" when learning python. Been search the web for a solution.
I am trying to install PyQt5 in the raspberry pi 5 terminal using pip install PyQt5. I got a couple of warnings: certificate verify failed and an ERROR: could not find a version that satisfies the requirement PyQt5(from versions: none) and ERROR: No matching distribution found for PyQt5.
Learned that the PyQt5 isn't supported on python versions after 3.9. Should I roll back to prev version of python?
So basically I tried multiple times this year to start my coding journey and always I started with python only but as soon as 1 week ends I stop enjoying it. Once again, I started doing it last week and today I am getting lazy to back to it. Can someone give me advice on this.
I just learned python for 1 month, and I need help. My teacher give me a web, and one of its task says that make a program that can count the numbers of lowercase letters when insert.
This is my code:
a = input()
b = 0
for i in a:
if i.islower():
b += 1
print(b)
But it says that this is the wrong answer, it does work though
Correct answer:
a = int(input())
words = ["a", "b",... ] -->lowercase alphabet
for i in range(a):
n = 0
lst = list(input())
for j in lst:
if j in words:
n += 1
print(n)
Sorry the second one I just copy from a correct answer, I don't even know if it's correct or not. What I want to ask is my code correct? Anyone got another way to code this? Thanks
I am struggling to create a dataclass from inventory data stored in a SQL database. retrieving the data and instantiating the class doesn't appear to be a problem. As I can see each instance thru a print statement in a for loop while instantiating the objects. My problem is I can't retrieve the info outside of the for loop used to create the objects.
This is a relevant snippet of the code I am using:
from dataclasses import dataclass
import os
#class Product(id,picture,sku,cost,oldsku,direct,notes,location,description,catalog,box,ratio,kind,images,catagory,pattern,video,current):
u/dataclass
class Product:
name:str
id:int
picture:str
sku:str
cost:str
oldsku:str
dir:str
notes:str
location:str
description:str
catalog:str
box:int
ratio:int
kind:str
images:str
catagory:str
pattern:str
video:str
current:int
data1=DB_open()
# Iterate through the data and write it onto the image
for row in data1:
newItem=('A'+row[2]) # sku
newItem = Product(newItem,row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8],row[9],row[10],row[11],row[12],row[13],row[14],row[15],row[16],row[17])
print(eval(str(newItem)))
print(eval(str(A1001))) # one of the objects created above A1001
I am New to Programming World.
Hi , I'm a college student taking a Python course "Modern Applications Development".
I don't feel my professor's slides and labs are enough to understand his exams. I did pretty bad on the midterm and have a project+final coming up.
So in my 1 week of fall break I want to learn these following topics:
Are there any well known online courses containing these topics?
I would like it to be free but paid is not off the table if it's worth it.
Any help would be appreciated, Thanks.
I'm learning Python from Replit, but I find it really hard to write code without seeing a solution first. Why is that? I'm not sure if it's just hard for me or for many people. I want to become an expert in Python as soon as possible because it’s in high demand for jobs, but coming from a commerce background, I find it especially difficult to understand programming concepts and I'm 29 years old.
I'm from a commerce background, which is why it's so difficult for me to understand Python or What.
I'm building a small tool in QT that uses a format string based on the standard format specifiers used by the QDateTime::toString()
function.
yyyy
- 4-digit yearMM
- 2-digit monthdd
- 2-digit dayhh
- 2-digit hour (24-hour format)mm
- 2-digit minutess
- 2-digit secondThe date format I'm using is: yyyy-MM-dd
I want to use Pillow within the tool and I can get the datetime like this:
datetime = datetime.strptime(date_time, "%Y:%m:%d %H:%M:%S")
I can then convert it to the same date format like this:
datetime = dt.strftime("%Y-%m-%d")
The issue is that I need to be able to convert between the dates dynamically, either by converting the QT date to DateTime or vice versa. The user is able to set their preferred date format so this bit of the code is unknown "%Y-%m-%d"
For example, instead of yyyy-MM-dd
the user might set the overall date format to yy-MM-dd
which would mean that I would need to use date_obj.strftime("%y-%m-%d")
but how would I actually know the format code to use seeing as the user can enter a range of different time formats?
Hope this makes sense.
What is the best premium school for python. I have seen pros and cons for most of them but which one gives you the best bang for buck. And will make sure I don't have any gaps.
Some I am considering Real python Udemy Programiz W3schools Codeacademy
Or any others you would recommend
Hi, I’m currently working on a web app for a group project that uses Firebase with JavaScript to retrieve and display recipes. My group tasked me with adding authentication in python to our almost complete codebase (utilizing python is a project req.). Currently the app has features like displaying, rating and querying recipes using firebase. I previously tried implementing authentication with Django and managed to get the authentication working smoothly, but I ran into issues getting firebase to connect and work properly. I spent a lot of time debugging to no avail.
Could anyone suggest a simple way to implement a login system using Python, which will work smoothly with our current Firebase/JavaScript setup? Thanks.
I'm an experienced programmer trying to learn Python. Please help me understand scope. If I understand what I've read properly, a variable defined at the top has global scope. So here is the code that has me scratching my head:
1 x = 5
2 def outer():
3 print (x)
4 #x=x+1
5 print("Value of x in the beginning is " + str(x))
6 outer()
7 print("Value of x after the function call is " + str(x))
This prints the value of x properly all 3 times (from lines 3, 5 and 7). If I uncomment line 4, it fails with an error (UnboundLocalError). I have a coupl questions now.
a) Since x is declared before any function definitions, shouldn't it scope be global, and hence should be usable anywhere?
b) If x is not global, how come the print command in line 3 works fine with line 4 commented out?
c) If the value of x is known in line 3, why does line 4 throw an error when it is uncommented?
Thanks in advance.