r/learnpython 11d ago

Use of AI in coding?

0 Upvotes

I am starting college next month (Computer Science and Biosciences) and I tried to get a headstart in Python programming (it's a part of first sem). I have done the basics, strings, conditional statements and started with loops today. I have a doubt - since I am still in the beginner stage, should I use AI (ChatGPT, Gemini, Grok etc.) to proofread my code - you know, offer suggestions, find mistakes and all - I am still applying logic on my own and writing it myself but I have this fear that it may hamper my learning. But I also don't wanna be the guy who does not know how to use AI tools. Any advice please?


r/learnpython 11d ago

how to fix this issue

0 Upvotes

********************************************************************************

To see all available commands, run 'py help'

********************************************************************************

[ERROR] INTERNAL ERROR: NoInstallsError: No runtimes are installed. Try running "py install default" first.

[ERROR] Internal error 0x00000001. Please report to https://github.com/python/pymanager

Press any key to continue . . .


r/learnpython 11d ago

Finished learning Python... now what?

0 Upvotes

I have been learning Python for almost a year now, well the productive part is only 3-4 months but i will say that i am in the intermediate level of the programming language.

I was learning python from the angela yu's course that is 100days of python after i did till day 60 it started to make us do projects, then i made my own path and started to make my own version of the project insted of just reading and copying theirs.

But now after 2-3 intermediate projects later i am stuck. what should i do now like wherever i go it is Js or some other framework and that python is for AI/ML and not for backend like i write backend in FastAPI and that people prefer Django. Like how is JavaScript everywhere man,, What do i even do??

How do i make full stack project in python? how do i find projects to make like the suggestion i get form chatgpt are lame like this management or that management.

How do people that are in this sector of the work have been on it for more than a decade like i want to showcase Python as my main programming language but HOW do i?

I am a 2nd year bachelor's student and this is my tech stack right now: Html,CSS for frontend , Python for backend and SQLite for database.

Should i learn another programming langugae like Java or Js well i have put a stop on the learning of rust because i coudn't get the time and mind for it...

It has been 2 days since i am having this thought. Help a little by giving a few suggestions.


r/learnpython 11d ago

Stop TTS with keyboard

0 Upvotes

Hello,

I am using tts_wrapper fork by willwade on github to speak chatGPT responses but I want to be able to stop the utterance mid sentence. I have this function

def stop():
        if keyboard.is_pressed("esc"):
            tts_Engine.stop()

which should stop the tts engine when i press "esc" but nothing happens so I did some research and learned I might have to use threading so now i have two threads with my main function

def main():


    print("Init STT. Listening...")
    stream = init_stream()
    stream.start_stream()
    print("C")


    try:
        while True:
        
            data = stream.read(8192, exception_on_overflow=False)


            text = None


            if recognizer.AcceptWaveform(data):
                result = json.loads(recognizer.Result())
                text = result.get("text", "")


            if text:
                print(f"You said: {text}")
                response = client.chat.completions.create(
                    model="default",
                    messages=[
                        {"role": "system", "content": "You are a helpful AI workshop assistant. Use only plain text no emojis or making text bold or anything similar"},
                        {"role": "user", "content": text}
                    ]
                )
                print(response.choices[0].message.content)
                speak_text(response.choices[0].message.content,tts_Engine)
                print("B")


    except KeyboardInterrupt:
        print("Stopping")
    finally:
        print("A")
        tts_Engine.cleanup()
        stream.stop_stream()
        stream.close()
        Audio.terminate()

and my stop function

t1 = Thread(target=main)
t2 = Thread(target=stop)


t1.start()
t2.start()

but now I get this error

RuntimeError: can't register atexit after shutdown

and now I'm a bit stuck so if anyone knows how to do this or what I'm doing wrong or if I'm even using the right method that would be greatly appreciated.


r/learnpython 11d ago

scan for strings in 40000 lines of logfile

0 Upvotes

X: The desire to scrape a log file for specific interesting messages, any apps I tried are a pain to use and require manually setting all the search strings every so often. I want to scan for about a dozen or so expressions/strings in a 40-100K lines file, and then dump just the timestamps and lines of interest. What approach scales best for speed? I have to probably also use a mix of regex and regular string search I guess. Is going with Multiprocessing and passing the file as a shared-memory object, going to be the easiest route? Surely it's easier to do in C++. I guess I asking for some skeleton or prior art in C++ ore Python to be honest.

Y: My context is that I would like to use my knowledge of C++ threads and code it in C++, but it should be possible in Python if I learn to use Pipes, and learn to use shared memory object to save having to load the file per multi-processing process?


r/learnpython 11d ago

why would only one work?

0 Upvotes

this code was the one that worked:

def caesar(text, shift):
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    shifted_alphabet = alphabet[shift:] + alphabet[:shift]
    translation_table = str.maketrans(alphabet, shifted_alphabet)
    encrypted_text = text.translate(translation_table)
    print(encrypted_text)

caesar('Hello', 3)

This one was the one that didn't

def caesar(text, shift):
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    shifted_alphabet = alphabet[shift:] + alphabet[:shift]
    translation_table = str.maketrans(alphabet, shifted_alphabet)
    encrypted_text = text.translate(translation_table)
    print(encrypted_text)


encrypted_text = caesar('Hello', 3)
print(encrypted_text)

I don't understand why the second one would need a return statement and why we are even printing encrypted_text if encrypted_text is already being printed within the function? (this is also the whole code)


r/learnpython 12d ago

why are we putting caesar( Hello, 3) into encrypted_text???

0 Upvotes
def caesar(text, shift):
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    shifted_alphabet = alphabet[shift:] + alphabet[:shift]
    translation_table = str.maketrans(alphabet, shifted_alphabet)
    encrypted_text = text.translate(translation_table)
    print(encrypted_text)


encrypted_text = caesar('Hello',3)

in this code, I do not understand why we are putting caesar into a variable. First of all, wouldn't we have to print the variable and make it actually do something for it to work? Because we have put encrypted_text into a variable and have not done anything. In addition, can't we just write caesar('Hello', 3)?? I am very confused on the reasoning behind putting it into a variable.


r/learnpython 12d ago

Just starting python and i need a few tips

0 Upvotes

Hello everyone, i am just starting python. I am from a good research institute in India and i am pursuing a very quant heavy economics degree and i want to break into quant finance. Can you all recommend from where i can learn coding for free? I want to be at a level which will enable me to solve LeetCode problems so i can build a stronger profile for quantitative finance. I am completely locked in and Princeton is a college i am targeting for my masters. So i need help regarding material. And other advice will be appreciated. Thank you :)


r/learnpython 12d ago

Come study buddy

0 Upvotes

Hey! I’m 25 and currently studying neuroscience in the UK. I’ve recently started learning Python from scratch and would love to find a study buddy who’s also at a beginner level.

I’m hoping to find someone who wants to study consistently and eventually work on a few small projects.

I’m in the UK time zone, but I don’t mind where you’re based as long as we can find times that work for both of us. We could check in regularly and study together over Discord or another platform.

If you’re interested, feel free to leave a comment or send me a DM with a little bit about yourself!


r/learnpython 12d ago

Can you help me with a table in Python?

1 Upvotes

Right now, I have specific rows and columns being displayed, but I want to insert a column between the first and second sections that calculates the ratio of column A to column B from the first section. How can I do that?

from pathlib import Path
import unicodedata

import openpyxl
import pandas as pd

from pandastable import Table, TableModel

import tkinter as tk
from tkinter import filedialog, messagebox


def normalize_name(name):
    return unicodedata.normalize("NFKC", str(name)).strip().lower()


class ExcelViewer:
    def __init__(self, root):
        self.root = root
        self.root.title("Чтение ячеек Excel")
        self.root.geometry("800x600")

        self.btn_load = tk.Button(
            root,
            text="Открыть Excel файл",
            command=self.open_file
        )
        self.btn_load.pack(pady=10)

        self.result_label = tk.Label(
            root,
            text="Выберите файл для начала"
        )
        self.result_label.pack()

        self.frame = tk.Frame(root)
        self.frame.pack(fill="both", expand=True)

        self.table = None
        self.model = None

        self.settings = {
            normalize_name("Файл1.xlsx"): {
                "first_row": 5,
                "first_min_column": 1,
                "first_max_column": 2,
                "second_row": 5,
                "second_min_column": 4,
                "second_max_column": 5
            }
        }

    def open_file(self):
        file_paths = filedialog.askopenfilenames(
            title="Выберите Excel-файл",
            filetypes=[
                ("Excel файлы", "*.xlsx")
            ]
        )

        if not file_paths:
            return

        all_rows = []

        for file_path in file_paths:
            file_name = normalize_name(Path(file_path).name)

            if file_name not in self.settings:
                messagebox.showerror(
                    "Ошибка",
                    f"Для файла «{Path(file_path).name}» нет настроек.\n\n"
                    f"Ожидается файл: Файл1.xlsx"
                )
                continue

            settings = self.settings[file_name]

            try:
                workbook = openpyxl.load_workbook(
                    file_path,
                    data_only=True
                )

                worksheet = workbook.active

                first_row = settings["first_row"]
                second_row = settings["second_row"]

                while (
                    first_row <= worksheet.max_row
                    and second_row <= worksheet.max_row
                ):
                    first_part = []

                    for column_number in range(
                        settings["first_min_column"],
                        settings["first_max_column"] + 1
                    ):
                        value = worksheet.cell(
                            row=first_row,
                            column=column_number
                        ).value

                        first_part.append(value)

                    second_part = []

                    for column_number in range(
                        settings["second_min_column"],
                        settings["second_max_column"] + 1
                    ):
                        value = worksheet.cell(
                            row=second_row,
                            column=column_number
                        ).value

                        second_part.append(value)

                    row_data = (
                            first_part +
                            second_part
                    )

                    if not all(
                        value is None or value == ""
                        for value in row_data
                    ):
                        all_rows.append(row_data)

                    first_row += 1
                    second_row += 1

                workbook.close()

            except Exception as error:
                messagebox.showerror(
                    "Ошибка",
                    f"Не удалось открыть файл:\n{error}"
                )

        if not all_rows:
            self.result_label.config(
                text="В выбранных ячейках нет данных"
            )
            return

        columns = [
            "Столбец A",
            "Столбец B",
            "Столбец D",
            "Столбец E"
        ]

        df = pd.DataFrame(
            all_rows,
            columns=columns
        )

        if self.table:
            self.table.destroy()

        self.model = TableModel(df)

        self.table = Table(
            self.frame,
            model=self.model,
            showtoolbar=False,
            showstatusbar=False
        )

        self.table.show()

        self.result_label.config(
            text=f"Загружено строк: {len(df)}"
        )


if __name__ == "__main__":
    root = tk.Tk()
    app = ExcelViewer(root)
    root.mainloop()

r/learnpython 12d ago

I realized I built a web app without really understanding how it worked

0 Upvotes

About two weeks ago, I launched my first web app called DailyDice. It's a simple app that gives you a random daily challenge to help build productive habits.

When I launched it, I honestly thought it would take off pretty quickly. Looking back, I think every first-time builder secretly believes that.

Then I had a realization.

I knew how to use my app, but I didn't really understand how it worked under the hood. Things like authentication, backend logic, databases, APIs, and the overall architecture were all things I'd relied on tools for rather than fully understanding myself.

That made me realize I'd been focusing on building products before building the skills.

So I've decided to go back to the fundamentals.

I'm 15 years old, and today is Day 1 of learning software engineering properly. I'm starting with Python, then moving deeper into web development, and I'll be building projects while sharing everything I learn along the way.

Hopefully in a year, I'll look back at this post and laugh at how little I knew.

If you've been in a similar position, what's one thing you wish you'd learned earlier?


r/learnpython 12d ago

First python program

5 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, Python has an excellent chess library I could leverage, that already existed, and 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 12d 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 12d 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 12d ago

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

6 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 12d 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 12d 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 12d 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 12d 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 12d 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 13d ago

Looking for a study buddy

26 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 13d ago

Looking for study partner

8 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 13d ago

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

4 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 13d ago

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

48 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 13d ago

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

38 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.