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

Looking for a partner in crime.

17 Upvotes

Hey everyone,

I’ve just started learning Python, and I’m really excited! However, I think it would be even more fun and motivating to have someone to learn with, especially as I delve deeper into this rabbit hole. It’s getting tough! I’m looking for a partner in crime to discuss concepts, share resources, and keep each other accountable.

If you’re also starting out or even if you’re a bit further along, I’d love to connect! We can chat about our progress, tackle challenges together, and maybe even work on some small projects.

Let me know if you're interested, and we can figure out how to stay in touch!

Happy coding! 🐍


r/learnpython 8h ago

Hardest thing about learning

21 Upvotes

I think the hardest thing about learning Python for me is dealing with all of the complicated ways of building a script that I come up with, to only later find out it was much more simple than I made it out to be.

And this…every single time…..


r/learnpython 5h ago

New to Python and wanted to know what the purpose of super is in this code.

7 Upvotes

Was trying to make an auto clicker in python with varying levels of success. I decided to google it and I understand most of the code except why super(ClickMouse, self) is there.

Here is the full code for reference

# importing time and threading 
import time 
import threading 
from pynput.mouse import Button, Controller 
  
# pynput.keyboard is used to watch events of  
# keyboard for start and stop of auto-clicker 
from pynput.keyboard import Listener, KeyCode 
  
  
# four variables are created to  
# control the auto-clicker 
delay = 0.001
button = Button.right 
start_stop_key = KeyCode(char='a') 
stop_key = KeyCode(char='b') 
  
# threading.Thread is used  
# to control clicks 
class ClickMouse(threading.Thread): 
    
  # delay and button is passed in class  
  # to check execution of auto-clicker 
    def __init__(self, delay, button): 
        super(ClickMouse, self).__init__() 
        self.delay = delay 
        self.button = button 
        self.running = False
        self.program_running = True
  
    def start_clicking(self): 
        self.running = True
  
    def stop_clicking(self): 
        self.running = False
  
    def exit(self): 
        self.stop_clicking() 
        self.program_running = False
  
    # method to check and run loop until  
    # it is true another loop will check  
    # if it is set to true or not,  
    # for mouse click it set to button  
    # and delay. 
    def run(self): 
        while self.program_running: 
            while self.running: 
                mouse.click(self.button) 
                time.sleep(self.delay) 
            time.sleep(0.1) 
  
  
# instance of mouse controller is created 
mouse = Controller() 
click_thread = ClickMouse(delay, button) 
click_thread.start() 
  
  
# on_press method takes  
# key as argument 
def on_press(key): 
    
  # start_stop_key will stop clicking  
  # if running flag is set to true 
    if key == start_stop_key: 
        if click_thread.running: 
            click_thread.stop_clicking() 
        else: 
            click_thread.start_clicking() 
              
    # here exit method is called and when  
    # key is pressed it terminates auto clicker 
    elif key == stop_key: 
        click_thread.exit() 
        listener.stop() 
  
  
with Listener(on_press=on_press) as listener: 
    listener.join() 

r/learnpython 5h ago

To all python experts :-

6 Upvotes

What is the process of thought while you guys are working on a project. May it be anything from a beginner project all the way to advanced work. Please share your words of wisdom with me as I am a beginner. Thank you!


r/learnpython 18h ago

I'm a beginner in python and have a coding interview tomorrow. How cooked am I? How can I save myself from 1 hour of embarrassment?

58 Upvotes

I'm a data analyst with a fair understanding of Python. I was interviewed for a Data QA Engineer position, and the coding round is tomorrow. I'm getting extremely anxious about making a fool out of myself tomorrow and need any last-minute tips and tricks to help myself even a little bit.

UPDATE: There was no live coding or any coding at all. It's weird because the email said there would be live coding in Python, but instead, they asked me probability and logical reasoning questions. IMO, that is a better assessment of my intellectual ability, so I'm happy! Thank you for your kind words and encouragement; they helped me immensely. I will post another update if I receive an offer or not.


r/learnpython 4h ago

Running only part of code in a file in VSCode

3 Upvotes

Hi all, I am coming from an SQL world where I can have many sql code segments in one file and then just select one of these (by highlighting) and then run selection.

This means I can have many small 'test' sql statements in one place and can select what to run.

I was writing some beginner python code and wanted to have it all in one place and just run the subset of all the code I selected.

Is this possible - without using something like Jupiter Notebook?


r/learnpython 4h ago

File Path Error when Importing CSV File

3 Upvotes

Hey All! I have some issues while uploading a CSV file to VS Code. I'm using WSL so I have successfully copied the CSV file to the Ubuntu Directory, yet it shows 'no Such File Directory'. I have tried importing from the local C drive as well, but the same issues arise.

Highly Appreciate any advice!

Thanks!


r/learnpython 4h ago

Need help for DSA in python

3 Upvotes

Hello, I'm a beginner in python and I'm looking for some good course & resource for DSA in python. Any recommendations?


r/learnpython 5h ago

Problem with pytest/vscode

3 Upvotes

Hello, I am new to python learning, and I'm using a book from Eric Matthes. I got to the chapter for code testing. Unfortunately pytest shows an error everytime I test the code exaple that is in the book and I don't know why. Here is the code and the test:

def get_formatted_name(first, last, middle=''):
    """Generate a neatly formatted full name."""
    if middle:
        full_name = f"{first} {middle} {last}"
    else:
        full_name = f"{first} {last}"
    return full_name.title()


from name_function import get_formatted_name

def test_first_last_name(self):
    """Do names like 'Janis Joplin' work?"""
    formatted_name = get_formatted_name('janis', 'joplin')
    self.assertEqual(formatted_name, 'Janis Joplin')

    def test_first_last_middle_name():
        formatted_name = get_formatted_name('wolfgang', 'mozart', 'amadeus')
        assert formatted_name, 'Wolfgang Amadeus Mozart'

The Error is:

=================================== ERRORS ==================================== ___________________ ERROR at setup of testfirst_last_name ___________________ file c:\Users\twals\python_learn\test_names.py, line 3 def test_first_last_name(self): E fixture 'self' not found

  available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, monkeypatch, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory
  use 'pytest --fixtures [testpath]' for help on them.

c:\Users\twals\python_learn\test_names.py:3 =========================== short test summary info =========================== ERROR test_names.py::test_first_last_name ============================== 1 error in 0.05s =============================== Finished running tests!

They are in 2 different files, the test file begins with "test_".

I don't know why I get this error. I wrote the exact same as the book says...


r/learnpython 3h ago

Notes to learn Python on Jupyter

2 Upvotes

If some has Python notes as a Jupyter notebook, please share it with me. Since notebooks allow text and codes together with all the editing options for text, I was wondering if someone out there has made a Jupyter notebook about everything Python. I feel that it would be a better learning experience if the notes and the console are together.


r/learnpython 20m ago

New to Python and learning web scraping. Can you guide me how to get the data in separate lines (as in website) without using the if statement

Upvotes

I'm scraping the following website through BeautifulSoup library.

https://subslikescript.com/movie/Titanic-120338"

I was able to get the transcript in separate lines with the help of chat GPT by following code.

transcript = box.find('div', class_='full-script')

with open(f'{title}.txt', 'w') as file:
    if transcript:             
        for line in transcript.stripped_strings:
            file.write(line + '\n')

I tried "Strip=True" & "Separator=' '", but it didn't work.

Is there any easy way to get the transcript in separate lines without using if statement.

Thanks


r/learnpython 32m ago

For those struggling with what methods to use in a particular module

Upvotes

I am a beginner so bare with me. I also struggled with knowing what is included in a module and some websites have the docs but there are some sites that don't provide everything

I just learned how to show all the methods for a module

print(dir(module)) # this prints all the methods that we are working with in the module

r/learnpython 34m ago

Code obfuscation

Upvotes

Does anyone have recommendations of which approach to use for obfuscation in Python?

Whilst I appreciate that every method we use can be reverse engineered, particularly given the interpreted nature, at a minimum I am looking to get to a point where I have something that is at least a bit of a pain to unpick, and at best, something that would take an attacker substantial time and effort to reverse engineer.

I'm working with multi script environments with imports etc. (which makes simple approaches a bit cumbersome)..

Ideal workflow would be, obfuscate ->Pyinstaller ->done (all from within a .venv setup for packing).

  • PyArmor was a candidate.. but even their licence terms is so littered with spelling mistakes and convoluted wording that I struggle to trust their solution with packaging a complex app (I'm beyond the size that their "trial" permits).. especially when it seems that something as basic as Pandas would require manual patching.

  • Oxyry - again, documentation is pretty light.. I don't want to spend $190+ and be stuck with something I need to debug for 3weeks.

Are there any other solutions that are relatively plug and play?

Has anyone used PyArmor, and is it actually better than it appears (particularly for complex projects)?


r/learnpython 1h ago

Great course or projects to keep learning python?

Upvotes

I just finished my first semester on programming in python and my teachers recommend to keep practicing python so we keep getting better at it and we don't forget stuff for when we start programming again in the future.

I've not done any OOP yet, but besides that I already had most of the other stuff like loops, if/else, functions, variables etc.

So are there any courses or projects you'd recommend to follow or make? I'd atleast like something that has a lot of exercises to practice what you learn.

I've already found the MOOC from the University of Helsinki and 100 Days of Code from Replit but idk if they'd be any good to do since I've already learned about the first half


r/learnpython 1h ago

Downside of one folder structure?

Upvotes

Hi, I'm refactoring/rewriting something for a client, I was originally having it all all in one juypter notebook given how often they changed requirements and I just find it easier to write there.

I then moved to a one big py file that I run daily locally, but we're moving it to a server, and eventually should be on cloud (originally I just wanted it all to be on az functions, but they didn't want to).

Currently I'm calling several apis, storing the responses (poor man's blob/lake) and processing it.

I wanted to have it in this structure for folders

env_config for .env and other constants get_data for api calls. process_data export_data

I obviously would need to call env_config from get_data and quickly had the displeasure of learning about relative imports

After houra of googling and chating with people on the discord server, I can either make a pip -e package or one folder.

I honestly don't feel like messing with pip at all, and just having everything in one folder that way it will just work whether locally, container, server, or serverless.

My plan for organization is to have f01_ prefix and keep a readme of what each one means, so f01 would be config, f02 would be get data and so on.

Will I miss out on anything? Or would this cause any problems?

I'm the only python guy there, and I don't plan on shifting to SWE and packaging is just daunting for me even though it seems like 7 lines of code in myproject.toml.

Looking for opinions, I know that folders would be organized better, but With a map for prefixes shouldn't it be fine?

There will be many files, probably 15-30 modules, so a lot but not that crazy, and most won't be tpiched anyways

Thanks.


r/learnpython 2h ago

Distutils can’t find vcvarsall.bat even though I have MSVC

1 Upvotes

I did everything I added vcvarsall.bat to path, I tried using devoloper command prompt. I ran the command cl and everything is installed properly. I tried compiling it with both python 3.12 and 3.11.

Edit- I am trying to compile pygame source code


r/learnpython 2h ago

Are there any "Studying Platforms" (ex. for math) that are downloadable?

1 Upvotes

I'm looking for a downloadable math study platform, preferably one that's open-source with accessible code to modify. I need it for a class project, so any suggestions would be greatly appreciated. Thanks in advance!

(Or a guide on how to do it, preferably in Django)


r/learnpython 3h ago

Free APIs for Indian Stock Market Data (NSE/BSE)?

1 Upvotes

Hey all,
I’m working on a project involving Indian stocks (NSE/BSE) and need free APIs for company overviews, financial data (PE ratio, market cap, etc.), and historical prices. So far, I’ve checked:

  • Yahoo Finance API (limited for Indian stocks)
  • Alpha Vantage (limited)
  • Screener.in (manual access)

I’m looking for automated, free solutions to retrieve this data. Any suggestions for reliable APIs or scraping techniques?

Thanks!


r/learnpython 9h ago

How do i make this display in one screen without scrolling horizontally

3 Upvotes

I'm using pycharm and when I write some long description for the codes, i have to keep scrolling horizontally. I rememeber there was a way to "wrap" it in one page but I forgot how to do it. Help please?


r/learnpython 4h ago

Learning coding

0 Upvotes

I am am a grade 9 going into grade 10 ( freshman -> sophomore) and my future is being emphasised on heavily its not that im worry some about the future but more so aware of what space and who I want to be around I’ve always loved tech but never ever learnt to code I have no prior experience or knowledge and I need advice on how to learn it before the big holidays ( dec-jan for me) so i can pick subjects that can help me develop on my skills and have more understanding. I previously watched 10 hours of youtube videos and tutorials it gave me 0 understanding of any practical work or anything.To conclude what is the best coding language for beginners, how do I learn coding and where and what are some tips everybody has?


r/learnpython 20h ago

Should I really be learning OOP(specifically creating my own classes) at my current level, or skip it and come back when I'm more experienced?

15 Upvotes

So, I just finished "the basics" of python in terms of learning most important built-in stuff, like if, elifs, loops, def functions, lists, dictionaries, nesting aaaand stuff like that.

Made a few mini projects like guess number game, blackjack, coffee machine...

And right after those basics I was hit with OOP as "next thing" in the course and I feel it's like I've skipped 10 chapters in a book.

Maybe the course has not introduced me with any useful examples of using OOP. I don't understand what's it for, how is it useful and how creating classes is useful to me.

Current class I'm creating feels unnecessary. Feels like 5x more complicated than if I'd use the skills I already have to build the same thing. I'm basically still using all the basic built-in stuff, but wrapping it in a 2 different class python files, bunch of silly functions, and the word "self" repeating itself every 2nd line, I have same thing split to... eh it hurts me head trying to even explain it.

There is so much to remember too, because you essentially have a bunch of functions inside class, these functions have their own attributes, which correlate with what you'll use in the main file so you have to associate/imagine every single line with what you'll use it for and there's this whole branch of class ->function -> function attributes -> what functions does. Multiply it by 6, add 2 more just self __init__ attributes, and ..eh

Learning how to create OOP classes feels like something "extra" or "good-to-know" for a more experienced programmer, not at all for a newbie, either in terms of understanding, or in terms of using.

I have not yet touched a code where I have to connect so many dots of dots connected to many different dots, that also have to work with *some other* dots.

Alright, I think I'm done complaining.

Oh, wait no. There's one more dot. There we go

td;lr:

  1. Is it important to learn OOP?

  2. Is it important to learn creating my own classes for OOP?

  3. If the answers to above to questions are "Yes" - do you think a newbie is a sufficient level of expertise to learn this?


r/learnpython 9h ago

Need help to publish my python library !!

2 Upvotes

I have created an amazing python library which helps stock market traders , analysts and other people related to the financial sectors to scrape , visualize and conduct analysis on stock market data.This library is built on top of pandas , numpy ,dash , matplotlib , plotily etc. I recently tried to publish this using twine but due to some error the publish wont happen. I have successfully created a distribution of the package.

When I use twine for upload it asks for the API toke, when I upload the api token it shows some error. Can anyone guide me through it or suggest another method for uploading.


r/learnpython 17h ago

Nurse to Learning Python

8 Upvotes

Currently using a Udemy course to learn Python, AI, Data Engineering.

Has anyone made this or a similar transition? I am super nervous about this change! I want to feel competent but I’ve been told that could take up to 3 years!


r/learnpython 7h ago

I'm a beginner. I don't know what happened to my laptop but every time when I login to the cluster, it shows "Error while loading conda entry point: conda-libmamba-solver (libarchive.so.20: cannot open shared object file: No such file or directory)."

1 Upvotes

I've tried to delete and reinstall my environments, but this error message keeps popping up. Can anyone help???


r/learnpython 17h ago

Working on function to create new users for website, have a couple of questions

6 Upvotes

I'm currently working on the backend code (FastAPI and SQLite for database (SQLAlchemy)) for a website. I have a couple of questions about this function I've written:

# Create new user
def create_user(db: Session, user: schemas.UserCreate):
    # Hash password
    hashed_password = bcrypt.hashpw(user.password.encode("utf-8"), bcrypt.gensalt())
    # New user
    new_user = models.User(userID=user.userID, email=user.email, password_hashed=hashed_password.decode("utf-8"))
    db.add(new_user)
    db.commit()
    db.refresh(new_user)
    return new_user

It's my first time using FastAPI, SQLAlchemy, and stuff like bcrypt, so while I think I've learned most of it, I still have a bit of confusion on some parts.

Note: UserCreate is a pydantic model and models.User is part of my SQLAlchemy ("users" table). This function will be used in my FastAPI function for creating a new user. I have two questions about this code:

  1. Is db.refresh(new_user) actually necessary? I used multiple resources when learning and sometimes I saw db.refresh used and other times I just saw db.commit. Also, do I need to return new_user like I have right now? I don't know why I would need new_user after I call this function in my FastAPI function?

  2. I needed to hash the passwords before storing them, so I looked up some stuff on bcrypt. The first resource I looked at did password.encode("utf-8") when hashing the password and then decode("utf-8") when making the user (like I have right now). Most other places I've looked at don't use encode and decode and my code would just be:

hashed_password = bcrypt.hashpw(user.password, bcrypt.gensalt())

new_user = models.User(userID=user.userID, email=user.emai, password_hashed=hashed_password)

So I'm confused on which way I should do it.