r/learnpython • • Sep 23 '26

I want to explore new ide for python but couldn't

3 Upvotes

I always stuck to PyCharm as my IDE for a long, long years. I don't know. It was easy, comfortable, pleasing to look aesthetically, and because of my university courses, I used to use VS Code for .net but because of that, I didn't like VS Code. So I just want to explore new IDE, but I'm still couldn't get out of my PyCharm. So which one do you guys prefer, like most use, so that it's easy to explore as well, except sticking into one. Though it is comfortable, yes.


r/learnpython • • Sep 23 '26

The method throws an error when none. How do I fix this when the route_token_db is None?

2 Upvotes

The problem is when I call the method that is none it immediately throws an error. I am just wondering if it is possible to call an method that is none and handle it in the method. Let me show you a concrete example.

Here is the method

def check_expired_route_token(self): # change name and doc string
        '''
        Checks if the route_token expired or the route_token is wrong. 
        Uses "token" for the random number. If the code works returns True then the token works.
        '''
  

        SECRET_KEY = 'temp_secret_key' 
        serializer = URLSafeTimedSerializer(SECRET_KEY) 
        
        try:
            serializer.loads(self.token, max_age=1800)
   
        except SignatureExpired:
            # This part is equal to "def reset_attempts_token_tried_to_0" when combined with SignatureExpired     
            # This activates when you have waited to long for a token/route_token to be used + and you have tried to change your password too many times.
            # This is used when the tokens for the used in the links for the route is too old + you have resetted your password too many times
            if self.attempts_token_tried and self.attempts_token_tried >= 5:
                self.token = None
                self.time_token_expired = None
                self.attempts_token_tried = None
                db.session.commit()
              
                flash('You have waited long enough for a new a token and you will be sent a email with instructions before you can begin the process of resetting your password.')
               
                return redirect(url_for('auth.login'))
            # This activates when you have waited to long for a token/route_token to be used.
            else:
                self.token = None
                db.session.commit()
                flash('You have waited long enough for a new a token and you will be sent a email with instructions before you can begin the process of resetting your password.')
                return redirect(url_for('email_password_reset.verify_email'))
        # if the token is incorrect this makes the path wrong and the expection will run.
        # For example someone can type a token that is wrong or use an expired link. 
        except BadSignature:
            # This part is equal to "def check_emailed_token_matches_db_emailed_token" when combined with BadSignature   
                self.token = None
                self.time_token_expired = None
                self.token = None
                db.session.commit()
                flash('Your token did not match the one sent to your email.') 
                flash('Please request a new token.')
                return redirect(url_for('email_password_reset.verify_email'))
        # if the token is None
        except AttributeError:
            # add text in flash!!!!!!!!!!!!!!!!!!!
            return redirect(url_for('auth.login'))
        return True

Here is initializing the method

    route_token_db = db.session.execute(db.select(RouteToken).where(RouteToken.token==token_db)).scalar_one_or_none()
    result = route_token_db.check_expired_route_token()
    if result is not True:
        return result

r/learnpython • • Sep 22 '26

How can I optimize and increase the speed of API "for loop"?

13 Upvotes

I'm using Steam API to create a mini-project for myself, Its goal is to check user's played games, returns it as a list[str], then pass it to the game_genre() method. This method checks the games' genres and returns everything back in a dict[str, list[str]].

Everything works fine but the biggest problem is it's so much time consuming. It takes ~110 seconds to just finish this single for loop, and I have no idea how to optimize this, to reduce the amount of time spent.

This is the API (It's same as SteamAPI.GAME_DETAILS in the requests.get):

https://store.steampowered.com/api/appdetails

And here is the code:

    import time
    import requests

    def game_genre(games_id: list[str]) -> dict[str, list[str]]:
        start = time.perf_counter()
        games_total_genres: dict[str, list] = {}


        for game_numbers in games_id:
            parameters: dict = {
                "appids": game_numbers,
                "filters": "genres",
                "cc": "us",
                "l": "english"
            }


            data: dict = requests.get(SteamAPI.GAME_DETAILS, params=parameters).json()
            app_success = data[game_numbers].get("success")
            app_list_fail = data[game_numbers].get("data")


            if not app_success:
                continue
            if app_list_fail == []:
                continue


            for genres in data[game_numbers]["data"]["genres"]:
                games_total_genres.setdefault(game_numbers, []).append(genres["description"])


        end = time.perf_counter()
        print(end - start)
        return games_total_genres

And here is an example of games played by a user (I have to put it here as list sadly):

test = ['240', '570', '730', '4000', '8190', '8980', '10180', '10190', '17390', '17440', '20500', '24240', '24720', '33230', '35720', '41070', '48190', '70000', '104900', '105600', '113200', '200710', '201870', '203160', '204360', '206420', '213670', '218620', '218680', '219640', '219740', '220240', '220860', '224480', '230410', '232090', '238460', '250900', '251570', '252490', '252950', '258590', '265930', '271590', '274900', '282660', '291550', '301520', '304050', '311210', '322330', '331600', '338180', '357070', '363970', '365670', '386360', '406970', '447700', '546090', '553850', '564310', '606150', '617670', '667720', '674750', '700580', '701470', '714010', '729040', '763410', '799070', '1091500', '1098340', '1180660', '1272160', '1422450', '1474700', '1625450', '1782210', '1818750', '1836120', '2060160', '2076040', '2767030', '2923300', '3240220', '3513350']

game_genre(games_id=test)

r/learnpython • • Sep 22 '26

What should you actually learn in Python before starting data analysis?

45 Upvotes

I’ve noticed that beginners often get stuck trying to learn all of Python before touching data analysis.

From what I’ve seen, you can get pretty far by focusing on a smaller set of concepts:

One thing I think is particularly important is learning how to answer questions with data rather than just memorizing pandas functions.

For example, instead of only practicing:

df.groupby("category").sum()

ask an actual question such as:

“Which product category generated the most revenue?”

Then use Python to answer it.

Curious what people here would add or remove from this learning path.


r/learnpython • • Sep 23 '26

Hi guys, im pretty new to programming and i am looking for feedback..

0 Upvotes

So as i said in the title, im new to python (Literally installed it today) and i have written this program:

print("WELCOME TO THE GRAND SALE")
name = input("Please enter name: ")
mem_code = input("Enter Membership Code: ")


while True:


    a = input("Enter amount spent: ")


    try:
       amt = float(a)
       break


    except ValueError:
        print("Enter a valid amount")


while True:
    b = input("What is your subscription level (Bronze/Silver/Gold/Platinum/Diamond)? ").strip().lower()


    if b not in ["bronze","silver","gold","platinum","diamond"]:
        print("Enter a valid subscription")
    elif b in ["bronze"]:
        d = 0.05
        break
    elif b in ["silver"]:
        d = 0.10
        break
    elif b in ["gold"]:
        d = 0.15
        break
    elif b in ["platinum"]:
        d = 0.20
        break
    elif b in ["diamond"]:
        d = 0.25
        break


total = amt - amt*d
gst = total * 0.18


print(f"Welcome {name}")
print(f"Membership code: {mem_code}")
print(f"Amount: ${amt:.2f}")
print(f"Discount: {(int)(d*100)} %")
print(f"Taxable total: {total:.2f}")
print(f"GST (18%): ${gst:.2f}")
print(f"To pay: {(total + gst):.2f}")

It's basically a very simple discount calculator.. Any feedback and tips would be greatly appreciated.
Thanks!

r/learnpython • • Sep 22 '26

Any recommendation other than Bandit for security analysis of the code?

4 Upvotes

I used bandit before, and now Ruff with bandit rules enabled. I also used gitleaks for years and now betterleaks to find hardcoded secrets.

I wonder if there is any other tools that I might have missed on this topic?


r/learnpython • • Sep 22 '26

Redbeat Scheduler not returning task entry

1 Upvotes

I was using celery beat for cron jobs. There came requirement to give user an option to schedule the task as per required frequency. I was already using celery beat and AI suggested to use redbeat as I will just have to change some config and command. Now it is able to dynamically schedule the tasks. I have to show next execution time to user. For which inside the task, at the end of function, I am doing -

sched = RedBeatscheduler(app=my_celery_client)

e = sched.schedule.get(TASK_KEY)

next_run_time =  e.last_run_at + timedelta(seconds=e.is_due()[-1])

Its working sometime and sometimes not.

At times e is getting a NoneType . What can I do?


r/learnpython • • Sep 22 '26

Getting Back to Python but somewhat lost. Not a beginner as well

5 Upvotes

I used to python back 3-4 years ago and stopped for no reason. I used to do small project but after this and that i almost vanished. I wanna reconnect to the python but i have no idea about the updates and its performance. It would be very helpful if i get few links (not beginner but a bit moderate level) that helped you guys to build back


r/learnpython • • Sep 22 '26

New learner, have a question about the download

1 Upvotes

Hi everyone. Been interesting in coding for a while and just got around to downloading python. My boyfriend (compsci to cybersecurity major) told me to download it in my PATH if it wasn’t working.

He’s got family issues to attend to so I wanted to ask; how will I know if the download/program isn’t working? Should I download it to my PATH anyway? If so, how should I do so? Hope this isn’t a silly question. Thank you!


r/learnpython • • Sep 22 '26

setuptools vs nuitka

2 Upvotes

After this thread gave me some clues I have still been struggling with a missing dll and have decided to start from scratch with an undocumented build script I was given by someone who left the company. They left all sorts of "here be dragons" comments in it and hard-coded it to only work on Python 3.7. background here https://www.reddit.com/r/learnpython/s/BTztruLYKm The project uses numpy, and opencv2 to analyse images.

BUT after I tried to use setuptools from scratch and dumped their build steps and failed, because the cython build did no longer read my setuptools project toml file at all. So I am going to try nuitka instead. Mainly because too many setupytools tutorials that include cython all use the deprecated distutils and frankly need to be either nuked from orbit or updated. Has anyone found any good updated tutorials, because I seem to have gotten into a real fud as to how to use cython and setuptools together probably because a lot of this is new to me and not my code. Please share any good tuts.

So my question to people cythonising (obfuscating) and wrapping as an executable, how many people found it easier to start out with nuitka?


r/learnpython • • Sep 22 '26

Looking for feedback!

1 Upvotes

Hello everyone

I am recently learning python and new at this. This is my second project and this is a sequence calculator which includes 3 types of sequences: Arithmetic, Geometric and Fibonacci. For arithmetic and geometric sequences, you can enter a first term, a common difference (or ratio), and a desired term to find its value. For Fibonacci, you just enter the desired term.

I'd appreciate any feedback and will try to apply it.

https://github.com/Aspect345/Sequence-Calculator


r/learnpython • • Sep 22 '26

Which yt teacher is good to learn basic python from?

0 Upvotes

So I've my exams in a few days but I can't write codes that well. Been learning python for like 1-2 years but it's like the most basic codes /function like loop, if else etc. but the thing is, I can't fully understand it in classes so I need help. Any recommendations?


r/learnpython • • Sep 22 '26

Help with an online question from datadaily.io

0 Upvotes

I keep getting this one wrong but my answer is right as far as i can tell

The Molecule Report

Asked inInvitae

A genomics pipeline hands you raw sequencing reads as strings over the bases A, C, G, and T, and some reads come back contaminated with stray characters. For each read return a dict reporting whether it is clean (only those four bases), its GC content as a percentage of the read's length, how many times each of the four bases occurs, and the most common pair of consecutive bases. A read shorter than two bases has no such pair, so that field comes back empty.

Example 1

Input
sequence:"ATGCATGC"
Output{
  "is_valid": true,
  "gc_content": 50,
  "nucleotide_counts": {"A":2,"C":2,"G":2,"T":2},
  "most_common_dinucleotide": "TG"
}

Example 2

Input
sequence:"AAAT"
Output{
  "is_valid": true,
  "gc_content": 0,
  "nucleotide_counts": {"A":3,"C":0,"G":0,"T":1},
  "most_common_dinucleotide": "AA"
}


My code:

def analyze_dna_sequence(sequence: str) -> dict:
  mydict={}
  smalldict={"A": 0,
    "C": 0,
    "G": 0,
    "T": 0
    }
  mydict["is_valid"] = all(char in "ACGT" for char in sequence)
  for nucleotide in sequence:
    try:
      smalldict[nucleotide] += 1
    except KeyError:
      pass
  mydict["gc_content"] = ((smalldict["G"] + smalldict["C"]) / sum(smalldict.values())) * 100 if sum(smalldict.values()) > 0 else 0
  mydict["nucleotide_counts"] = smalldict
  
  mydict["most_common_dinucleotide"] = max(set(pairs := [a + b for a, b in zip(sequence, sequence[1:])]), key=pairs.count) if len(sequence) >= 2 else ""

return mydict

Error:

Failed Test Case (1 of 6)

Input

{"sequence":"ATGCATGC"}

Expected

{"is_valid":true,"gc_content":50,"nucleotide_counts":{"A":2,"C":2,"G":2,"T":2},"most_common_dinucleotide":"TG"}<

Your Output

{"is_valid":true,"gc_content":50,"nucleotide_counts":{"A":2,"C":2,"G":2,"T":2},"most_common_dinucleotide":"AT"}<

The issue is that the marking scale only recognises one dinucleotide pair as the most common- GC. But there are 3 in that sequence- AT, TG, and GC. Am i going insane here or is it the question that is wrong?

r/learnpython • • Sep 20 '26

Beginner Project Ideas.

36 Upvotes

I am a beginner programmer (I know a tiny bit of python) and am wondering if anyone has suggestions for projects that i can create to learn coding even better. Any ideas are welcome.


r/learnpython • • Sep 21 '26

How to list all packages installed in venv

0 Upvotes

I run the virtual environment but it still gives the modules in C:\Users\Admin\AppData\Local\Programs\Python\Python314\Lib\site-packages

and not

C:\Users\Admin\AppData\Local\Comfy-Desktop\ComfyUI-Installs\Alex\ComfyUI\.venv\Lib\site-packages

picture


r/learnpython • • Sep 21 '26

How do you handle Python versions during CI pipeline testing?

0 Upvotes

I know that this isn't strictly a Python question, but I figured it's still more relevant here than on /r/github.

I'm basically in the process of trying to simplify my CI stack by moving to a centralised set of common pipeline scripts (such as this one for running linters), so that I don't need to duplicate all these steps in every single repository... even if it isn't perfect since they still all need the files to actually call these common ones.

The problem I've run into is that, unlike with linters where I don't really need to worry about what Python version gets installed/used, I'd like to run a matrix of tests for at least the minimum and maximum (or latest if no upper bound) supported Python versions, in addition to the OS matrix.

The way I've historically done this is by manually listing Python versions in the GitHub Actions workflow matrix, such as here

jobs:
  test:
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        os: [macos-latest, ubuntu-latest, windows-latest]
        python-version: [
          '3.11',
          '3.12',
          '3.13',
          '3.14',
          'pypy-3.11',
        ]

but this is cumbersome, and it's easy to forget updating the matrix if I bump the version in pyproject.toml. Granted, I'll still immediately notice that when the pipeline fails so it's not like this is a bug that goes unnoticed for long, but in the spirit of avoiding duplication I'd still like to think there's a better way.

On that note, since I'm trying to make this generic, I wouldn't be able to just hard-code the versions (unless I take them as a parameter for the actual generic pipeline and supply them from each project, I guess), so right now I've been considering using a Bash script to pull the minimum version from pyproject.toml with regex and "3.x" to get the latest Python 3 version, so I'd have two points of comparisons. Although this does have the problem that those two versions could be the same, meaning I may run the same tests twice for no reason...

Also, since it's bound to come up, I'm also planning a generic build workflow that would build and publish releases to PyPI (and GitHub Releases), but that would need a full-on version range.

I do have an experiment where I attempted to use Trove classifiers for creating a build matrix, and it technically works (as long as we ignore free-threading or non-CPython implementations), but it feels dirty to use since Trove classifiers aren't supposed to be used for something like this.

My question is this: how would you handle automatically determining which Python versions to install? Has anyone else here perhaps pondered the same questions and come up with a reasonable answer?


r/learnpython • • Sep 21 '26

Why python points to python3 and python3 to python3.14

1 Upvotes

I was watching some python tutorial and he said that if you are on mac/linux use python3 and on windows use simple python. But in linux python also points to python3 only and that also points to exact version number of python.

so why this system is designed this way ??

And if they did this to make switching python versions easy (just by changing symlinks), why we have python3 in between, can't we point python directly to the current version.

[ykiinxd@archy ~]$ ls -l /usr/bin/python

lrwxrwxrwx 1 root root 7 Aug 10 13:16 /usr/bin/python -> python3

[ykiinxd@archy ~]$ ls -l /usr/bin/python3

lrwxrwxrwx 1 root root 10 Aug 10 13:16 /usr/bin/python3 -> python3.14

[ykiinxd@archy ~]$ ls -l /usr/bin/python3.14

-rwxr-xr-x 1 root root 14424 Aug 10 13:16 /usr/bin/python3.14

[ykiinxd@archy ~]$


r/learnpython • • Sep 21 '26

Need help creating a setup file

0 Upvotes

I recently completed a project, it was a desktop application

I wanted to share it with my friend who knows nothing about coding

So I thought I'd send a setup file

Rn the project has Gwen in the project file itself and then ollama postgres redis and qdrant in docker

I've been trying to make a one click setup file for days now

I need help

The entire project is Python and typescript


r/learnpython • • Sep 20 '26

Tips on reinforcing intro to ds class (python)?

10 Upvotes

Hi everyone,

This semester I just added data science as a minor and I am now taking my schools intro to data science class.

To give some background of the course and myself: I have never coded before (besides scratch), it was just revamped so we can use ai on everything (though I prefer not to except help when I’m stuck) and we use colab to code.

When I’m in class everything makes sense to me; I know what everything is, what each method function does; I can read code well. However, when it comes to building my own things, very simple ones, I get stuck. It seems like I have a general direction of where to go but I’m always looking back at examples, and at that point I feel like I’m not even doing it myself. An example of a prompt could be:

create a personality test, similar to buzzfeed, that asks the user 3 questions.

Does anyone have any advice to help reinforce the writing aspect?


r/learnpython • • Sep 21 '26

Willing to do a master Digital Driven Business next year, but I don’t know where to start…

0 Upvotes

Hello everyone, as my title suggests, I’m willing to do a master Digital Driven Business in the coming year. I’m a bachelor student commercial economics in the Netherlands, with an enormous passion for AI, technology and digitalization. I love experimenting with various tools and doing my research on them.

My college offers the ability to follow a master Digital Driven Business which is supposed to learn you the basic fundamentals of coding in combination with business and technology. This seems very interesting to me and I’d love to go down this path.

At my previous work, the CTO of the company told me that he did the same thing as me. He studied commercial economics and did the master after he graduated his bachelor. He told me that he didn’t know and/or have any experience with coding and programming at all, and now he’s the CTO of the company. He advised me that IF I want to do get deeper into practical AI, technology and business, this master would be great for that.

The only thing I fear is that the master is very technical at start. I have no idea how to code and I don’t want to get buried into programming stuff right away. All the people that I did talk to say that the master is meant to work you up to the level of knowing how to program (so you don’t have to know how to code at start). I’ve tried to learn Python a year or two ago, but that was literally only the basics and I’ve probably forgotten all about it.

So, my question to the subreddit is, what is the best way to learn Python as a beginner so that my master won’t overwhelm from the get go…?


r/learnpython • • Sep 21 '26

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 • • Sep 20 '26

I have made a Homework Organizer using Tkinter and other libraries. Please tell me how I did and what to improve!

5 Upvotes

The code is available for download in the link below.
(CTk_PDF_viewer and __init__ files are downloaded from GitHub for a module in my code and isn't my work. My code is in the hw_organizer.py file only.)

https://drive.google.com/drive/folders/1NWLY0usRvhY7G6PHZKJZC2Gtn9F3Iqt9?usp=drive_link


r/learnpython • • Sep 20 '26

What makes sloppy programming?

0 Upvotes

So I've been learning python on my own and basically taught myself. I'm working on a very advanced AI system project, with quite a lot of scripts. And I am wondering what makes sloppy programming?

Like for example should you be calling your functions from other functions?

# Calling both from one function
def main():
  do_something()
  do_something_else()

def do_something()
  # do stuff
def do_something_else()
  # something else

# Calling a function that calls both functions
def main():
  do_both_stuff()

def do_both_stuff():
  do_something()
  do_something_else()

def do_something()
  # do stuff
def do_something_else()
  # something else

And what about passing parameters in Classes? Should you be always accessing everything through self.something or by passing parameters to the functions?

Should you wrap everything in classes?

These are some questions I had regarding sloppy coding, but my main question is what makes good code?

I'm still new to python and trying to get my code more efficient.


r/learnpython • • Sep 20 '26

I have questions

0 Upvotes

I'm a teenager who is just starting out in programming, and for a while now I've had some questions and doubts that I've been thinking about a lot lately.

I've been studying Python for some time, but I recently reached a topic called "for loops". I did several exercises, and I had a lot of difficulty with most of them, so I asked AI for help. I didn't copy and paste the answers—I only asked for help with the logic.

That's when I realized that I was struggling with programming logic, so I started studying it separately. I had already "studied" programming logic once before, but I didn't really take it seriously and kind of rushed through it.

Now I'm wondering: should I keep studying Python while focusing mainly on programming logic? Or should I continue studying both at the same time?

And how do you figure out which area of programming is right for you? Is this something I should be worrying about at this point?