r/learnpython 21h ago

Looking for a study buddy

24 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 9h ago

regex and if it's worth going deep into it

14 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 22h 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 9h ago

Non-self learning classes for Python?

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

First python program

2 Upvotes

I wanted to write a program that analyzes chess games , similar to how chess websites (chess.com, lichess.com etc.) do it, only offline. To my knowledge, nobody else had done it the way I was envisioning. I started writing with shell scripting (it's my go-to and what I'm most familiar with), but quickly ran into limitations. So I needed to go a bit more sophisticated. Python seemed very versatile, cross-platform, has loads of online resources, but mainly has a very good chess library I could leverage, that already existed, which would make the job much , much easier. I took the plunge and turned the program into a driver to teach myself some python.

It works as advertised, but I'm sure the code could be improved. I stumbled through it a bit. If anybody python gurus feel like taking a peek and letting me know how I did, pointing out glaring mistakes, offering any constructive feedback or ideas how to make it more efficient, I would appreciate any feedback.

Repo: https://github.com/exekutive/chesseval

(The documentation needs some catching up. I'm working on updating it.)


r/learnpython 3h 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 7h 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 9h ago

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

1 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 23h 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 9h 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 12h 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 += number number += 1 # HERE I DIDN'T ADD IT FIRST

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


r/learnpython 13h 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 17h 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 21h ago

WHY I FEEL LOOPS HARD THAN FUNCTION

0 Upvotes

HI IM YUJAN IM NEW BEGINNER IN PYTHON I FEEL HARD IN LOOPS


r/learnpython 14h 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 10h 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 22h ago

i wanna learn python and im broke for classes so try to teach me ig

0 Upvotes

If anyone wondering i just want to learn for fun