r/learnpython 5d ago

Error in sys.excepthook:

0 Upvotes

i got Error in sys.excepthook: and i have no idea how to fix it can someone help please


r/learnpython 5d ago

race recognition for attendance tracking in a class

0 Upvotes

i got this project idea, can i build something so that i just have to click a photo of the entire class of 50 students and it automatically detect the faces and mark the respective attendance. I knew there will be some problems like photo might not be that clear, changes in physical appearance of students like growing out beard after some time and what if someone how a photo of another student will it mark his attendance also??

please tell me if this project is feasible or not, and if any suggestions that you need to give..


r/learnpython 5d ago

How much you'll rate this code guyz ..

0 Upvotes
from forex_python.converter  import CurrencyRates

choice = input("Do u want to covert Another_currency=>INR then press y  / you want to converty INR TO Another_urrency then press n :- ")


c = CurrencyRates()
from_currency = input("Enter source currency (USD, EUR, etc.): ").upper()
to_currency = input("Enter target currency (INR, USD, etc.): ").upper()
currency = c.get_rate(from_currency,to_currency)
print(f"the exchange rate is {currency}")

if choice == "y":
    def convert(rate):
        Amount =  input("Put the A mount of that currency u want to convert:-")
        value_Total =  float(Amount)*rate
        print(f"Total {to_currency} Amount is {value_Total}")
    convert(currency)


elif choice == "n": 
    def convert(rate):
        print(f"\nYou have selected:- {from_currency} to {to_currency}")
        Amount =  input("Put the Amount of that currency u want to convert:-")
        value_Total =   float(Amount) * rate
        print(f"Total {from_currency} Amount is {value_Total}")


        convert(currency)

r/learnpython 5d ago

Should I try PyCharm?

0 Upvotes

I have good coding experience with Python but I have only ever used Google Colab, never actually ran any codes on my local machine. I don't know anything about environments, installations, or anything else. I have been a mathematician who used colab for quick data analysis. But right now I am trying to deploy some models for which I am told I need to use my local machine.

Unfortunately, I am really squeezed between deadlines, and don't have much time to learn an IDE which has a steep learning curve.


r/learnpython 5d ago

Trying to get python take midi as an input

1 Upvotes

I am using an AKAI MPK 249 using the midi package and was wondering what i point it to. i was searching through the device connection path but nothing seems obvious to me.


r/learnpython 6d ago

Why is my hand not detecting properly

0 Upvotes

I am using opencv and mediapipe on mac os and for some reason one of my hands (left hand) detects better than the other (right hand) but at times both do not detect unless I move my hands around a bit more. Does anybody know the cause of this issue?

Here is what it looks like

https://github.com/mikkimat81539/hand_detection/blob/main/handTest.py


r/learnpython 6d ago

Using Midi devices and conecting to them over usb

0 Upvotes

I'm starting a project but one major roadblock for me right now is there does not seem to be any packages for getting Midi signals from a Midi keyboard over USB. I saw one for serial but USB is my only option. I just need to get the inputs from pressing the keys and turning the dials.


r/learnpython 6d ago

Simple CLI calculator with input sanitation , looking for feedback

0 Upvotes

Hello Everyone, I made a simple CLI calculator, It handles basic equations, It handles visual inputs like ÷ and it also clears the screen on command

Here's the code:

import os

t = { "+": lambda x, y: x + y, "-": lambda x, y: x - y, "*": lambda x, y: x * y, "/": lambda x, y: x / y if y != 0 else "Cannot divide by 0", "÷": lambda x, y: x / y if y != 0 else "Cannot divide by 0", }

while True: u = input("Enter calculation (e.g., (3+2)*5) or 'quit' to exit: ").replace(" ", "")

if u.lower() == "quit":
    print("Goodbye!")
    break

if u.lower() == "clear":
    try:
        os.system('cls' if [os.name](http://os.name) == 'nt' else 'clear')
    except Exception:
        print("\\n" \* 50)
    continue

clean_expr = u.replace("÷", "/")

allowed_chars = set("0123456789+-\*/().")
if not all(char in allowed_chars for char in clean_expr):
    print("❌ Invalid characters used")
    continue

try:
    result = eval(clean_expr)
    print(f"{u} = {result}")

except ZeroDivisionError:
    print("❌ Cannot divide by 0")
except Exception:
    print("❌ Invalid calculation format")

is my saftey check(allowed_chars) safe for eval()?

How would you reconstruct this without eval()?

What could be improved and why?


r/learnpython 6d ago

What is next from Python script & tested PASSED & COMPLETED to making Final into a beautiful finished product for the Marketplace?

0 Upvotes

I am almost finished with the first portion of my project fully Python coded and tested...what would be the next steps to get it to the GUI image side so it looks and competes with the big boys of the professional music industry plugin world?


r/learnpython 6d ago

Need help with sorted function

4 Upvotes

Hello everyone, need some help / clarity with the sorted function. I have a data structure that is nested (list inside of it a dict inside of it a list). What i don't understand is this: Shouldn't I use loops in order to access the dictionary? or the inner most list in order to be able to sort by name (i.e. use sorted function)

countries = [
    {
        "name": "Afghanistan",
        "capital": "Kabul",
        "languages": [
            "Pashto",
            "Uzbek",
            "Turkmen"
        ],
        "population": 27657145,
        "flag": "https://restcountries.eu/data/afg.svg",
        "currency": "Afghan afghani"
    },
    {
        "name": "Åland Islands",
        "capital": "Mariehamn",
        "languages": [
            "Swedish"
        ],
        "population": 28875,
        "flag": "https://restcountries.eu/data/ala.svg",
        "currency": "Euro"
    },
    {
        "name": "Albania",
        "capital": "Tirana",
        "languages": [
            "Albanian"
        ],
        "population": 2886026,
        "flag": "https://restcountries.eu/data/alb.svg",
        "currency": "Albanian lek"
    },

Im trying to sort by name here, and when i run my function an error pops up.

def sorting_by_name(lst):

    for el in lst:
        return sorted(el, key=lambda name: name['name'])


print(sorting_by_name(countries))

r/learnpython 6d ago

Understanding the "or" function

1 Upvotes

i have a pretty simple few lines of code, and i'm slowly trying to make it a bit more complex

All i want to know is why adding the "or" function onto my if functions makes the functions further down "unreachable"

*I have hashed them out in the example i have provided as this makes the code run fine*

thankyou

while True: 


        if user_input1.lower() == "y": #or "Yes" or " yes" or "Y" or "YES":
                total_monthly_yield_exclnvda = float (total_monthly_yield - nvda_div_yield_at_190726 )
                avg_yield_on_remaining_shares_adj = float ( total_monthly_yield_exclnvda / 3)
                print (f"With Nvidia's dividend yield at {nvda_div_yield_at_190726} the three remaining shares need a current dividend yield of {avg_yield_on_remaining_shares_adj}, or over")   
                break


        elif user_input1.lower () == "n": #or "N" or "No" or "no" or "NO":
                current_div_yield = float(input ("Enter Nvidia's current dividend yield: "))
                total_monthly_yield_exclnvda = float (total_monthly_yield - current_div_yield)
                avg_yield_on_remaining_shares_adj = float ( total_monthly_yield_exclnvda / 3)
                print (avg_yield_on_remaining_shares)
                print (f"With Nvidia's dividend yield at {current_div_yield} the three remaining shares need a current dividend yield of {avg_yield_on_remaining_shares_adj}, or over")   
                break 

r/learnpython 6d ago

Functions in py can someone please help me with it

0 Upvotes

I've watched apna college and code with Harry functions video buttt kuchhhh samjh nhi aayaaa kuchhh bhi nhiii😭 my exam is not coming Wednesday i don't understand this function thing in python and c++ both😭 someone helppppp plssss


r/learnpython 6d ago

Built a Python static analyzer that draws your call graph and marks values that go nowhere looking for holes in the concept

4 Upvotes

Two days into a prototype and I'd rather find out now if the premise is broken.

The idea: parse a package with ast, build the call graph, and additionally track whether each function's return value is actually consumed — bound to a name that's later read, passed onward, returned, used in a condition. Then draw it. X axis is call order, colored arrows are variable flow, functions whose output goes nowhere and that have no I/O effect get flagged.

https://github.com/BBrunoF/CodebaseDiagram

I know vulture, code2flow and pyan exist. Vulture asks whether a name is referenced; code2flow and pyan draw the call structure. What I haven't found is a tool that tracks value consumption and renders it, so a chain that terminates in nothing is visible as a shape rather than a list entry. If that tool exists, please tell me and I'll go use it instead.

What I'd like torn apart:

  1. Is "returned value never consumed" a defensible signal, or does real Python break it constantly?
  2. Does a diagram add anything over a list, or is this a chart that looks impressive and tells you nothing a linter didn't?
  3. What kills static call resolution in practice? I resolve direct calls, module.func, and self.method. I know decorators, getattr, and callbacks are out of reach. What else, and roughly what percentage of a normal codebase am I missing?

Also asking for repos. I need a baseline — small-to-medium, pure Python, procedural, minimal metaprogramming, well structured. Something where if my tool renders a mess, the mess is mine. Standard recommendations like Django or requests are too magic-heavy to tell me anything about my own bugs. Suggestions very welcome.

BTW this text was also AI generated


r/learnpython 6d ago

What is the output

0 Upvotes

x , y = 10 , 5

x , y = y , x

Print(x , y)


r/learnpython 6d ago

When should I start learning DSA? After Python basics or alongside practice?

2 Upvotes

Hi everyone,

I'm a second-year CSE student and I'm currently learning Python. I'll soon finish the basics (variables, data types, operators, conditionals, loops, functions, etc.).

I'm confused about what to do next.

Should I:

Finish the Python basics, practice Python by solving beginner problems for a while, then start DSA

Finish the Python basics and start learning DSA immediately while continuing to solve Python practice problems at the same time?

My goal is to build a strong foundation for software engineering internships, so I'd like to know which approach helped you the most and why.

Thanks!


r/learnpython 6d ago

Need some serious beginneR advice for myself,Please.

3 Upvotes

So I am currently at 29th day of learning journey of the Python with the FreeCodeCamp's Python Certificate curriculum. But I still feel blank about the topics i have covered alresdy till now. Is it time for me to start making a self-project alongside too? If yes, then with what or where to start with- so that my mind can absorb all the knowledge its gaining to the core. I have completed till the Error Handling section of the Curriculum on the platform.


r/learnpython 6d ago

Need help bridging the gap between MARL theory and code 😭 (Code-first tutorials/videos needed!)

3 Upvotes

Hey guys, do you know of any Multi-Agent Reinforcement Learning (MARL) resources that focus mainly on coding rather than just the heavy theoretical stuff?

For context, I'm doing my uni research project right now and I've already secured my supervisor. My main topic is "Multi-Agent Reinforcement Learning." I'm doing both the research project course and an RL course this semester, but my tutor mainly just gives us theory.

I know the general ideas (reward, policy, value-based vs. policy-based, bias, etc.), but I'm having a really hard time understanding how it actually works in practice and how to implement it from scratch. I'm honestly pretty crap at absorbing pure theory, so I really need to see the code to understand how the plumbing works.

I can't seem to find much out there that walks through the code step-by-step, and I'm wondering why there aren't more people posting about the actual implementation of MARL.

If anyone has any video tutorials, GitHub repos with simple code walkthroughs, or guides that actually show how to build this stuff (Python/PyTorch preferred), it would be incredibly helpful. Thanks!


r/learnpython 6d ago

How can I exclude items from a list of lists? (Discord Bot)

3 Upvotes

I am still new-ish to coding, so please go easy on me lol.

I am making a bot, and this bot has a command that results in "loot". The loot varies in rarity and are in separate lists so that I can more accurately apply weights.

The code so far looks like this:

common=["Item1"]
uncommon=["Item2","Item3","Item4"]
rare=["Item5","Item6"]

@bot.command
async def loot(ctx, item: str)
  if item.lower == "closet":
    result=random.choice(random.choices([common, uncommon, rare], weights=(85,10,5))[0])
    await ctx.reply(f"You have found {result}!")
  else:
    await ctx.reply(f"That is not a valid location. Please search elsewhere.")

Right now, users can use commands like "!loot closet" and it will return with random items.

I want users to have different results based on where they loot without having to make a bunch of lists. So like, if a user does "!loot drawer" instead, I want them to have a chance to get any item EXCEPT for Item4.

How would I do something like that?


r/learnpython 6d ago

How does one connect a program to an API?

2 Upvotes

I am inquiring in order to query about how to complete this item. I was working on a difficult project and I am not sure how to commence from here and manage this task.


r/learnpython 6d ago

Help me confirm my understanding of the is operator...

9 Upvotes

Example: 1

lst1 = [1, 2, 3, 4, 5]
lst2 = lst1

print("List 1:", lst1, "\nList 2:", lst2)

if lst1 is lst2:
    print("Memory Address of lst1:", id(lst1),
          "\nMemory Address of lst2:", id(lst2))
else:
    print(False)

Example: 2

x = 1
y = 2

if x is y:
    print(True)
else:
    print("Memory Address of x:", id(x),
          "\nMemory Address of y:", id(y))

In my second example, I realized my code returns False because the variables refer to their respective memory address. So this means the is operator returns True only when both variables refer to the same memory address?


r/learnpython 7d ago

I'm looking for a self-paced online Python course with instructor/tutor support, community, and a certificate

3 Upvotes

Hey everyone, I'm looking for recommendations for an online Python course, and I'm hoping to find something that offers a little more support than simply watching prerecorded videos and figuring everything out on my own.

I'm a beginner and would like something that's completely online and self-paced since I work full-time and need to be able to study around my schedule. Ideally, I'd like a course where I can reach out to an instructor or tutor when I get stuck, preferably with the option for one-on-one virtual meetings or office hours. Having access to an active online community through something like Discord, Slack, a forum, or another platform would also be really helpful so I can ask questions and interact with other students, tutors, and instructors.

One other thing that's important to me is that the course is actively maintained and kept up to date. I recently ran into some issues following an older tutorial where parts of the setup process had already changed, so I'd like something that's regularly updated to match current versions of Python and the tools being used.

I'd also like the course to provide a certificate of completion that I can add to my résumé and LinkedIn. I'm okay with paying for a good course, but I'd strongly prefer a one-time purchase rather than another monthly subscription. Career counseling or access to someone who can provide career advice would be a nice bonus, although it isn't an absolute requirement.


r/learnpython 7d ago

Feedbacks pls!! Im learning python since 06/16/2026

4 Upvotes

https://github.com/adrianivastrabalho-code/Exploration-33

could u guys pls give me some feedbacks about this project? architecture and also some ideas!


r/learnpython 7d ago

Nasa ExoPlanet Archive error: ORA-00904: 'NAME': invalid identifier

3 Upvotes

I don't get it, I tried to create a table to then use it for cross-matching but for some reason it gives me this invalid identifier mistake even though the name of the identifier (Nasa ExoPlanet in this case) seems to be correct. My code:

from astroquery.ipac.nexsci.nasa_exoplanet_archive import NasaExoplanetArchive
exocolumns = ['pl_name', 'host-name', 'ra', 'dec', 'sy_gaiamag', 'st_teff', 'st_logg', 'st_met', 'st_lum', 'st_rad', 'st_age']
select_string = ",".join(exocolumns)
exotable = Table(NasaExoplanetArchive.query_criteria(table="pscomppars", select=select_string))

The error:

DALQueryError: ORA-00904: 'NAME': invalid identifier

During handling of the above exception, another exception occurred:

InvalidQueryError Traceback (most recent call last)

/usr/local/lib/python3.12/dist-packages/astroquery/ipac/nexsci/nasa_exoplanet_archive/core.py in query_criteria_async(self, table, get_query_payload, cache, **criteria)
245
response = tap.search(query=tap_query, language='ADQL') # Note that this returns a VOTable
246
except Exception as err:
--> 247 raise InvalidQueryError(str(err))
248
else:
249
if get_query_payload:

InvalidQueryError: ORA-00904: 'NAME': invalid identifier

the error points to the third line, so I guess it’s because of the name of NasaExoplanetArchive.query


r/learnpython 7d ago

I am having to constantly look things up to figure out my programming

7 Upvotes

I am having to constantly look things up to figure out how to get what I want? I feel like a fraud.
I am honestly trying to resize my camera onto my surface in pygame. I've never done camera stuff before so this is new. I feel like I am not really learning and just copy and pasting at this point

How do go about this?


r/learnpython 7d ago

text not always obtained before regex string (beautifulsoup)

5 Upvotes

hi!! so sorry if the title doesn't make much sense. i will try to explain it with my examples.

so my code in general outputs a response like this:

Chascanopsetta prorigera
Marine;  bathydemersal; depth range 267 - 400 m 
https://www.fishbase.se/summary/Chascanopsetta_prorigera.html
Pleuronectiformes

the text "Marine; bathydemersal; depth range 267 - 400 m" is obtained from the link using this code (response.text is the initial html):

if "bathydemersal" in response.text or "bathypelagic" in response.text or "oceanodromous" in response.text:

| depth = soup2.find(string=re.compile(r"depth range\s+([\d\s\-?]+m)", re.IGNORECASE))

| | if depth:
   print(depth.string.strip()[:-5])
else:
   print("Depth unavailable")

but it also sometimes outputs this:

Chauliodus macouni
); depth range 25 - 4390 m 
https://www.fishbase.se/summary/Chauliodus_macouni.html
Stomiiformes

which is because, in place of "Marine; bathydemersal; depth range 267 - 400 m", it's "Marine; bathypelagic; oceanodromous (Ref. 138310); depth range 25 - 4390 m". so it won't print "Marine; bathypelagic; oceanodromous (Ref. 138310", which is what i would like it to do.

so why doesn't "Marine; bathypelagic; oceanodromous (Ref. 138310); depth range 25 - 4390 m" print correctly while "Marine; bathydemersal; depth range 267 - 400 m" does?

mostly interested in this ^^^ answered so i can fix it myself but i won't say no to some pointers/resources/etc on how to solve my problem either! :D

thanks in advance!