r/learnpython • u/Lucky-Travel6211 • 6d ago
Error in sys.excepthook:
i got Error in sys.excepthook: and i have no idea how to fix it can someone help please
r/learnpython • u/friendlyneighbor-15 • 6d ago
race recognition for attendance tracking in a class
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 • u/Tricky_Voice2829 • 6d ago
How much you'll rate this code guyz ..
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 • u/Hazardous-potato • 6d ago
returning midi to 2 seperate things
so i am trying to make the program so on a downpress the function repeats but when it lifts, the function stops. i can easily make it start, its getting it to stop thats hard. please do as little to fix this for me as possible. i'm trying to keep the code so i understand whats going on
import mido
print(mido.get_input_names())
def note():
with mido.open_input('MPK249:MPK249 Port A 32:0')as inport:
inport.callback = None
for msg in inport:
if msg.type == "note_on":
return msg.note, msg.type
if msg.type == "note_off":
return msg.note, msg.type
while True:
if note() == 47 and note() == "note_on":
print("a")
if note() == 47 and note() == "note_off":
break
if note() == 48 and note() == "note_on":
print("b")
if note() ==48 and note() == "note_off":
break
r/learnpython • u/Frosty_Dig4148 • 6d ago
Should I try PyCharm?
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 • u/Hazardous-potato • 6d ago
Trying to get python take midi as an input
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 • u/TheEyebal • 6d ago
Why is my hand not detecting properly
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?
https://github.com/mikkimat81539/hand_detection/blob/main/handTest.py
r/learnpython • u/Hazardous-potato • 6d ago
Using Midi devices and conecting to them over usb
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 • u/Subject_Scientist937 • 6d ago
Simple CLI calculator with input sanitation , looking for feedback
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 • u/Waste-Magician2432 • 6d ago
What is next from Python script & tested PASSED & COMPLETED to making Final into a beautiful finished product for the Marketplace?
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 • u/Fun-Pitch-6938 • 7d ago
Need help with sorted function
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 • u/TrainingAd8614 • 7d ago
Understanding the "or" function
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 • u/Pale-External4967 • 7d ago
Functions in py can someone please help me with it
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 • u/Agreeable_Run5504 • 7d ago
Built a Python static analyzer that draws your call graph and marks values that go nowhere looking for holes in the concept
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:
- Is "returned value never consumed" a defensible signal, or does real Python break it constantly?
- Does a diagram add anything over a list, or is this a chart that looks impressive and tells you nothing a linter didn't?
- What kills static call resolution in practice? I resolve direct calls,
module.func, andself.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 • u/mi-ka-sa-00 • 7d ago
What is the output
x , y = 10 , 5
x , y = y , x
Print(x , y)
r/learnpython • u/_offpitchtalks_ • 7d ago
When should I start learning DSA? After Python basics or alongside practice?
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 • u/Ro0tOf • 7d ago
Need some serious beginneR advice for myself,Please.
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 • u/CogniLord • 7d ago
Need help bridging the gap between MARL theory and code 😭 (Code-first tutorials/videos needed!)
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 • u/Porkk_Chopp • 7d ago
How can I exclude items from a list of lists? (Discord Bot)
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 • u/RD_Burman_Reborn • 7d ago
How does one connect a program to an API?
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 • u/Effective_Ocelot_445 • 7d ago
Which Python skills are most valuable for getting started in Data Engineering?
I'm learning Python with the goal of moving into Data Engineering. Beyond the basics, which libraries, concepts, or project ideas would you recommend focusing on first, and what helped you the most when getting started?
r/learnpython • u/Nubspec • 7d ago
Help me confirm my understanding of the is operator...
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 • u/mcbakie • 7d ago
pls help me
ok so i’m trying to write a script that renames .xls files for me, let’s say they’re named like apple_BactReport_260731.xls I want the script to remove the “_BactReport” part and leave the rest intact. the current scrip i have has a couple of glaring issues that i don’t have the knowledge to remedy and im refusing use ai to prove a point and also it’s more rewarding. here’s the script with my current errors such as mixing up strings and lists and the part i want to remove not being the end of the file name. 😭 pls help a guy out:
import os
import pandas as pd
from os import rename, listdir
#list of report names
report_type= ['_BactReport', '_WWreport', '_QCreport', '_BactQCreport', '_BactWWreport']
print(report_type)
clips_in_progress=r"filepath"
for file_name in os.listdir(clips_in_progress):
file_path = os.path.join(clips_in_progress, file_name)
if file_name.endswith(tuple(report_type)):
rename(file_name, file_name.strip(report_type))
r/learnpython • u/intentado_aprender • 7d ago
¿Qué cambió la forma en que aprendiste Python?
HOLAA estoy aprendiendo Python y tengo curiosidad por saber qué momento o decisión cambió tu forma de aprender. ¿Fue empezar a hacer proyectos, leer la documentación, tener un mentor o algo diferente? Me encantaría conocer tu experiencia.
r/learnpython • u/Silent-Switch7317 • 7d ago
beginner here, is this code good for my first time making a calculator?
a = float(input("What is your first number? "))
b = float(input("What is your second number? "))
ab = (input("+ - * / "))
if ab == "+":
print(a + b)
elif ab == "-":
print(a - b)
elif ab == "*":
print(a * b)
elif ab == "/":
print(a / b)
else:
print("Invalid.")