/r/learnpython

Photograph via snooOG

Subreddit for posting questions and asking for general advice about all topics related to learning python.


Rules

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.


Learning resources

Wiki and FAQ: /r/learnpython/w/index


Discord

Join the Python Discord chat

/r/learnpython

861,476 Subscribers

1

OpenCV to stimulate a damp fingerprint image

I’m working on an image processing project using OpenCV, (I'm very new to image processing). From my understanding, fingerprint sensors work by capturing an image of a finger, processing it, and comparing it against a stored reference image. If the images match above a certain threshold (say, 90%), the fingerprint is accepted, else rejected.

If the user's finger is slightly damp, the sensor may not function as accurately due to distortions in the image. My goal is to detect when a fingerprint is slightly damp and adjust the matching threshold—lowering it to around 70%—to improve recognition accuracy even with minor moisture on the finger.

The problem is I don't have a fingerprint sensor with me. I did find a fingerprint dataset on kaggle but it dosnt have "damp fingerprints". I want to simulate the appearance of a slightly damp fingerprint in OpenCV to test this concept.

Is it feasible ? Any ideas on how ? Any suggestions would be helpful.

Thank you :)

0 Comments
2024/11/01
16:12 UTC

5

Do you guys often use stack overflow?

Title. I asked because I want to know if it is worth looking into when it comes to learning python

6 Comments
2024/11/01
15:49 UTC

2

Python isn't uninstalling

I'm trying to reinstall Python but it won't let me. Whenever I run the installer and select Uninstall it shows me that is was successfully uninstalled, but it wasn't.

Any ideas on this?

Info: Windows 11

7 Comments
2024/11/01
15:10 UTC

3

What is the best way to learn Python "independently"?

Hi, kind of thought of other way around learning python.I kind of follow up with book called "Python crash course" it was really great experience,makes me have head ache on some coding task done came from book.I also watch coding streams,some vids and a few tutorials/guides.Where they other best way to learn Python?I just like to speed things up abit more while mentaning my proficiency on learning it as possible, as I plan to learn other languages as well.Thank you all in advance!!

5 Comments
2024/11/01
15:00 UTC

2

Interview Question

Hello I was solving an interview question. The question was that a matrix is given to us and we have to cut it from a point to create 4 rectangle sub matrixes from it. Each matrix has to have at least one non-negative value. After that all non negative values are added in each matrix to find their individual summation. The question is finding the cutting point that would give us the minimum difference between max and min summations. If there are multiple candidates, the point with the lowest row is selected. If still multiple, point with lowest column is selected. It is guaranteed that such point exists.

This is the answer I came up with. I believe it gives the correct answer but I was wondering if it was a very inefficient answer as it has 4 for loops and if there was a way to improve the code.

def divide_matrix(matrix):
    results = {} # creating a dictionary for the cutting points
    for i in range(len(matrix)-1):
        for j in range(len(matrix[i])-1):
            s1, s2, s3, s4 = 0, 0, 0, 0 # each sub matrix summation. initialized 0 for each cutting point
            s1_count, s2_count, s3_count, s4_count = 0, 0, 0, 0 # count of how many members each sub matrix has
            for k in range(len(matrix)):
               for l in range(len(matrix[k])):
                   if matrix[k][l] >= 0: # to make sure that only non negative ones are accounted for
                       if k <= i:
                           if l <= j:
                                s1 += matrix[k][l]
                                s1_count += 1
                           elif l > j:
                                s2 += matrix[k][l]
                                s2_count += 1
                       elif k > i:
                           if l <= j:
                                s3 += matrix[k][l]
                                s3_count += 1
                           elif l > j:
                                s4 += matrix[k][l]
                                s4_count += 1
            if s1_count > 0 and s2_count > 0 and s3_count > 0 and s4_count > 0: # to check if all matrixes have non negative values
                res = max(s1, s2, s3, s4) - min(s1, s2, s3, s4) 
                results[(i, j)] = res # adding to the dictionary 
    min_key = None
    min_value = float('inf')
    # to check for the minimum result
    for key, value in results.items():
        if value < min_value:
            min_value = value
            min_key = key
    return min_key

Thank you to everyone who took their time to answer it.

1 Comment
2024/11/01
13:34 UTC

2

Any free site for practicing python problems?

A newbie in python and I'm currently doing it in codewars (It's great)and looking for some other sites for more practice

1 Comment
2024/11/01
12:49 UTC

1

what would be a better way to write this code?

if i want to add more planets and simulate gravity between them too. should i use class if yes then how exactly?

import pygame 
import math
from pygame.time import Clock

# Scaling facrot

Scaling_factor= 9**20
scaling_factor_vel=0.001
# Initialize Pygame
pygame.init()

# Set up the display
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Solar System Simulator")

# Velocity
(vel_x,vel_y)=(30000,0)
(acc_x,acc_y)=0,0

# Positions
(sun_x,sun_y )=(400,300)
(planet1_x,planet1_y)=(400,200)


# Masses
mass_sun =2*10**30
mass_planet=2*10**24

# Colors
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)

# Clock
clock = Clock()

#functions
#position
def change_position(x, y):
    a = x[0] + y[0]
    b = x[1] + y[1]
    return (a, b)

# Velocity
def change_velocity(x,y):
    a = x[0] + y[0]
    b = x[1] + y[1]
    return (a, b)


# Force
def force(dist,angle,m_sun,m_planet):
    angle_radians = math.radians(angle)
    
    fx = (((m_sun * m_planet) / dist**2) * math.sin(angle_radians))/Scaling_factor
    fy = (((m_sun * m_planet) / dist**2) * math.cos(angle_radians))/Scaling_factor
    return (fx, fy)

#distance

def distance(x,y):
   
    d=(math.sqrt((x[0]-y[0])**2+(x[1]-y[1])**2))
    return d

# Angle
def angle(x,y):
   dx = y[0] - x[0]
   dy = y[1] - x[1]
   return math.degrees(math.atan2(dx,dy))



# Main game loop
running = True
while running:
    clock.tick(10)
    # Handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Fill the screen with black
    screen.fill(BLACK)

    # Draw a blue circle representing a planet
    pygame.draw.circle(screen, BLUE, (sun_x, sun_y), 20)
    pygame.draw.circle(screen, BLUE, (planet1_x, planet1_y), 20)


    dist=distance((planet1_x,planet1_y),(sun_x,sun_y ))
    ang = angle((planet1_x,planet1_y),(sun_x,sun_y ))
    (f_x,f_y)=force(dist,ang,mass_sun,mass_planet)
    acc_x, acc_y = f_x / mass_planet, f_y / mass_planet
    (vel_x,vel_y)=change_velocity((vel_x,vel_y),(acc_x*scaling_factor_vel,acc_y*scaling_factor_vel))
    (planet1_x, planet1_y)=change_position((planet1_x,planet1_y),(vel_x*scaling_factor_vel,vel_y*scaling_factor_vel))

    (acc_x,acc_y)=(0,0)
    
    # Update the display
    pygame.display.flip()

# Quit the game
pygame.quit()
5 Comments
2024/11/01
12:09 UTC

0

Why does it says "syntax error" when I input print(\t"variable")

Python 3.11.4 (main, Sep 30 2023, 10:54:38) [GCC 11.4.0] on linux Type "help", "copyright", "credits" or "license" for more information.

print(\t"python")

File "<stdin>", line 1 print(\t"python") ^ SyntaxError: unexpected character after line continuation character

It was said that it could deal with the Python version or with the app itself already.I'm using pyroid 3 and Acode ok mobile.

4 Comments
2024/11/01
11:24 UTC

1

Why does get() work inside of a function and not outside of a function?

So, I am learning Tkinter and currently on Entry Widget. This is a sample code I am doing now to learning.

from tkinter import *

root = Tk()

e = Entry(root, borderwidth=5)
e.pack()
ok = e.get()

def name():
    label = Label(root, text=ok)
    label.pack()


button = Button(root, text='CLICK ME!', command=name)
button.pack()

root.mainloop()

Why doesn't the function name() take in ok = e.get() for any entry I place? I asked ChatGPT and its just confusing me even more. I can't wrap my head around the event loop. I mean, mainloop() loops Entry and Button Widget but not ok=e.get(). It always prints "". Please help me understand this.

4 Comments
2024/11/01
10:47 UTC

0

ChatGPT added code that I would like to remove

Hi all!

I recently watched Grant Sanderson's Manim demonstration with Ben Sparks (https://youtu.be/rbu7Zu5X1zI?si=pimx3uIMAWqHM2CZ) and it got me motivated to give Manim a try. However, I don't have any experience coding (except for Stata and RStudio). Installing Manim cost me the better part of three days, but I have finally succesfully made two animations through guides and ChatGPT. I am running the code in VSCode. ChatGPT added the last block of code below, but I've see no one else use something like this? Could anyone explain in layman's terms what it is, and how to remove it (while still being able to run the script)?

from manim import *

class First_scene(Scene):
    def construct(self):
        t = Text("Hello... Again?")
        self.play(Write(t))
        self.wait(2)

class Second_scene(Scene):
    def construct(self):
        t = Text("IT WORKED")
        self.play(Write(t))
        self.wait(8)

# ChatGPT comment: This block allows running the script directly and renders both scenes
# This is also the block that I want to remove
if __name__ == "__main__":
    scene1 = First_scene()
    scene2 = Second_scene()
    scene1.render()
    scene2.render()
21 Comments
2024/11/01
10:30 UTC

3

Data processing for dashboard-webapp.

Hi all!

I am currently moving with a project for a custom self hosted webapp/dashboard for ~ 1000 users.
The app will be based on python & dash-plotly. I've done similar things couple of times, but this time I'd like to focus on the efficiency & speed of the data retrieval.

The part i am currently looking at will be a specific interactive data table with ~10-12 different measures (metrics for all users will be the same, data will be changing). What should be the go-to approach for an underlying data table in the database?

Is storing all the metrics/measures in two columns "Measures" & "Metrics" and then preparing the right data using polars the right approach? (Currently the table has ~ 16M rows, overall 25 different metrics and 25 overall columns). Or should i move all the metrics to the separate columns?

Thank you all for any insights & help.

0 Comments
2024/11/01
10:09 UTC

18

What really was that "f" before the first parentheses for?

Here is the ex:

full_name=f"{first_name} {last_name} print(full_name)

Idk I'm just worrying if I need to change it when I will use different variables

38 Comments
2024/11/01
06:54 UTC

2

How to prepare for ICPC?

Hi guys. I am a sophomore student at AASTU and I am really looking forward to compete for the next round ETCPC(which will be my first time) and I am really struggling for a way to prepare for the contest. I just finished CS50 course on python and getting into reading a book and I just heard about ETCPC. And I saw recent years problems and I couldn't even figure out what kind of problems they are. So now I am trying to figure out what kind of questions are asked, what kind of books should I read and what free site should I enroll for problems and learning?(if there is any thing that I don't know to mention, please give me a suggestion.)

0 Comments
2024/11/01
06:18 UTC

1

PymuPDF licensing requirements when its a dependency of another dependency?

I am exploring various tools and libraries for data extraction from documents like PDFs. One tool I've looked into is img2table, which has been effective at extracting tables and works as a wrapper around different OCR tools. However, I noticed that PyMuPDF is a requirement for img2table, and I’ve read that if you build with PyMuPDF, you must make your source code open-source in line with its AGPL license. Does this requirement still apply if I use a project where PyMuPDF is a dependency, even if I don’t directly interact with the library myself?

6 Comments
2024/11/01
06:17 UTC

0

I copied this code from the internet because I needed a vanilla solution to find the mode of a list of values. Can anyone walk me through how exactly it works?

nums = [1, 2, 2, 4, 5]
mode = max(set(nums), key=nums.count)
16 Comments
2024/11/01
05:10 UTC

0

How do I get pyGames on windows 11 and have it work with Spyder?

I was doing some drawing on Python using Spyder, and I don't have pygames on this computer. I had the same code, but when I ran it, it said "ModuleNotFoundError: No module named 'pygame'" and there was a box saying "important" + "It seems you're trying to use a module that doesn't come with our installer. Check this FAQ in our docs to learn how to do this." How do i get pygames and continue drawing? I searched up where to download it and found this website "Downloads" which looks like it was from the prehistoric times. It even has Macintosh download! It also looked a bit shady, and i have windows 11 and don't know which one to get. Thanks!

5 Comments
2024/11/01
03:10 UTC

0

How do I format this code so that the numbers appear in 0.00 versus appearing in 0.0, also i know this is not a subreddit for homework but i genuinely don't know to format this.

import math 

starting = float(input("what is the starting amount ",))
down_payment2 = float(0.1)
down_payment = starting * down_payment2
balance = starting - down_payment
anual_interest = float(0.12)
principle = float(0.05)
payment = starting*principle
montly_payment = anual_interest / 12
month = 1

while balance > 0:
    interest_to_pay = balance * montly_payment
    principle_to_pay = payment - interest_to_pay
    ending_balance = balance - payment
    round(interest_to_pay, 2)
    round(principle_to_pay,  3)
    interest_to_pay = round(interest_to_pay, 2)
    principle_to_pay = round(principle_to_pay,  3)
    print("Month  Starting Balance  Interest to Pay  Principal to Pay  Payment  Ending Balance")
    print(" ",month,"         ",balance,"           ",interest_to_pay,"             ",principle_to_pay,"        ",payment,"        ",ending_balance,)
    month += 1
    balance -= payment
15 Comments
2024/11/01
00:56 UTC

3

I used to make gTTS work..whats up?

I have some sample code. Need to execute some text:

from gtts import gTTS
import os
import playsound

def speak(text):
    tts = gTTS(text=text, lang='en')

    filename = "abc.mp3"
    tts.save(filename)
    playsound.playsound(filename)
    os.remove(filename)

    speak(filename)


The command line in pycharm returns nothing! 
1 Comment
2024/11/01
00:21 UTC

0

Importing named range from excel

Hello!

Is there a way to easily import a defined excel named range into a python script?

I'm generally an R user who is working in python for a work project, and there are some things in python that seem really clunky compared to R. For example, named range imports. In R you can use read_xlsx from the openxlsx2 package and use the NamedRegion variable to import data easily from excel.

However in python, it doesn't seem like pandas or openpyxl has anything out of the box? And instead people have been making their own functions to import the data into a script, sometimes by getting the range of a table and iterating through each and every cell to get the data out of the spreadsheet.

Am I missing something obvious somewhere?

8 Comments
2024/10/31
23:37 UTC

2

Scheduler for tasks

I'm currently building a scheduler in Python for setting notifications for tasks and reminders for them, so that I can pace myself and do monthly or weekly tasks. It is different from a typical TODO app because one can set a periodic reminder for the tasks. I did try to find if such an application did exist before but I could not find it. Is there such a program already made? At least one for Windows, I did find Getting Things Gnome, but that is only for Linux and I don’t have the time to learn a new operating system when I have a master thesis to do.

10 Comments
2024/10/31
23:21 UTC

3

Datetime strip and replace to a different timezone

Hi everyone,

I have some code that I use to take a date and time from a line of text and compare it against the current time to see if it is within 90 minutes but the line of text is always in UTC and my Raspberry Pi is in AEST+10

An example of the text is

YARM 312100Z AUTO 08010KT 9999 // NCD 14/10 Q1015 RMK<br>RF00.0/000.0

The 312100Z part is the date 31st and time 2100 UTC

My current code is this

match = re.search(r'(?P<UTC>\d{6})(?:Z)', metar_info)
if match:
    ztime = match.group('UTC')
    ztime_object = datetime.strptime(ztime, '%d%H%M')
    ztime_object = ztime_object.replace(year=ztime_object.now().year,month=ztime_object.now().month)
    Z_limit = datetime.utcnow() - timedelta(minutes=90)
    if ztime_object < Z_limit:
        visibility = 12345678
        ceiling = 12345678

Every month on the 1st it will replace the day to be the current timezone AEST+10 which is the 1st but UTC should still be the 31st so the 90 minute comparison fails when it should work.

Is there a way to have it compare UTC to UTC without changing the timezone of the Pi?

25 Comments
2024/10/31
23:10 UTC

0

Why is the wrong variable updating?

Hi!

Sorry, I am pretty new to python but have coded in Matlab before. I am encountering the following problem where variables are updating when I am not expecting them to, e.g. if I run:

array = [1, 2, 3, 4]

new_array = array

new_array[1] = array[1] + 2

print(array)

The output is [1, 4, 3, 4] - I can't understand why 'array' updates?

Thanks!

6 Comments
2024/10/31
22:44 UTC

11

Actually learning python

Hey everyone, I’m just a guy trying to learn python. I have been doing beginner projects and trying to learn the basics.

My mate is a carpenter, and pretty much everyone I know and live around is (live a bit rural - so programming and coding is a bit weird here). Anyway to the point, I’m learning about modules and I have this way of thinking about it like they are all different toolsets that you can bring to a project. Like a carpenter has his tools he works with, same as an electrician, mechanic, etc. And I just thought that was a cool visualisation - anyone else see it like that?

So I wanted to make this post just to get some people that know coding or are learning, and maybe we could chat about it, and help each other - it will help me stay accountable to try and show off new things or help out people, or try to at least.

Anyways, let me know 👍 peace

6 Comments
2024/10/31
22:38 UTC

34

Will I ever learn this language

I have been studying and practicing python for about a year now. And I still have a hard time making it stick. I almost feel like everyday I'm starting all over again with concepts. Does anyone else feel this way and what are some tricks to make it stick better.

67 Comments
2024/10/31
22:21 UTC

6

Struggling to understand this line of code.

def squared(string, number):
    i = 0
    row = ""
    while i < number * number:
        if i > 0 and i % number == 0:
            print(row)
            row = ""
        else:
            row = string[i%len(string)]
        i += 1
    print(row)  

Hi guys, I was struggling with this piece of code. I understand the first half but the row = string[i%len(string)] I can't wrap my head around how this works. Thx

10 Comments
2024/10/31
20:40 UTC

1

Excel Cell Value formatted String Comparison

Exactly as the title says. I’ve been trying for a while now to create a way to compare strike through formatting. For example if Cell A1 in Book 1 has text like “The hat” and Book 2 has text “The hat” but in book 2 “hat” would have strike through text. How would I compare this

3 Comments
2024/10/31
20:02 UTC

2

How do I know if a pip package installed is necessary?

I have some packages in some old code and I don't remember installing them. Some are on my Pythonanywhere server and not on my own machine, so maybe they were already there? But some I might have installed myself at some point to try out and forgotten to uninstall.

I'd like to clean up my requirements.txt and have the same packages locally and remotely if possible. But is there a way to find out if they're being used? Will they necessarily appear in the code if they're necessary or can they do something "beneath" that I didn't make it do? Like if they're neccesary for other packages and were automatically installed or somehow necessary on the server because of the OS it's using...or something?

7 Comments
2024/10/31
19:33 UTC

11

New to learning Python, how's my code? Rock, Paper, Scissors challenge.

So I'm learning from a Udemy course with Angela Yu, 100 days of python.

She gave us a challenge and I did it before I checked out her solution.
Her solution was different from mine, which is fine. Everyone has a different solution to a problem.

My question is, do you think my way of going about this Rock, Paper, Scissors game is okay? Did I make it more complicated then needed? AKA does my coding method look ok?

import random
rock = '''
    _______
---'   ____)
      (_____)
      (_____)
      (____)
---.__(___)
Rock
'''
paper = '''
    _______
---'   ____)____
          ______)
          _______)
         _______)
---.__________)
Paper
'''
scissors = '''
    _______
---'   ____)____
          ______)
       __________)
      (____)
---.__(___)
Scissors
'''
computerChoice = random.randint(0,3)
if computerChoice == 0:
    computerChoice = rock
elif computerChoice == 1:
    computerChoice = paper
else:
    computerChoice = scissors

userChoice = input("Pick Rock [0], Paper [1], or Scissors [2]: \n")

if userChoice == "0":
    userChoice = rock
elif userChoice == "1":
    userChoice = paper
elif userChoice == "2":
    userChoice = scissors
else:
    userChoice = "BIG DUMMY MOVE"
print("Your Choice:" + userChoice + "\n\nComputer Choice: " + str(computerChoice))

if userChoice == "BIG DUMMY MOVE":
    print("You didnt choose a valid input. \nYou lose, asshole.")
else:
    if computerChoice == userChoice:
        print("Draw")
    else:
        if userChoice == rock and computerChoice == scissors or userChoice == paper and computerChoice == rock or userChoice == scissors and computerChoice == paper:
            print("You Win")
        else:
            print("Computer Wins")
37 Comments
2024/10/31
19:15 UTC

1

hello! i need to scrape a lot of text from a site!

i need to scrape a very big amount of text (html) from a resource (mayocliniclabs.org, it has a /test_catalog which includes thousands of pages about biomarkers that i need to have in text format) and every time i do that using requests, selenium, undetected_chromedriver etc. i cant scrape data. When i do a simple request, it returns 403 and when i am simulating a full browser environement its very slow and the data is not full and does not even contain the text on the page. What could you recommend?
my english is not perfect as well as python. thank you.

7 Comments
2024/10/31
18:53 UTC

0

Where to begin?

I'm looking for starter courses or a bootcamp for python if anyone knows any good ones. Preferably free but doesn't have to be free.

3 Comments
2024/10/31
17:32 UTC

Back To Top