r/learnpython • • 6d ago

Ask Anything Monday - Weekly Thread

2 Upvotes

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 • • 4h ago

How do you escape tutorial hell and actually become good at Python?

7 Upvotes

Learning Python syntax is one thing, but solving a problem from scratch feels completely different.

What small projects or daily exercises would you recommend to develop real programming skills without constantly following tutorials?


r/learnpython • • 8h ago

is there any interactive apps or games that can help me learn the basics of python

10 Upvotes

im looking for apps like Duolingo but for python or interactive games that can get me to learn the basics of python


r/learnpython • • 9h ago

Looking for a more comprehensive guide on Classes and Objects

8 Upvotes

Hello, I'm a programmer who already knows several other languages and I'm looking to relearn Python recently (I learned and used it briefly several years ago). I was going through The Python Tutorial on the official python documentation site but it seems like the chapter on Class is way too brief and doesn't even touch on topics I knew were quite useful, like super(), \@property, and those amazing dunder/magic methods. Does anyone have recommendations on a more comprehensive guide to Python Classes, Objects, and Inheritance? I know there are books like Fluent Python but those are too heavy for me as a review of the language, I don't need to look under the hood that much, just explanations and practical uses of useful features.


r/learnpython • • 2h ago

Can you render sprites on your desktop?

0 Upvotes

What I mean is not rendering pngs in a window, but on your desktop with the app shortcuts (Not literally changing the shortcut icons).


r/learnpython • • 2h ago

How did you escape tutorial hell with Python for data analysis?

0 Upvotes

I understand Python fundamentals and have some experience with Pandas, NumPy and Matplotlib.

However, there's a big difference between following a tutorial and independently completing a real-world project.

What helped you make that transition?

I'm researching practical learning resources and would particularly like to understand what existing courses or projects are missing.


r/learnpython • • 6h ago

Asking advice to learn python from scratch.

1 Upvotes

Hey i am ayush and i am from india and i am 20 yrs old and i am thinking of learning python from scratch . so right now i am using a book called 'Python Crash Course, 3rd Edition' by Eric Matthes . so i am confused that should i continue from this book or should i watch some videos from you tube . plzzzzzz helpp.


r/learnpython • • 14h ago

Help with pre-commit or alternatives to not require a dev to manually do a step before it works

0 Upvotes

As a primarily Python and Django developer for the last 1.5 decades (but also all the other things... Ruby, RoR, Go, JS, Typecript, CoffeeScript, whatever) I latched onto pre-commit several years ago as an easy way for devs to "just do the right thing" in terms of linting and formatting and easy to skip stuff because "it doesn't matter as long as thing work" or "I didn't mess something that simple up".

But with proper tooling which just does stuff correctly for you, those arguments go away.

My problem with pre-commit, which is Python based and so the Python community latched onto, has been that every dev still has to manually type "pre-commit install". It is insane how many times I have had to have my first comment on a code review be "Did you run pre-commit install?" even for commits from devs who have been working on a project for months (are they deleting and doing a new clone every few weeks? I have no idea.)

At my current employer, as of around 1 year ago, I found that they were using Lefthook on both JS/TS and Java projects. The most interesting part was that it "just worked". I did not need to run a manual command for it to do its thing, unlike with pre-commit.

I have tried to use it for a Python project, using uv for package management, and it does not "just run". I suspect using uv as the environment is the problem because of needing to use uv run lefthook, etc. There is a good chance it would work in some of my other environments where they run in a container and so the path points at the virtualenv bin.

Is there a way to make this "just work", whether with lefthook or pre-commit, where a dev does not need to initially run a command which they may not do?


r/learnpython • • 14h ago

Fixing my skipped list

0 Upvotes

So I just posted a post and had to delete because I realized I fucked up and didn’t upload any code with it. I have a project in Python that I have to make. Mine is going to be a text adventure game and it keeps skipping the enmy list. It also just reloops regardless of if the user dies or not.
Here is the section of the code:

for i in range(len(loc)):
        current_loc=loc[i]
        current_dsrp=dsrp[i]
        current_nos=nos[i]
        current_enmy=enmy[i]
        print("\nYou find yourself in,:" + current_loc + ".")
        print(current_dsrp)
        print(current_nos)


        choice = input("\nDo you want to investigate? (Yes or No): ").lower()
        while choice != "yes" and choice != "no":
                print("You cower away and die of fear!")
                
        else:
            choice == "yes"
            printItem(current_enmy)
            conChoice = input("\nDo you wish to continue? (Yes or No): ").lower()
                    
            while conChoice != "yes" and conChoice != "no":
                         print("You curl in a ball and cry.")
                     
            if conChoice == "no":
                 conChoice == "no"
                 print("You have died from dehydration and fear!")
            else:
                print("You have escaped the killer!")


main()for i in range(len(loc)):
        current_loc=loc[i]
        current_dsrp=dsrp[i]
        current_nos=nos[i]
        current_enmy=enmy[i]
        print("\nYou find yourself in,:" + current_loc + ".")
        print(current_dsrp)
        print(current_nos)


        choice = input("\nDo you want to investigate? (Yes or No): ").lower()
        while choice != "yes" and choice != "no":
                print("You cower away and die of fear!")
                
        else:
            choice == "yes"
            printItem(current_enmy)
            conChoice = input("\nDo you wish to continue? (Yes or No): ").lower()
                    
            while conChoice != "yes" and conChoice != "no":
                         print("You curl in a ball and cry.")
                     
            if conChoice == "no":
                 conChoice == "no"
                 print("You have died from dehydration and fear!")
            else:
                print("You have escaped the killer!")


main()

r/learnpython • • 1d ago

My first complete comand in Python, from my first day on:

31 Upvotes

Look:

import random
import time

def drawn(a, b):
    return random.randint(a, b)
answer = 'yes'

while answer == 'yes':
    a = int(input('Min number: '))
    b = int(input('Max number: '))
    print(f'Drawn: {drawn(a, b)}')

    time.sleep(2)

    answer = input('Try again? ').lower()

This creates a random number generator where you can choose the minimum and maximum numbers!


r/learnpython • • 17h ago

How was everyone else's learning experience with Python?

1 Upvotes

I'm up to learning returns and looping dictionaries and my brain goes into over drive while learning new concepts and variables. and I just end up over heating, leading to procrastinating. Anyone else have any similar issues when learning?


r/learnpython • • 18h ago

Giveaway comment picker in Python

0 Upvotes

at first I assumed I had to scrape comment threads directly or fight OAuth setup just to pull entries from a giveaway post. Both ended up wasting time before I even wrote a real script.

I am still fairly green with Python, mostly comfortable with basic loops, lists, and requests, so I wanted something straightforward. Usinghikerapi.com, a REST API with an x-access-key header and pay as you go pricing starting around $0.001 per request (with 100 free requests to test), I got a working response on the first real run.

python

import requests
headers = {"x-access-key": "YOUR_KEY"}
r = requests.get("https://api.hikerapi.com/v2/user/by/username?username=apple", headers=headers)
print(r.json())
  • import requests loads the HTTP client library so Python can send web requests.

  • headers = {"x-access-key": "YOUR_KEY"} stores the authentication header the API checks for your key.

  • r = requests.get("[https://api.hikerapi.com/v2/user/by/username?username=apple](https://api.hikerapi.com/v2/user/by/username?username=apple)", headers=headers) sends a GET request with the query parameter and auth header, returning a response object r.

  • print(r.json()) parses the JSON body into a Python dictionary or list and prints it to the terminal.

what tripped me up once I moved from a test profile call toward comment fetching was pagination and identifier formats. Comment endpoints return data in pages or chunks with cursors rather than dumping every single comment at once, and mixing up shortcodes, media IDs, and comment fields can easily cause empty pulls or KeyError crashes when filtering entries or deduplicating usernames.

for anyone who has built a comment raffle or giveaway script in Python, how do you structure cursor pagination loops and handle duplicate or spammy comments cleanly?Giveaway comment picker in Python

at first I assumed I had to scrape comment threads directly or fight OAuth setup just to pull entries from a giveaway post. Both ended up wasting time before I even wrote a real script.

I am still fairly green with Python, mostly comfortable with basic loops, lists, and requests, so I wanted something straightforward. Using hikerapi.com, a REST API with an x-access-key header and pay as you go pricing starting around $0.001 per request (with 100 free requests to test), I got a working response on the first real run.

python
import requests
headers = {"x-access-key": "YOUR_KEY"}
r = requests.get("https://api.hikerapi.com/v2/user/by/username?username=apple", headers=headers)
print(r.json())

import requests loads the HTTP client library so Python can send web requests.

headers = {"x-access-key": "YOUR_KEY"} stores the authentication header the API checks for your key.

r = requests.get("[https://api.hikerapi.com/v2/user/by/username?username=apple](https://api.hikerapi.com/v2/user/by/username?username=apple)", headers=headers) sends a GET request with the query parameter and auth header, returning a response object r.

print(r.json()) parses the JSON body into a Python dictionary or list and prints it to the terminal.

What tripped me up once I moved from a test profile call toward comment fetching was pagination and identifier formats. Comment endpoints return data in pages or chunks with cursors rather than dumping every single comment at once, and mixing up shortcodes, media IDs, and comment fields can easily cause empty pulls or KeyError crashes when filtering entries or deduplicating usernames.

For anyone who has built a comment raffle or giveaway script in Python, how do you structure cursor pagination loops and handle duplicate or spammy comments cleanly?


r/learnpython • • 1d ago

Is it just me or freecode camp "12 Beginner Python Projects - Coding Course" feels advance from early

6 Upvotes

I am learning python and I decided to do some basic projects. Till rock hangman it was fine. I loved it, was easy to learn and wrote another code of it bymyself adn added some cool stuff.

But I am now learning tic tac toe and it just feel advance. Like I have learned about classes, loop but the way it is used in the video feels like a level above beginners.

Am I overthinking? Any suggestion and other beginner project that I should do


r/learnpython • • 1d ago

Is it normal in an interview for an interviewer to ask very niche questions?

80 Upvotes

I recently had an interview for an intern position. my resume had some good Python projects and my previous internship experience also involved Python.

The interviewer began by asking me basic Python questions, which I answered well. He then moved on to more detailed questions.

Interviewer: What would be the output of the following code?


num1 = 1

num2 = 1

num3 = 257

num4 = 257

print(num1 is num2, num3 is num4)

I know about integer caching in python, so I said True, False. The interviewer asked if I was sure, and I said yes. He then handed me his laptop, opened VS Code, and asked me to run the code. To my horror, it printed True, True.

He moved on to the next question.

Interviewer: What is __init__ in Python?

Me: It’s a constructor for a class.

Interviewer: What is the first argument it takes?

Me: The object we created.

Interviewer: If it’s the constructor, how can it take the object itself? Who creates the object if __init__ is the constructor?

Me : Silence.

I know it's kinda my fault for this question.

Moved on to the next question

Interviewer: What is the output of the following code?


def fun(a=[], i=1):

    a.append(i)

    print(a)

fun()

fun(i=2)

I didn’t know that Python reuses the same list when it’s used as a default argument, so I got it wrong.

He moved on to the next question.

Interviewer: What is the output of this code?


tup = ([1, 2, 3], 4, 5)

try:

    tup[0] += [4, 5]

    print('tup modified', tup)

except:

    print('Not modified', tup)

Apparently it raises an error on the third line, but the list still gets modified. The output is:


Not modified ([1, 2, 3, 4, 5], 4, 5)

I haven’t heard back yet, but I’m wondering: is this how python specific interviews typically go?

How should I prepare for these kinds of scenarios next time?


r/learnpython • • 20h ago

How to make your website live on the internet for all?

0 Upvotes

I can write HTML, CSS, JavaScript, Python, but how do I actually make a website go live? I know how to host locally at 127.0.01.
I created an account at PyhtonAnywhere.com, I bought a domain name through GoDaddy.com.
My site is JoshuaVoss.net

I don't know what to do.

How did you make your website work in the internet?


r/learnpython • • 1d ago

I'm confused by the escape loop

1 Upvotes

Hi, I've just got to the escape loop part of my learning, I have wrote my code following the books directions. Here it is:

sensor_readings = [ 3, 5, 4, -1, 6, 7]
total = 0
for sensor_reading in sensor_readings:
    if sensor_reading < 0:
        break
    total = total + sensor_reading
print("total is: " + str(total))

Now as far as I understand, this code adds the digits up until the negative, which in this case is 12. Why does the total have to be 0? And why does it actually add the digits? Also if I change the total or the less than to anything else it returns 0, or 18 usually. I get the break part, but I don't understand the code leading up to it. I posted a while ago about another section, and I was informed that the directions in the book were incorrect. Is it a case of that here? Thanks


r/learnpython • • 2d ago

The python library "Beautiful Soup", from where did it gets that name from?

43 Upvotes

√|


r/learnpython • • 1d ago

Final project

1 Upvotes

Hi, so i have a final project in uni so im first year student and we take python on semester 1 and the prof made us choose whatever it just need to be in python only and each oneh as 5 functions

so me and my team picked lost and found system which we didnt know anything about it
so its includes a report a lost item part and report a found item part and search and match part and the file handling

i swear this stuff is harder than it seemed we dont take in uni how to make a project its like they threw us in the sea and told us learn to swim
and now i feel so overwhelmed there is alot of stuff that idek how to do
starting from how do we even start to how to work together and how does the program should look like

so i asked ai to give me a sample of what my part should look like which is the file handling and the search and match it gave some complicated stuff that i cant even understand and the project should be done in 4 weeks maybe less

so i wanted to ask how do i do the project without ai and actually understand what the actuall fuck is going on.


r/learnpython • • 1d ago

Sentence transformer model - what has worked for you in JIRA

1 Upvotes

Hi Red fam. I work in PMO and was looking at change management tickets logged in JIRA. Idea was to group tickets and take it up with LT for process interventions.

For context, my org is flexible in terms of who gets to raise JIRA tickets - be it Product, Architecture, Engineering, Delivery or Project Managers themselves (way of working fail). One objective was to find any correlation between groupings and job roles.

I used BERTopic for topic creation and mpnet for clustering. While am happy with the MVP - I had to brute force some business overrides/nuances as the model misgrouped quite a few tickets.

I tried changing dimensionality and clustering variables but the model didn’t help much beyond a point. Am looking for suggestions to train the model on existing data and automatically group new tickets that come in into the queue - can anyone please help me with an approach?


r/learnpython • • 1d ago

Python Dice Roller Help

4 Upvotes

Hello, I was making a sort of dice roller function that could be called to make a range of random numbers. However, I get an error and cant understand really what is wrong.

My Code to do this is:

import random


def diceroll(high, low, times):
    
    for _ in range(int(times)):
        random.randint(int(high), int(low)) 
    return high, low, times


high = input("enter a high number: ")
low  = input("enter a low number: ")
times = input("how many times would you want this to run? ")
drresult = diceroll(high=int(high), low=int(low), times=int(times))
print(drresult)import random


def diceroll(high, low, times):
    
    for _ in range(int(times)):
        random.randint(int(high), int(low)) 
    return high, low, times


high = input("enter a high number: ")
low  = input("enter a low number: ")
times = input("how many times would you want this to run? ")
drresult = diceroll(high=int(high), low=int(low), times=int(times))
print(drresult)

And the Error:

File "D:\PYTHONPROJECTS\EXERCISESANDTESTS\TEST0001\TESTAPP-0001.py", line 12, in <module>
    drresult = diceroll(high=int(high), low=int(low), times=int(times))
  File "D:\PYTHONPROJECTS\EXERCISESANDTESTS\TEST0001\TESTAPP-0001.py", line 6, in diceroll
    random.randint(int(high), int(low)) 
  File "C:\Users\-\AppData\Local\Programs\Python\Python310\lib\random.py", line 370, in randint
    return self.randrange(a, b+1)
  File "C:\Users\-\AppData\Local\Programs\Python\Python310\lib\random.py", line 353, in randrange
    raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (20, 2, -18)

Any help would be appreciated!

EDIT: I figured out my problem and fixed it, making the code set up different! Ill edit the post to have my fix posted once I am able to!


r/learnpython • • 1d ago

Help a beginner out with tuple unpacking :D

1 Upvotes

Yes I know its rather beginner, but since starting my python class I've been breezing through and its been so fun to learn, and I began to wonder why so many pythonists and other high level language users say its so hard.

Then I met tuple unpacking. I don't know what it is or why but its so hard for me to grasp and do. Here's an example problem I struggled with:

Q: analyze daily revenue based on the meals customers purchase

menu = {

"Burger": 12.50,

"Pizza": 15.00,

"Pasta": 13.50,

"Salad": 9.00,

"Sandwich": 8.50,

"Fries": 4.00

}

orders = [

("Monday", "Burger", 2), ---- These are Day, Product, Quantity btw

("Monday", "Pizza", 1),

("Tuesday", "Pasta", 3),

("Wednesday", "Burger", 1),

("Wednesday", "Fries", 4),

("Thursday", "Pizza", 2),

("Friday", "Sandwich", 2),

("Saturday", "Pasta", 2),

("Sunday", "Salad", 3)

]

Basically I'm supposed to get the price from the dictionary, and add to orders to get the daily revenue, such as like

Monday: 40.00
Tuesday: 40.5

and etc

But I keep messing up, I just can't seem to grasp the concept despite how much I have GPT give me more problems, the closest I got was this. One recurring issue I have is making sure a day doesn't repeat, like having Multiple Mondays when it should just be one monday and the final revenue for that day:

def calculate(sales):

daily_sales = {}

for day, product, quantity in orders:

price = menu[product]

daily_sales[day] = daily_sales.get(day, 0) + (price * quantity)

return(daily_sales)

print(orders)


r/learnpython • • 2d ago

Is there any way to play audio in Python without using external libraries or winsound?

12 Upvotes

I wanted to play audio in Python, so I started looking for modules that were already installed, it means ones that wouldn't require an internet connection to install (for example Pygame)

I found winsound but the problem is that it will only play audio on Windows and no in other OS

It seemed more convenient not to have to install external libraries to test Python capabilities within the existing environment (such as using Tkinter instead of game engines)

Unfortunately many audio libraries and modules were removed in 3.13 (i'm using 3.14)


r/learnpython • • 2d ago

How come randomly placed drawing don't go to the side of my canva?

4 Upvotes

Long story short, my assignement is to create a "forest". I already created many functions to draw the trees and a window with a button that allows the user to choose how many trees will be drawn in it. My biggest problem is that I'll have points deducted if the randomly placed trees touch the border. I thought just making sure that my trees coordinates where withing the range that would make them not touch the canva but fr some reason they are always a bit to much to the side and I don't know what to do, because everything I try makes them "escape" the canva. I tried to create a "formula" that'll subtract the width and height of the trees to the x and y coordinates to make sure they don't touch the border but with no success. I thank you guys for any help or advice you might be able to bring!

Here's the relevant code:

from random import*
from turtle import*
from tkinter import*
from math import*

#Screen
screen = Screen()
screen.setup(900,600)
colormode(255)
screen.bgcolor(0, 46, 122)
screen.tracer(0)
hideturtle()
master= screen.getcanvas().master 

#Functions needed to make the tree
def triangle(x,y,cote):
    penup()
    goto(x,y)
    pendown()
    begin_fill()
    colormode(255)
    color(25, 87, 5)
    for i in range(3):
        forward(cote)
        left(120)
    end_fill()
    penup()
    
def tronc(cote2):
    colormode(255)
    color(66, 33, 1)
    begin_fill()
    for i in range(2):
        forward(cote2)
        right(90)
        forward(cote2*1.5)
        right(90)
    end_fill()
    penup()
    

def sapin():
    cote= randint(10,100)
    cote_tronc= cote*0.3
#What might be the problem
    x=randint(-abs(425-cote),425-cote)#The abs() is there to make sure it stays within
    y=randint(-abs(225-ceil(cote*1.1)),225-ceil(cote*1.1))
#The coordinates are purposefully in a range smaller than the canva in an attempt
#to have them not "escape" it.
    x2 = x+cote*0.375
    penup()
    goto(x2,y)
    tronc(cote_tronc)
    deplacementX= cote*0.085
    deplacementY= cote*0.3
    for i in range(3):
        triangle(x,y,cote)
        x += deplacementX
        y += deplacementY
        cote *= 0.8

def foret(n):
    for i in range(n):
        sapin()

foret(200)

master.update()
exitonclick()

master.mainloop()

r/learnpython • • 2d ago

Looking for a developer to run my bot on my servers hourly is 10/ usd

0 Upvotes

Looking for a developer to run my bot on my servers hourly is 10/ usd