r/learnpython • • 4d 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

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

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

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

23 Upvotes

√|


r/learnpython • • 40m 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 • • 48m ago

Python Dice Roller Help

1 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\Ryan Axtell\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!


r/learnpython • • 7h 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


r/learnpython • • 1d ago

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

11 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 • • 1d ago

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

3 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 • • 1d ago

Relearning coding, no gen AI?

7 Upvotes

Note: I am not here to debate generative AI ethics.

I haven’t coded in a while and can’t think of a project to work on, so I was hoping for a course I could take to refresh my knowledge that would not delve into generative ai. Any suggestions? I’d really like to find something that just doesn’t talk about it at all, as I’m sick of having to set up a cognitive filter to ignore it myself.

I’m aware I could find a book written before ~2022 but I thrive under a “class learning” structure and like learning on the go.


r/learnpython • • 21h ago

any tips for learning python as a first coding language when you don't know anything about coding

0 Upvotes

i know literally nothing about coding but i wanna start, how and where? (preferably not costing money) and is python the best option to learn first? i am pretty much unsure of anything about coding at all


r/learnpython • • 23h ago

Is coddy a good place to start if I'm looking forward to build a career from scratch?

0 Upvotes

I really want to get into the programming world despite the fact that I've studied else back at school,my Ultimate goal is to get hired as a programmer from here to the next year,I heard they give you a certificate upon completing the course,is it worth anything?


r/learnpython • • 1d ago

pythagoras tree

2 Upvotes

I made code for one "branch" of the Pythagoras tree, and I have no idea how to make the full tree. Can someone help? My code:

from turtle import*
x=100
while True:
    for i in range (4):
        fd(x)
        rt(90)
    rt(90)
    fd(x)
    lt(45)
    xNaDwa= x*x/2
    y= xNaDwa**0.5
    x=y

r/learnpython • • 1d ago

How to solve python problems?

0 Upvotes

This may be a dumb questions, but I do not get how to write code. For some context, I am taking a scientific computing course in my uni, I am a physics major, so most of the coding we do pertains to some kinda physics/math related problem. I know how to do the math on its own but I don't get how to translate it into code. When I see a problem I don't even know how to start it.
For example:

Write a function my_cubic_spline_flat(x, y, X), where x and y are arrays containing experimental data points, and X is an array. Assume that x and X are in ascending order and have unique elements. The output argument, Y, should be an array, the same size as X, where Y[i] is the cubic spline interpolation of X[i]. However, instead of the constraints we introduced before, 𝑆′1(𝑥_1)=0 and 𝑆′𝑛−1(𝑥_𝑛)=0.

When I see that, I do not know what to do. Like I know how to write functions and stuff, but not the actual code that goes inside the function.

Any advice is appreciated! :)


r/learnpython • • 1d ago

How do you keep a small open-source package maintained over time?

7 Upvotes

I recently published my first package on PyPI. It works and has tests and CI, but I've never maintained anything long term. For those of you with packages people actually use:

  • How to determine which features should be in a patch and which in a small release. And when to upgrade to 1.0?

  • How to ensure that your dependencies and GitHub actions are up-to-date without it becoming tedious. For example, is Dependabot or Renovate (or another tool) used?

  • Should dependencies be version locked or not?

  • How much time do you allocate to this? And how do you manage it if you are particularly busy?

All good practice and common errors are really appreciated!


r/learnpython • • 2d ago

6 weeks into learning python and a friend keeps telling me to switch to go for backend

8 Upvotes

6 weeks in, about an hour most nights. function, loops, dicts, just started classes. i want to end up doing backend work and was about to pay for a structured python course but a friend who writes go at work keeps saying python is a detour and i should switch now before i get too deep. i don't want to restart every time someone has an opinion but i also don't want to burn months on the wrong things. so do i stay or switch??


r/learnpython • • 1d ago

Append key and value list to another value list of a different dict...

1 Upvotes

I have a problem that I need to solve, and I've been working on this for too long to care about doing it another way.

I have a dict with keys that I need to split into different sections. For example: I need keys 1-3, 4-6, 7-9 to go into section 1, 2, 3 etc, which have their own keys in another dictionary (Code below)

sectioned = {'1': {}, '2': {}, '3': {}}
unsectioned = {'key1': [value1, value2, value3], 'key2': [value1, value2, value3], 'key3': [value1, value2, value3], 'key4': [value1, value2, value3], 'key5': [value1, value2, value3], 'key6': [value1, value2, value3], 'key7': [value1, value2, value3], 'key8': [value1, value2, value3], 'key9': [value1, value2, value3]}

I want to move these to make:

sectioned = {'1': {'key1': [value1, value2, value3], 'key2': [value1, value2, value3], 'key3': [value1, value2, value3]}, '2': {'key4': [value1, value2, value3], 'key5': [value1, value2, value3], 'key6': [value1, value2, value3]}, '3': {'key7': [value1, value2, value3], 'key8': [value1, value2, value3], 'key9': [value1, value2, value3]}}

How would I do this? I've tried a few things using 'for' statements, but I can't get it quite right...


r/learnpython • • 2d ago

Hot write "Not A, unless B" in Boolean Algebra?

3 Upvotes

I have a rather complex row selection mission at hand.

To select the rows I want, I have to use two lists of keywords. One contains words that I want (kw_Y), and the other contains words I don't want (kw_N). I originally used this simply to collect the rows that have the wanted information, but now I need to do some comparison analysis with rest of the data.

I need to select rows "that don't have the kw_Y terms, unless they have kw_N terms". Or as Google put it: "No A unless B" (meaning A is false except when B is true) translates to ¬A unless B, or ¬A ∨ B (logically equivalent to B → A, "if B then A").

Boolean logic has never been my strongest point. What would this be in Python?

Codes:

good_stuff = dataframe[kw_Y & ~kw_N] #Yes these masks, not just lists. Algebra is the focus.

bad_stuff = dataframe[kw_N & ~kw_Y] #didn't select enough rows

bad_stuff2 = dataframe[~kw_Y] #I realized this removes rows that contain stuff I now want. 

all_bad_stuff = dataframe[???]

r/learnpython • • 1d ago

Does anyone play high level sudoku?

0 Upvotes

Hi,

I'm trying to make a very advanced sudoku player in python.

However, it generates sudokus far too slowly. Can someone help me? (I'll only share source code once someone says yes)

EDIT: found solution, deleting in a week


r/learnpython • • 3d ago

Learning Python at 37 and I can read code fine but can't write 10 lines without the lesson open

259 Upvotes

37, learning Python in the evenings for about 3 months. I can read other people's code and follow every lesson, but the moment I close the lesson and try to write something small on my own, like a script to rename my photos, I'm stuck after a few lines. I did a free intro course before this and hit the same wall, so this time I'm paying for something structured. What made writing code on your own start to click?


r/learnpython • • 2d ago

What exactly i've should learn to automation and script building?

1 Upvotes

Hey guys, my english is very bad but i think you can understand!

I have a good knowledge in java development and linux fundamentals, but lately i have searching ways to be more efficient in my personal projects, and python always appears in very different cases.

To be more specifically, i love build my own programs and create some terminal apps.

So, how can i learn python without watching insane playlists with 40 minutes / video, just using previous knowledge!


r/learnpython • • 2d ago

one parse function per store in my scraper, normal?

10 Upvotes

every grocery store my deals script checks has its own parse function. one keeps specials in a table, one in cards, one only fills in after the js runs so that one needs playwright. main picks one with an if/elif on the url

it works.. until a store redesigns and its function quietly returns an empty list for a week

how do you keep new stores from being near copies​


r/learnpython • • 2d ago

How to not clobber a class when inheriting

0 Upvotes

I wrote a visitor to extract some datas via the ast

class VariableFinder(ast.NodeTransformer):
    """ Visitor pattern impl."""
    def __init__(self, find_object:str, find_method:str):
        """ 
        filter for only method calls that match find_object.find_method 
        store the line number and store the value or args passed to the call
        """
        self.find_method = find_method
        self.find_object = find_object
        self.found = []
...

And it struck me this is not C++, so how do we stop ourselves accidentally blatting/clobbering over ast.NoteTransformer attributes? I'm missing something and my searches are all indicating that the visitor pattern is frowned upon. Is there an alternative way to do these safely?


r/learnpython • • 2d ago

For learning Python

0 Upvotes

I have been learning Python for over a year now. I have already finished Eric Matthes's book, "Python Crash Course." Are there any other books similar to "Python Crash Course"—specifically ones that focus on project-based learning, like the three projects featured at the end of that book? In other words, what other books are there that allow you to learn by building projects?

(N.B. This is not a promotional post)


r/learnpython • • 3d ago

Basically, if main

9 Upvotes

In Python, when you run your program in another folder, we add this, but I don't understand why. What's the point of doing this? If someone could explain it in a simplified way, I'd appreciate it.