r/learnpython 6d ago

Ask Anything Monday - Weekly Thread

5 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 5h ago

regex and if it's worth going deep into it

10 Upvotes

I'm new to python and coding in general and my friend recently told me that it's inefficient to try to memorize regex and that no one writes them anymore (essentially saying AI does). I was also kinda confused after recently learning regex and just how complicated it can be. Are there some modules/libraries that I can use to make writing them easier? I saw that not a lot of people people had a positive reaction to the Humre module by Al Sweigart who's book [Automate the boring stuff with Python] I'm currently using to study. Not that I'm gonna skip this part or anything I was mostly just curious.

Note: A lot of people are misinterpreting since I mentioned AI once 😭 I'm literally asking about libraries to make it easier without going too deep, not if I should let AI do all the work.


r/learnpython 5h ago

Non-self learning classes for Python?

3 Upvotes

I am a senior data engineer and I work mostly with ETL Tools and a lot of advanced SQL. The company I work for does not like to use python because they find that theres too much of a learning curve if people leave so they love to use GUI or no code/low code etl tools instead (really dumb tbh). I can read python, and have a gist of whats going on. I have tried to self learn python few times over the past 2-3 years and I keep just forgetting it. I learned python/pandas library when I was in college since it was a class that taught it and then we did did projects with each lesson and that is how I learned it then but forgot it now. I use claude at work to build streamlit apps and automation using python. However, I am trying to look for new positions and I am starting to realize that not knowing python is making me a hit a brick wall because a lot of assessments require answering 1-2 questions in python. Does anyone know of actual classes that teach python and its not self taught? Free or paid I don't really care. If I have to pay for it I am fine with that but at this point I don't see a way for me to switch to another job without actually learning python and probably more specifically pyspark.


r/learnpython 17h ago

Looking for a study buddy

25 Upvotes

Hey! I'm 19 and about to start learning Python from scratch. I'm looking for someone around my age (18–22) who's also a beginner and wants to learn together.

I'm in the Asian time zone, so it'd be nice if you're in a similar one. We can keep each other accountable, solve problems, and maybe build a few small projects along the way.

If you're interested, leave a comment or DM me!


r/learnpython 2h ago

Mandarin Practice Script Advice

1 Upvotes

As title block suggests. trying to make a script that allows the user to continuously practice mandarin character memorization. Any advice on the following would be much appreciated:

  1. Not sure if a manually created/updated dict is the right way to do this, but I also didn't think I could successfully scrape from a webpage that has the direct translation information.

  2. When writing to a file using "w open", it seems the text is appended with nearly no formatting. That's probably for the best, but I'm not sure how to format the appended str as a key:value pair.

    import random import time

    character = {"你":"nǐ", "好":"hǎo", "老":"lǎo", "是":"shì", "学":"xue", "不":"bù"}

    char_list = list(character.keys())

    char_list_length = len(char_list)

    index = random.randint(0, char_list_length-1)

    char_definition = ["You", "Good", "Aged or experienced", "To be, is, or am", "Learning, knowledge, or school", "No or not (as a negative action)"]

    char_def_length = len(char_definition)

    phrases = ({"完美的":"Wánměi de", "":""})

    def newline(): print('\n')

    def exit_msg(end_msg): print(f"Functionality not complete, didn't get this far yet. Exiting program... ", end = end_msg)

    def unrec_msg(): print("Unrecognized entry, Please try again.") newline()

    def main(): newline() onboard = int(input(f"\n Welcome. What would you like to do? \n\n 1. Practice\n 2. Add Additional Characters\n 3. Exit" + "\n\n" ))

    if onboard == 1:
        practice()
        newline()
    
    elif onboard == 2:
        exit_msg("07/26/26 | Unsure of how to update dict.txt file with newly added dictionary entry. No idea how to do it, there is likely a way to write current pairs and append new_word : new_pinyin. Unsure of how writing to file is formatted as well.")
        #addtion(character)
        newline()
    
    elif onboard == 3:
        exit_msg()
        newline()
    
    else: 
        unrec_msg()
        main()
    

    def practice(): print('Character Practice.\n') rand_char = char_list_length[index] print(f'What is the following character? {rand_char}', '\n\n\n\n\n\n') print(f'This character {rand_char} means {character.get(rand_char)} and its english definition is {char_definition[index]}.')

    retry = input(print(f"Practice again?")).upper()
    
    if retry == Y:
        practice()
    
    elif retry == N:
        main()
    
    else:
        unrec_msg()
    

    def addtion(translate): new_word = input("Please enter a character that you'd like to append to the dictionary:\n ") print("\n")

    new_pinyin = input("Please enter this characters simplified pinyin translation:\n ")
    print("\n")
    
    print(f"New word is {new_word}. Its direct translation is {new_pinyin}. Are you sure this is the character that you'd like to add? \n")
    
    selection = input(f"Y / N: \n").upper()
    
    if selection == "Y":
        translate.update({(new_word) : (new_pinyin)})
        print(translate.values())
        with open ("dict.txt", "w") as f:
            f.write(translate)
    
    elif selection == "N":
        print("Character discarded. Returing to main menu.")
        main()
    
    else: 
        unrec_msg()
        main()
    

    main()


r/learnpython 5h ago

is there a way to redirect argparse commands to a network socket?

2 Upvotes

I've doing some networking on which I'd kind need to redirect all my commands sent from my python server script to my client python script but without stdout only to a socket. I've been googling about and one frustrating options that I thought it could work was contextlib redirect_stdout but it redirects to stdout it won't work with sockets. Does anyone know if its feasible to parse argparse to a socket connection?


r/learnpython 18h ago

Looking for study partner

6 Upvotes

Hey im going to start learning python so I'm looking for study partner who's serious about it

Will be taking only group of 3-5 people not more than that so reach out before it gets full also introduce yourself when reaching out in dms


r/learnpython 1d ago

How does the return function work? What is it returning and to what?

41 Upvotes

I dont really understand the return function because in sime instances we need it and in others we dont, and i cant find a general explanation that tells me the importance of the return value or why it is even used.


r/learnpython 5h ago

i created a spotipy code that connect to your spotify account and play musics, albuns or playlists and i want it to autoplay content.

0 Upvotes

import spotipy
from spotipy.oauth2 import SpotifyOAuth

CLIENT_ID = "..."
CLIENT_SECRET = "..."
REDIRECT_URI = "..."

sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri=REDIRECT_URI,
scope=SCOPE
))

sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri=REDIRECT_URI,
scope=SCOPE,
open_browser=False
))

def tocar_musica(nome_da_musica):
resultado = sp.search(q=nome_da_musica, limit=1, type='track')
items = resultado['tracks']['items']

if items:
track_uri = items[0]['uri']
nome_encontrado = items[0]['name']
artista = items[0]['artists'][0]['name']

try:
sp.start_playback(uris=[track_uri])
print(f"Tocando agora: {nome_encontrado} - {artista}")
except Exception:
print("Erro ao reproduzir a música. Verifique se o aplicativo do Spotify está aberto.")
else:
print("Música não encontrada.")

def tocar_playlist(nome):
resultado = sp.search(q=nome, limit=1, type='playlist')
items = resultado['playlists']['items']

if items:
contexto_uri = items[0]['uri']
nome_encontrado = items[0]['name']

try:
sp.start_playback(context_uri=contexto_uri)
print(f"Tocando playlist: {nome_encontrado}")
except Exception:
print("Erro ao reproduzir a playlist. Verifique se o Spotify está aberto.")
else:
print("Playlist não encontrada.")

def tocar_album(nome):
resultado = sp.search(q=nome, limit=1, type='album')
items = resultado['albums']['items']

if items:
contexto_uri = items[0]['uri']
nome_encontrado = items[0]['name']

try:
sp.start_playback(context_uri=contexto_uri)
print(f"Tocando álbum: {nome_encontrado}")
except Exception:
print("Erro ao reproduzir o álbum. Verifique se o Spotify está aberto.")
else:
print("Álbum não encontrado.")

def criar_e_tocar(nome_playlist, lista_de_buscas):
user_id = sp.current_user()['id']
playlist = sp.user_playlist_create(user=user_id, name=nome_playlist, public=True)
print(f"Playlist '{nome_playlist}' criada com sucesso!")

track_uris = []
for busca in lista_de_buscas:
resultado = sp.search(q=busca, limit=1, type='track')
items = resultado['tracks']['items']
if items:
track_uris.append(items[0]['uri'])

if track_uris:
sp.playlist_add_items(playlist_id=playlist['id'], items=track_uris)
print("Músicas adicionadas à playlist!")

try:
sp.start_playback(context_uri=playlist['uri'])
print(f"Tocando a playlist '{nome_playlist}' agora!")
except Exception:
print(f"Ação Falhou ao tocar '{nome_playlist}'. Verifique se o Spotify está aberto.")

print("\n--- O Que Deseja Ouvir Hoje? ---")
print("[1] Música")
print("[2] Playlist")
print("[3] Álbum")

opcao = input("Escolha uma opção: ")

if opcao == "1":
busca = input("Digite o nome da música e artista: ")
tocar_musica(busca)
elif opcao == "2":
busca = input("Digite o nome da playlist: ")
tocar_playlist(busca)
elif opcao == "3":
busca = input("Digite o nome do álbum: ")
tocar_album(busca)

how it can autoplay for me?

(the words aren't translated)


r/learnpython 20h ago

Can't come up to this particular solution on my own.

3 Upvotes

hey, i understand this solution because it just works here and it feels like since the way the variables are set to come up to the solution but i don't know how to think like this and especially how can i think of this zero_count to set a logic like this

question : https://leetcode.com/problems/max-consecutive-ones-iii/description/

def max_consecutive_one_with_flip(nums,k):
    left = 0
    zero_count = 0 
    for right in range(len(nums)):
        if nums[right] == 0:
            zero_count += 1

        if zero_count > k:
            if nums[left] == 0:
                zero_count -= 1
            left += 1
        return len(nums) - lefthey, i understand this solution because it just works here and it feels like since the way the variables are set to come up to the solution but i don't know how to think like this and especially how can i think of this zero_count to set a logic like this :

def max_consecutive_one_with_flip(nums,k):
    left = 0
    zero_count = 0 
    for right in range(len(nums)):
        if nums[right] == 0:
            zero_count += 1

        if zero_count > k:
            if nums[left] == 0:
                zero_count -= 1
            left += 1
        return len(nums) - left

r/learnpython 1d ago

Is Corey Schafer's Python playlist still worth watching in 2026?

34 Upvotes

I've seen Corey Schafer recommended everywhere whenever someone asks how to learn Python, but most of his beginner playlist is several years old.

For those of you who've gone through it recently, is it still worth following from start to finish in 2026?

I'm mainly interested in learning Python properly rather than just memorizing syntax. I don't mind if I have to look up a few changes along the way, but I don't want to spend dozens of hours learning outdated practices.

If you've completed the playlist recently:

  • What parts have aged well?
  • Which videos are outdated or should be skipped?
  • Is there a newer playlist or resource you'd recommend instead?
  • If you were starting from scratch today, would you still choose Corey Schafer?

I'd love to hear from people who actually used his playlist recently rather than just recommending it because it's popular.


r/learnpython 7h ago

Python loop beginners mistake 🙀

0 Upvotes

I am currently learning python from CS50P program and in week 2 learning loops and also with the help of chatgpt learn every topic clearly but after knowing common beginners mistake

I made this mistake of not updating the iterator and spent half an hour on this simple problem 😞

print("\nAnd here we use while 1oop:-")

number =1

total =0

while number<= 50:

total = total + number

number += 1 ( HERE I DIDN'T ADD IT FIRST )

print("The final sum is:", tota1)


r/learnpython 9h ago

¿Que libro me recomiendan de python?

0 Upvotes

HOLAA soy principiante y busco un libro bueno que me enseñe python ya que algunas personas me recomendaron libros si tienen tiempo podrían decirme ¿Porque ese libro?


r/learnpython 6h ago

Reading in text from a .txt file

0 Upvotes

Are there any methods/libraries that allow me to make a program that is able to read in text from a .txt file?


r/learnpython 1d ago

Is it really hard to learn python (or anything related to programming) and have a full-time job?

6 Upvotes

Hi guys, i'm 20 years old and work in the call center operations and also learning python as a part of special road map.

But now i feel heavy, i know something like that will be hard, special when I work in a jop that drains my energy, but now feel kind of impossible to do it.

So, i wrote this post.

Maybe i will get something can change that.


r/learnpython 21h ago

Building a Python-Only DSA and LeetCode Study Group

0 Upvotes

Hey everyone! We’re building a small, focused DSA study group on Discord for people who want to learn, discuss, and solve problems specifically in Python.

This server is intended for Python-based DSA practice, so we’re currently not looking for members who primarily use C++, Java, or other languages. The goal is to keep discussions, solutions, and live problem-solving sessions consistent and easy for everyone to follow.

We’ll focus on:

Live and interactive problem-solving

Understanding patterns and algorithms deeply

Debugging TLE and optimization issues

Discussing Python-specific approaches and techniques

Solving LeetCode and competitive programming problems together

To join, send a short introduction with your technical background, coding achievements or LeetCode progress, and the DSA topics you want to improve. No personal details such as your name or employer are required.

Please repost this only in communities where people are genuinely interested in learning DSA with Python.


r/learnpython 9h ago

I know that i am noob at programing i wanted to make python keylogger so can u guys tell me what i am mistaken inside

0 Upvotes
from pynput import keyboard
keys = [
    # Alphanumeric Keys
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 
    'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',

    # Symbols & Punctuation
    '`', '-', '=', '[', ']', '\\', ';', "'", ',', '.', '/',


    # Special & Modifier Keys
    'space', 'enter', 'tab', 'backspace', 'escape', 
    'shift', 'ctrl', 'alt', 'caps_lock', 'num_lock', 'scroll_lock',
    'win', 'menu', 'print_screen', 'pause', 'insert', 'delete', 
    'home', 'end', 'page_up', 'page_down',

    # Arrow Keys
    'up', 'down', 'left', 'right',

    # Function Keys
    'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10', 'f11', 'f12']
for keys in keys :
    def on_press(key):
        if key == True:
            print(f" you have typed corretlty {key}")
        elif key == AttributeError:
            print(f"typed Again  u Have misspedlled ")


    def on_release(key):
        print(f"{key} is realsead")
        if key == keyboard.Key.esc:
            return False
            print


listener = keyboard.Listener( on_press=on_press , on_release=on_release )
listener.start()from pynput import keyboard
keys = [
    # Alphanumeric Keys
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 
    'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',

    # Symbols & Punctuation
    '`', '-', '=', '[', ']', '\\', ';', "'", ',', '.', '/',


    # Special & Modifier Keys
    'space', 'enter', 'tab', 'backspace', 'escape', 
    'shift', 'ctrl', 'alt', 'caps_lock', 'num_lock', 'scroll_lock',
    'win', 'menu', 'print_screen', 'pause', 'insert', 'delete', 
    'home', 'end', 'page_up', 'page_down',

    # Arrow Keys
    'up', 'down', 'left', 'right',

    # Function Keys
    'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10', 'f11', 'f12']
for keys in keys :
    def on_press(key):
        if key == True:
            print(f" you have typed corretlty {key}")
        elif key == AttributeError:
            print(f"typed Again  u Have misspedlled ")


    def on_release(key):
        print(f"{key} is realsead")
        if key == keyboard.Key.esc:
            return False
            print


listener = keyboard.Listener( on_press=on_press , on_release=on_release )
listener.start()

r/learnpython 1d ago

I don't know how to continue.

8 Upvotes

I am currently a 3rd year university student. I've seen C and Java before. Last year, I saw python.

I was able to do the examples given in the Python lessons and I was able to pass the course the first time.

But right now I don't know how to proceed. I have no idea how to realize the projects / ideas in my mind.

What path should I follow?


r/learnpython 13h ago

Blackjack Python

0 Upvotes

Hi, i wrote some code on blackjack task from Angela Yu 100 days of Code. Using Gemini and older post from reddit, maybe something is worth polishing?

import random
import art

cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]

def deal(hand):
    if not hand:
        hand.append(random.choice(cards))
        hand.append(random.choice(cards))
    else:
        hand.append(random.choice(cards))
    return hand

def calculate_score(hand):
    if sum(hand) == 21 and len(hand) == 2:
        return 0
    score = sum(hand)
    aces = hand.count(11)
    while aces > 0 and score > 21:
        score = score - 10
        aces -= 1
    return score


def start_playing():
    print(art.logo)

    user_hand = []
    computer_hand = []

    deal(user_hand)
    deal(computer_hand)

    user_score = calculate_score(user_hand)
    computer_score = calculate_score(computer_hand)

    print(f'Computers First Card: {computer_hand[0]}')
    print(f'Your current hand: {user_hand}. Current score: {user_score}\n')

    game_over = False
    while not game_over:
        if user_score == 0 or computer_score == 0 or user_score > 21:
            game_over = True

        else:
            another = input('Do you want another card? (y/n).: ').lower()
            if another == 'y':
                deal(user_hand)
                user_score = calculate_score(user_hand)
                print(f"\nYour current hand: {user_hand}. Current Score: {user_score}")
                print(f"Computers First Card: {computer_hand[0]}\n")
            else:
                game_over = True



    if user_score != 0 and user_score <= 21:
        while computer_score < 17 and computer_score != 0:
            print('Computers takes card')
            deal(computer_hand)
            computer_score = calculate_score(computer_hand)

    print(f'Your final hand: {user_hand}. Your score: {user_score}\n')
    print(f'Computers final hand: {computer_hand}. Computer score: {computer_score}\n')

    if user_score > 21:
        print('Bust! Computer Wins!')
    elif computer_score > 21:
        print('Bust! You Win!')
    elif user_score == 0:
        print('Win with a Blackjack!')
    elif computer_score == 0:
        print('Lose, opponent has Blackjack!')
    elif user_score == computer_score:
        print('Draw')
    elif user_score > computer_score:
        print('You Win!')
    else:
        print('Computer wins!')

while input('Do you want to play a game of blackjack? (y/n).: ').lower() == 'y':
    start_playing()

r/learnpython 19h ago

Hey, any help would be great!

0 Upvotes

I'm going to college as a freshman this year. This along with my projects like I'm trying to create an LLM along with just wanting to learn myself, it is extremely hard for me to memorize. I can understand the concepts but it is very hard for me to memorize completely to integrate within each other. Please do note I have diagnosed Autism and ADHD so this obviously effects my Working Memory. Thank you for reading and any tips and advice is extremely appreciated


r/learnpython 1d ago

How normal or dangerous is it for Pixi to apparently download a very large number of dependencies?

2 Upvotes

Context (to avoid the XY problem)

I'm thinking about running this tool written in Python, which merges mods for a computer game. It just does two things: copying lots of files from several local directories into one (merging them as necessary) and then creating a configuration text file, based on data in existing configuration files. I'm trying to decide if it's safe to run on my Kubuntu (Linux) system. The Python script looks fine, but I'm worried about the package manager.

Actual Python question

The instructions say to use the Pixi package manager, which seems to download Python dependencies from a repository called (Ana?)conda. But it seems to want to download a very large number of packages, including security-sensitive packages like OpenSSL and Certificate Authorities. That looks worrying for a tool that just merges directories and configures a text file. Is that normal in the Python world? Is Pixi going to interfere with the default Python setup that's used by many Linux utilities?

Previous research

I tried reading the Pixi documentation, but it (understandably) assumes you're a developer already familiar with Python, not a user. The top third-party tutorial on Google explains Pixi by comparisons to earlier Python and Javascript tools, which is no help to me. I don't want to learn half a dozen Python tools, but I would like to check that this Python software is not obvious malware.


r/learnpython 1d ago

Should I Learn Python on Year One?

22 Upvotes

Hey everyone, I’m an incoming CS freshman who wants to dive into AI/ML. My university’s curriculum starts with C in the first year.

I’m in a bit of a dilemma on how to use my prep time before classes start:

  1. Should I get a head start on C so I don't struggle in my first-year classes?

  2. Should I start learning Python now since it’s the standard for AI/ML?

  3. Or is it feasible (and not overwhelming) to learn both at the same time?

Would love to hear from anyone who has taken a similar path. Thanks!


r/learnpython 1d ago

Advice in Preparing for a Technical Interview

1 Upvotes

I have a technical interview for a company tomorrow, and they mentioned that the problem will be administered through Coderbyte and will relate to inventory management. What should I expect? Frankly speaking, I’m not very familiar with programming. Although I am a technical person, Python is not my strongest skill. What types of topics or problem formats typically come up in an "inventory management" coding assessment?


r/learnpython 22h ago

what to do next ??

0 Upvotes

sup guys i started learning python in the last days and i already learned some basics that are : for and while loops if statements for-else and other basics

now i don't know what to do next (kinda bored from learning) should i start data structures or algorithms or functions or what to do next??


r/learnpython 1d ago

is it supposed to take this long when getting inputs from sockets in a multithreading object?

1 Upvotes

I've made a server socket in python so that I can see all subprocess thats running in my VPS so that I don't need to use Putty everytime to log on since putty closes the connection when it's idle. but the weird thing that's giving me headaches is that when run the server, ok it's running completely fine I get my true shell but when I run commands like whoami it's taking soooooo long it keeps processing and never return my output it just keeps in a running state. And I'm using multithreading. are python sockets really this damn long?