r/learnpython • • 1d ago

Ask Anything Monday - Weekly Thread

1 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 • • 8h ago

Tuples..I don’t get it

42 Upvotes

Hi crew, I’m a Python newbie and I just learned about the concept of tuples.

We can’t change them.if we want to store we have to start at the index we want + 1.

I just don’t get it. Why wouldn’t we just use lists? When would we ever need this?


r/learnpython • • 4h ago

I've learned Python fundamentals - how do I actually get really good at Python?

9 Upvotes

I've spent time immersing myself in Python fundamentals, including syntax, data types, loops, functions, data structures, and working in the development environment. I want to move beyond the basics and develop a much deeper technical understanding of the language.

I'm starting to look into libraries like NumPy and pandas, but I'm wondering what else I should focus on to become proficient at Python.

For those of you who are experienced developers, what would you recommend learning next? Should I focus on libraries, data structures and algorithms, writing more complex projects, understanding how Python works under the hood, software engineering practices, or something else entirely?

I'm not necessarily looking for another beginner course. I want to get to the point where I can write effective, well-structured code, understand what's happening behind the scenes, and tackle increasingly complex technical problems.

Thanks!


r/learnpython • • 2h ago

Is this normal?

4 Upvotes

I’m currently teaching myself Python by solving exercises on my own. My personal rule so far has been to give myself 15 minutes to solve a problem; if I’m still completely blank after that, I ask an AI for a hint. The issue is that AI hints usually just hand over the solution, so I’m not even sure if my approach is right.

The main problem is that I’m on Part 5 of the University of Helsinki Python MOOC, and for the last five exercises or so, I just freeze up. It’s starting to get really frustrating. I try asking myself guiding questions and writing down my thought process in a notepad before writing any code. Most of the time I have a rough idea of what I want to do, but translating that logic into actual syntax trips me up.

I’m starting to wonder if I’m actually cut out for this or if I’ll ever be able to learn it properly. Is this normal?


r/learnpython • • 5h ago

Values won't add to my string, just overwrites it

6 Upvotes

Hi I'm really new to python, I originally started coding using p5.js but made the transition recently, I'm currently trying to covert an old project of mine into python so I can run it in touch designer.

Its an ASL fingerspelling activity that I've been working on but I'm struggling to create the word strings I did in my original prototype. Instead of the letters being added together and creating a word I can use to trigger effects, the previous letter is just replaced with the current one.

For context I have the guesser and getMostFrequent to allow for it to take the average of every letter signed during a period of time and determine which one was signed the most to add to the word (this is due to the fact that transitioning from one letter to the next can trigger other letters in between) These are both integral parts of the code and are working as intended, its just the stringing the word together that I'm struggling with.

Any help or insight would be appreciated, if you need any more insight please let me know and I can add it.

Code in Pastebin: https://pastebin.com/91mPYwC8

I've provided a link to a google doc with my code because it is just easier formatting wise than in here.
My code: Python Code

My original code for reference if needed: p5.js code


r/learnpython • • 2h ago

Python beginners collaborating on github

1 Upvotes

Hi all, I am starting to use python at work for data analysis and I feel like I am kind of at a standstill in learning. I was wondering if there were any groups collaborating on beginner projects on GitHub so I can learn more python, GitHub ecosystem, and how to code within a team because there isn't much collaborating in coding at work. If there are two people assigned on a project at work, we're usually sharing our screens while one types and we discuss together.


r/learnpython • • 7h ago

enumarting issue for images and masks

2 Upvotes

Hi!
Preface I am self taught and learning as I go.

I have been working on a U-Net semantic segmentation model, which was working fine yesterday and gave good(ish) outputs on unprocessed data and now no longer wants to read the files correctly?

I spent the day processing some new masks in fiji and changed the path of the mask variable and when I went to run my code and sanity checks, for both my images and masks, the first chunk of tif files I created a missing/ not read, when they are in file. (I even checked with fiji if it was an order of files but that was fine)

I'm a bit stumped because it was working fine yesterday, as all I have changed is the original file paths.

from simple_unet_model import simple_unet_model

from keras.utils import normalize

import os

import cv2

from PIL import Image

import numpy as np

from matplotlib import pyplot as plt

image_directory = r'E:\Uni\Dissertation\IB\test output\images\IB unprocessed/'

mask_directory = r'E:\Uni\Dissertation\IB\test output\masks\IB_BC_24_117_G4_thresh mask/'

SIZE = 256

image_dataset = []

mask_dataset = []

images = os.listdir(image_directory)

for i, image_name in enumerate(images): #Remember enumerate method adds a counter and returns the enumerate object

if (image_name.split('.')[1] == 'tif'):

#print(image_directory+image_name)

image = cv2.imread(image_directory+image_name, 0)

image = Image.fromarray(image)

image = image.resize((SIZE, SIZE))

image_dataset.append(np.array(image))

masks = os.listdir(mask_directory)

for i, image_name in enumerate(masks):

if (image_name.split('.')[1] == 'tif'):

image = cv2.imread(mask_directory+image_name, 0)

image = Image.fromarray(image)

image = image.resize((SIZE, SIZE))

mask_dataset.append(np.array(image))

And when I run a sanity check, I end up getting a mismatch between my image and ground truth/mask

In the table of elements, the correct number of elements is listed, however, 0 should be linked to mask_0_00.tiff (the same for the image data), but jumps to mask_0_00.tiff

I even changed the path back to the unprocessed masks for the data set and encountered the same problem...

Any ideas? Thank you :,)


r/learnpython • • 20h ago

looking for a web scraping api that handles the browser part so im not babysitting headless chrome

11 Upvotes

keep a few python jobs pulling pricing and review pages for the weekly growth deck. requests + bs4 was fine until half the targets went full client-render and started blocking anything that isnt chrome

moved them onto local playwright and now half my mornings are restarting dead sessions and chasing proxy bans. ridiculous ops load for a scrape job

anyone found a web scraping api path where the browser part is just handled and the scripts stay boring​


r/learnpython • • 10h ago

newbie here -- how to find a color on the screen and more?

1 Upvotes

i want to find a color on the screen and click it. so its not complex please separate concepts and examples, but i also want to find a random occurence of acolor and click on that, i havent tried figuring out clicking on something yet so im not really looking for that rn

im barely pythoning and docs are kinda difficult to read, im able to get the screenshot of a screen via pillow, output it to a screen via .show() and i also got some getcolors output but its kinda confusing and doesnt seem useful?


r/learnpython • • 13h ago

PROJECT HELP

1 Upvotes

​

Hi, I'm new here. So I've been learning Python and I wanna advance to Django web frame work. I've watched slot of tutorials and I feel maybe it's stagnating me and I need to do something more. I've had a few projects I've worked on, but whenever I try to join in on open source projects I get confused. Almost as if I've never learner python before.

I need help on ways to grow your python knowledge and connect with the community to make it easier to get even beginner level project jobs when I'm ready.

Oh and also, suggestions on a few things to get acquainted with after knowing Python basics and OOP. Thanks.


r/learnpython • • 20h ago

Append one value from a list to one list in a list of lists

3 Upvotes

Hi :)

I've just started a python course and I'm stuck on a problem that I feel should be easy, but I'm missing something. I need to append a value from a list to a list at the same index in a list of lists, but I'm not getting the result I need. Any help to let me know what I'm doing wrong would be greatly appreciated!

b = [5, 6, 7, 9, 13, 12, 17]
new_list = len(b) * [[0]]

for ind_b, num_b in enumerate(b):
    new_list[ind_b].append(num_b)

print(new_list)

My goal is to get

[[0, 5], [0, 6], [0, 7], [0, 9], [0, 13], [0, 12], [0, 17]]

but instead I get

[[0, 5, 6, 7, 9, 13, 12, 17], [0, 5, 6, 7, 9, 13, 12, 17], [0, 5, 6, 7, 9, 13, 12, 17], [0, 5, 6, 7, 9, 13, 12, 17], [0, 5, 6, 7, 9, 13, 12, 17], [0, 5, 6, 7, 9, 13, 12, 17], [0, 5, 6, 7, 9, 13, 12, 17]]


r/learnpython • • 1d ago

Is learning Python from books worth it for a beginner?

37 Upvotes

Hey everyone!

I'm currently learning Python through YouTube videos, and I'm wondering if I should also start learning from a Python programming book.

For those of you who have learned Python:

Do books help you understand Python concepts more deeply?

Would learning from a book alongside YouTube tutorials help me build a stronger foundation?

Which beginner-friendly Python book would you recommend?

I want to build a solid understanding of Python and become better at solving problems on my own.

I'd love to hear your experiences and suggestions. Thanks!


r/learnpython • • 17h ago

Nested dictionary comprehensions

1 Upvotes

I have an assignment in which I have to create a nested dictionary using employee data. I've created a function that works, but the function is supposed to just have a return statement with the dictionary comprehension, and I'm struggling to convert it.

This what I currently have (each department must only appear as an outer key once and employee names in each department should be unique, with the latest salary overwriting previous entries if duplicates exist):

def organize_employee_data(employees):
    new_dic = {}
    for name, department, salary in employees:
        new_dic[department] = {}
    for name, department, salary in employees:
        if name not in new_dic[department]:
            new_dic[department].update({name: salary})
        else:
            new_dic[department][name] = salary
    return(new_dic)

With the following list as input:

employees = [
    ('Alice', 'Engineering', 70000),
    ('Bob', 'HR', 50000),
    ('Charlie', 'Engineering', 80000),
    ('David', 'Sales', 45000),
    ('Eve', 'HR', 51000),
    ('Alice', 'Engineering', 80000),
    ('David', 'HR', 52000)
]

This is returned:

{'Engineering': {'Alice': 80000, 'Charlie': 80000}, 'HR': {'Bob': 50000, 'Eve': 51000, 'David': 52000}, 'Sales': {'David': 45000}}

I've been trying to create a working function using just the nested dictionary for the better part of two hours and I'm about to lose my mind. I have to assume the foundation is something like this:

return {department: {name: salary} for name, department, salary in employees} 

but whenever I try to add any conditions, the whole thing gets messed up. Any help would be amazing!


r/learnpython • • 18h ago

Title: Looking for advice and occasional guidance on a Python embedding service for a fintech project

0 Upvotes

Hi everyone!

I'm currently working on a team project called Fintech Trendwatcher. The goal is to collect public fintech news, identify important events and generate short analytical summaries with links to the original sources.

I'm responsible for the embedding service. My task is to use a pretrained text embedding model to convert news articles into vectors that another service will use for clustering similar publications.

My current stack is Python, and I'm learning as I go. I have some experience with Python, APIs, JSON and Git, but this is my first time working with embeddings in a real team project.

I'm planning to start with Sentence Transformers and a pretrained multilingual model, test it on Russian fintech news, and then integrate it into our service architecture.

I'd really appreciate advice from more experienced developers, especially on:

- Choosing a suitable embedding model for Russian-language fintech news.

- Designing a simple and maintainable embedding service.

- Comparing embeddings and preparing them for clustering.

- Common mistakes beginners make when building NLP services.

I'm not expecting anyone to mentor me full-time. Even occasional advice, feedback on my approach, or pointers to useful resources would be incredibly helpful.

If anyone has experience with Python, NLP, Sentence Transformers or similar projects and is willing to share some advice, I'd be very grateful.

Thanks!


r/learnpython • • 19h ago

Python tutorial: Understanding algorithmic complexity with practical examples

0 Upvotes

I recently put together a Python crash course on algorithmic complexity, focusing on how to reason about the efficiency of algorithms rather than just memorizing Big O notation.

The tutorial covers time and space complexity, Big O, Big Omega, and Big Theta, along with practical examples in Python, including linear search, binary search, matrix multiplication, and recursive Fibonacci.

The goal is to build intuition for how algorithms scale as the input grows, with examples that are useful for anyone learning algorithms or preparing for coding interviews.

The video is available here:
https://youtu.be/6c9Qjnto6E4

I'd appreciate any constructive feedback on the explanations or examples!


r/learnpython • • 19h ago

Freelance start

0 Upvotes

Anyone have any suggestions to start freelancing with python? I have my bachelors in software engineering and work full time as a data analyst. I have python, sql, and tableau experience. Any suggestions on where and how to start will be appreciated
Thank you


r/learnpython • • 23h ago

i know python basics but i need to learn more, where should i learn it from

3 Upvotes

Suggest me some good resources i could learn python from. now if there is any language that teaches from basics to advanced level that would also be fine, since i could just skip the beginners part


r/learnpython • • 1d ago

Is there a way to use Python in desktop app design?

1 Upvotes

I want to design desktop apps with Python. Is there anyway for me to translate my python knowledge into a functional desktop application?


r/learnpython • • 1d ago

I want to learn Python together with my 15 yo son in a fun way. What are your ideas?

2 Upvotes

I work as a web developer, but I don't really know Python.

And I'd like to teach my son to start programming in a more advanced way, and Python seems easy and fun (unlike C#).

(my son already knows the basics of programming, such as if's and while's)

What fun project do you recommend? I think it would be amazing to try something that involves physical objects. Maybe build a mini self-driving car that recognizes street signs.

Or maybe a drone that does a choreography in the air?

I want this to be a project that we can work on each weekend for at least a few months.

I'm aware that we might have to get an arduino and other things.

Sure, we'll start by just printing "hello world", but I want to get into the fun stuff as soon as possible.

I read that coding helps develops a teen's brain, even if there might not be much of future in programming careers (thanks to AI).


r/learnpython • • 1d ago

When should I avoid list comprehensions in Python?

20 Upvotes

Hi, I'm trying to get a grip on list comprehensions, but I'm not sure when they aren't the best choice. I wrote some code today that uses a nested comprehension to flatten a list of lists, but it quickly became unreadable. I think I might have overcomplicated it. Is there a rule of thumb for using them, particularly with nested structures? I want my code to stay clear and easy to understand. Any insights on best practices would be appreciated!


r/learnpython • • 1d ago

How do you safely handle untrusted input when building Python tools?

3 Upvotes

When building Python security tools, how do you safely handle untrusted input to prevent path traversal, command injection, and insecure deserialization? What common mistakes should developers watch out for?


r/learnpython • • 1d ago

getting started with python in VS CODE

0 Upvotes

So I have a MacBook Pro with the recent update of OS sequoia 15.8.1 . I started a college class of intro to programming with python and my teacher wants us to have python downloaded and visual studio code. Except my Mac probably is not supported with it because of the 🚫 icon displaying right before I drag it into applications .i wonder why I search up on YouTube all these videos on how they install it but mine can’t.:(


r/learnpython • • 1d ago

how is my cs50 code in design?

2 Upvotes

I've decided to go back to basics and make sure I complete all the exercises. I'm currently working on the Meal Time exercise.

Could anyone give me some feedback on the design of my code? I'm particularly unsure about my convert function. It has quite a few if statements, and I'm wondering whether there's a clearer way to write it.

Here's my code:

```python def main(): time = input("what is the time?\n") convertedTime = convert(time) print(tellMealTime(convertedTime))

def convert(time): if time.endswith(" a.m"): hour, minute = time.replace(" a.m", "").split(":") if hour == "12": hour = "0" elif time.endswith(" p.m"): hour, minute = time.replace(" p.m", "").split(":") if hour != "12": hour = int(hour) + 12 else: hour, minute = time.split(":") return float(hour) + float(minute) / 60

def tellMealTime(time): if time >= 7.00 and time <= 8.00: return "breakfast time" elif time >= 12.00 and time <= 13.00: return "lunch time" elif time >= 18.00 and time <= 19.00: return "dinner time" else: return "not a meal time"

if name == "main": main() `


r/learnpython • • 1d ago

Looking to create a game similar to clangen, dont really know where to begin

0 Upvotes

Hello,

A friend of mine is looking to make a game like it but with their own original species, and I offered to try to code it because I have some (extremely limited) experience with python. However, it's been a long time since I have worked Python, I am not a regular coder, and I do not really know where to begin. Does anybody have any tips or know anything about how Clangen is structured that could help me figure out where to even begin? I have never made a game in python before and am happy to start where you think I should considering my limited experience, but I am a learn by doing person.

Thanks!


r/learnpython • • 1d ago

Any advice for my coding?

0 Upvotes

Right now i have this

I want to know anybody give me advice for my coding how can i improve it without same mistakes next time.

import random
import os
def Retry():
print('do you want try again?')
choice = input("Y/N   > ").lower()
match choice:
case 'y':
return True
case 'n':
return False
case _:
print("Enter Y or N")
return Retry()
playing = True
while playing:
secret = random.randint(1,20)
attempts = 5
won = False
while attempts > 0:
os.system('cls')
print("Attempts left:", attempts)
try:
guess = int(input("Enter your guess: "))
except ValueError:
print("Enter a valid number")
input("Press Enter to continue...")
continue
if guess == secret:
print("You won")
won = True
break
elif guess > secret:
print("Too High")
attempts -= 1
else:
print("Too low")
attempts -= 1
if not won:
print("you run out attempts")
print("the number was:", secret)
playing = Retry()
if playing:
print("Starting new game")
else:
print("Goodbye")
import random
import os
def Retry():
print('do you want try again?')
choice = input("Y/N   > ").lower()
match choice:
case 'y':
return True
case 'n':
return False
case _:
print("Enter Y or N")
return Retry()
playing = True
while playing:
secret = random.randint(1,20)
attempts = 5
won = False
while attempts > 0:
os.system('cls')
print("Attempts left:", attempts)
try:
guess = int(input("Enter your guess: "))
except ValueError:
print("Enter a valid number")
input("Press Enter to continue...")
continue
if guess == secret:
print("You won")
won = True
break
elif guess > secret:
print("Too High")
attempts -= 1
else:
print("Too low")
attempts -= 1
if not won:
print("you run out attempts")
print("the number was:", secret)
playing = Retry()
if playing:
print("Starting new game")
else:
print("Goodbye")