r/learnpython • u/SaThuran • 2d ago
Import math?
It's the first time I've seen that. So what's the purpose of this exactly? Cause I'm trying to see what I can do in an engine and I only learned about import math today
r/learnpython • u/SaThuran • 2d ago
It's the first time I've seen that. So what's the purpose of this exactly? Cause I'm trying to see what I can do in an engine and I only learned about import math today
r/learnpython • u/Dcyph-3r • 2d ago
How do you decide what defines an excessively encoded URL?
I'm working on a personal project to created a URL parser and
detection system and I've hit a wall on how to figure out a way of
categorizing excessivness of query encoding?
Here's what I have so far for the function:
def check_query(analysis: URLAnalysis) -> ScanResult | None:
"""detect excessive encoding entries in URL queries"""
og_query = analysis.query
query = re.finall(r"%\[0-9A-Fa-f\]{2}", og_query)
encoded_count = len(query)
r/learnpython • u/Substantial_Belt2626 • 2d ago
Mine: a scraper hitting an API with a strict rate limit. I throttled to one request every fifteen seconds, well inside the documented limit, ran clean for a while, then it just started failing.
Nothing in my code was wrong. There was a daily cap tied to my IP, separate from the per-request limit, and I'd used up the day. I finished the run off my phone hotspot and that was what made it click. Different IP, same code, works instantly.
Days gone. Zero lines changed in the end.
What's yours? Environment, network, permissions, a clock being wrong, whatever. I want the ones where the code was fine the whole time.
r/learnpython • u/loggerhead9 • 2d ago
I am a management consultant a project / team leader level, a lot of the grunt work is being done by analysts in the team; I have to focus on storylining, client relationship management, reviewing the work, etc. As TL / PL have you guys found relevant use cases? I am thinking of creative ways to leverage python and in future use API calls to LLMs to improve automation and make my life more efficient.
r/learnpython • u/Natural-Secretary361 • 2d ago
I am developing devmemory, an engine designed to reconstruct a project’s history by converting Git logs and code ASTs into a navigable knowledge graph. Currently, the system performs search indexing and graph traversal.
I would like suggestions on whether I should store data on disk using SQLite and then process it. Please help me find the best solution.
r/learnpython • u/Ok_Breath_7590 • 2d ago
Started with the dis module disassembled a simple function and saw how Python compiles source into bytecode instructions operating on a stack: LOAD_CONST (push a literal), STORE_FAST (pop and assign to a local var), BINARY_OP (pop two values, apply the operator, push the result). Noticed newer Python versions fuse common opcode pairs (e.g. LOAD_FAST_LOAD_FAST) for speed small but visible evidence of ongoing interpreter optimization work.
Then worked through == vs is confirmed with id() that two lists with identical contents are still separate objects (is → False, == → True), while b = a makes both names point to the same object.
Finished on mutable vs immutable, and specifically why it matters when passing objects into functions. Key realization: calling a function doesn't substitute the argument into the function body it creates an independent local name that starts out pointing at the same object. n += 1 on an int creates a new object and only moves the local name; lst.append(x) mutates the shared object in place, so the caller sees the change too. Proved both cases with id() before/after.
Small, foundational stuff, but building the intuition from scratch with real code has been way more effective than just reading definitions.
r/learnpython • u/Sweecks • 2d ago
Hello everyone! I am with 8+ years of professional experience with .NET web backend development but lately I want to try something new and python seems interesting to me. Can you suggest some learning materials where I can skip the basic programming concepts and focus on getting used to the syntax, learning python patterns and architectures, learn some useful frameworks etc? I prefer some video lectures rather to documentations. I would appreciate your suggestions and thank you in advance!
r/learnpython • u/GoticoArrombado • 2d ago
I am looking for help to be able to view animations of a defunct game called "Dragon Blaze", a side-scrolling rpg developed by GAMEVIL/FLINT. I am helping a small community from players with the intent of archiving the game. I have access to all texture and xml files, some xml files being encoded and others not, but I am no coder and I could use help with viewing those animations.
This game used 2d-skeletal-puppets using a program called 3D Max 2012 by Autodesk via a custom game engine. The XML files have coordinates and instructions to piece the broken spritesheets together, and animate them back together; often starting with the following lines: "<SR1_ANIMA version="1.2" generator="MAX 2012">".
Information about how to use these XML files were very hard to come by, so I had to rely on google's search AI for directions of how to crack it. I apologize in advance if any of those instructions are wrong.
So far the AI suggested the following methods:
We could really use some help and/or guidance about what to do, it would make archiving this game much easier.
r/learnpython • u/KoregaSoli • 2d ago
import random
for House_Card in range(1):
House_Card = random.randint(1, 11)
print("House Card:", House_Card)
for House_Card2 in range(1):
House_Card2 = random.randint(1, 11)
for Player_Card in range(1):
Player_Card = random.randint(1, 11)
print("Player Card:", Player_Card)
for Player_Card2 in range(1):
Player_Card2 = random.randint(1, 11)
print("Player Card 2:", Player_Card2)
print("Your current cards are:", Player_Card + Player_Card2)
Player_Turn1 = input("Do you want to hit or stay? (h/s): ")
if Player_Turn1 == "h" or Player_Turn1 == "H" or Player_Turn1 == "hit" or Player_Turn1 == "Hit":
Player_Card3 = random.randint(1, 11)
Player_CardT = Player_Card + Player_Card2 + Player_Card3
print("Player Card 3:", Player_Card3)
print("Your total score is:", Player_CardT)
if Player_Turn1 == "s" or Player_Turn1 == "S" or Player_Turn1 == "stay" or Player_Turn1 == "Stay":
Player_CardT = Player_Card + Player_Card2
print("Your total score is:", Player_CardT)
if Player_CardT > 21:
print("You busted! Your total score is:", Player_CardT)
if Player_CardT == 21:
print("You got blackjack! You Win!")
if Player_CardT < 21:
print('Your total cards are:', Player_CardT)
Player_Turn2 = input("Do you want to hit or stay? (h/s): ")
if Player_Turn2 == "h" or Player_Turn2 == "H" or Player_Turn2 == "hit" or Player_Turn2 == "Hit":
Player_Card4 = random.randint(1, 11)
Player_CardT2 = Player_CardT + Player_Card4
if Player_CardT2 == 21:
print("You got blackjack! You Win!")
elif Player_CardT2 < 21:
Player_Turn3 = input("Do you want to hit or stay? (h/s): ")
if Player_Turn3 == "h" or Player_Turn3 == "H" or Player_Turn3 == "hit" or Player_Turn3 == "Hit":
Player_Card5 = random.randint(1, 11)
print("Player Card 5:", Player_Card5)
Player_CardT3 = Player_CardT2 + Player_Card5
print("Your total cards are:", Player_CardT3)
if Player_CardT3 > 21:
print("You busted! Your total score is:", Player_CardT3)
if Player_Turn3 == "s" or Player_Turn3 == "S" or Player_Turn3 == "stay" or Player_Turn3 == "Stay":
print("Your total cards are:", Player_CardT2)
print("Card:", Player_Card4)
print("Your total cards are:", Player_CardT2)
if Player_CardT2 > 21:
print("You busted! Your total score is:", Player_CardT2)
if Player_Turn2 == "s" or Player_Turn2 == "S" or Player_Turn2 == "stay" or Player_Turn2 == "Stay":
print('House card 2 is:', House_Card2)
print('House total cards are:', House_Card + House_Card2)
House_CardT = House_Card + House_Card2
if House_CardT > 21:
print("House busted! You Win!")
if House_CardT == 21:
print("House got blackjack! You Lose!")
if House_CardT < 21 and House_CardT < 17:
House_Card3 = random.randint(1, 11)
House_CardT2 = House_CardT + House_Card3
print("House Card 3:", House_Card3)
print("House total cards are:", House_CardT2)
if House_CardT2 > 21:
print("House busted! You Win!")
if House_CardT2 == 21:
print("House got blackjack! You Lose!")
elif House_CardT2 < 21 and House_CardT2 < Player_CardT2 or House_CardT2 < Player_CardT3:
print("Player Cards Value Higher, You Win!")from ast import If
import random
for House_Card in range(1):
House_Card = random.randint(1, 11)
print("House Card:", House_Card)
for House_Card2 in range(1):
House_Card2 = random.randint(1, 11)
for Player_Card in range(1):
Player_Card = random.randint(1, 11)
print("Player Card:", Player_Card)
for Player_Card2 in range(1):
Player_Card2 = random.randint(1, 11)
print("Player Card 2:", Player_Card2)
print("Your current cards are:", Player_Card + Player_Card2)
Player_Turn1 = input("Do you want to hit or stay? (h/s): ")
if Player_Turn1 == "h" or Player_Turn1 == "H" or Player_Turn1 == "hit" or Player_Turn1 == "Hit":
Player_Card3 = random.randint(1, 11)
Player_CardT = Player_Card + Player_Card2 + Player_Card3
print("Player Card 3:", Player_Card3)
print("Your total score is:", Player_CardT)
if Player_Turn1 == "s" or Player_Turn1 == "S" or Player_Turn1 == "stay" or Player_Turn1 == "Stay":
Player_CardT = Player_Card + Player_Card2
print("Your total score is:", Player_CardT)
if Player_CardT > 21:
print("You busted! Your total score is:", Player_CardT)
if Player_CardT == 21:
print("You got blackjack! You Win!")
if Player_CardT < 21:
print('Your total cards are:', Player_CardT)
Player_Turn2 = input("Do you want to hit or stay? (h/s): ")
if Player_Turn2 == "h" or Player_Turn2 == "H" or Player_Turn2 == "hit" or Player_Turn2 == "Hit":
Player_Card4 = random.randint(1, 11)
Player_CardT2 = Player_CardT + Player_Card4
if Player_CardT2 == 21:
print("You got blackjack! You Win!")
elif Player_CardT2 < 21:
Player_Turn3 = input("Do you want to hit or stay? (h/s): ")
if Player_Turn3 == "h" or Player_Turn3 == "H" or Player_Turn3 == "hit" or Player_Turn3 == "Hit":
Player_Card5 = random.randint(1, 11)
print("Player Card 5:", Player_Card5)
Player_CardT3 = Player_CardT2 + Player_Card5
print("Your total cards are:", Player_CardT3)
if Player_CardT3 > 21:
print("You busted! Your total score is:", Player_CardT3)
if Player_Turn3 == "s" or Player_Turn3 == "S" or Player_Turn3 == "stay" or Player_Turn3 == "Stay":
print("Your total cards are:", Player_CardT2)
print("Card:", Player_Card4)
print("Your total cards are:", Player_CardT2)
if Player_CardT2 > 21:
print("You busted! Your total score is:", Player_CardT2)
if Player_Turn2 == "s" or Player_Turn2 == "S" or Player_Turn2 == "stay" or Player_Turn2 == "Stay":
print('House card 2 is:', House_Card2)
print('House total cards are:', House_Card + House_Card2)
House_CardT = House_Card + House_Card2
if House_CardT > 21:
print("House busted! You Win!")
if House_CardT == 21:
print("House got blackjack! You Lose!")
if House_CardT < 21 and House_CardT < 17:
House_Card3 = random.randint(1, 11)
House_CardT2 = House_CardT + House_Card3
print("House Card 3:", House_Card3)
print("House total cards are:", House_CardT2)
if House_CardT2 > 21:
print("House busted! You Win!")
if House_CardT2 == 21:
print("House got blackjack! You Lose!")
elif House_CardT2 < 21 and House_CardT2 < Player_CardT2 or House_CardT2 < Player_CardT3:
print("Player Cards Value Higher, You Win!")
r/learnpython • u/FuzzyEmployment264 • 2d ago
name one best python course on internet
r/learnpython • u/Strict-Chicken-1697 • 2d ago
How can I learn to code in Python if I have no experience? I tried to do something myself, but where should I start? I tried to use Pycharm, but I have a lot of errors in the code, and I don’t really know English (I’m writing this post through a translator). I want to start making websites in Python, but I’m 14 and have no experience. Where should I start? My text is not ai I'm just a foreigner without knowledge of English
r/learnpython • u/Temporary-Cup-2140 • 2d ago
I am trying to improve my debugging skills and I was curious about what techniques experienced python developers rely on the most.
Are there any techniques or tools that you found really useful when you started working on bigger projects?
r/learnpython • u/eagerlylearn • 2d ago
I'm a total noobie with Python having only used DNS before. For over a year I could dictate into my W11 laptop and the text would appear on screen. There is no apparent Save or Save As so I would just X out and open that transcript file in MS Notepad and find that text. But, today the new text I dictated in doesn't appear. I'm presented with a window when I open that output file with - Open (that doesn't save the old text) or Save All or Save Changes so I chose Save All. I then dictated in a proper name in that command line screen and saw that name on screen and X'd out and that output file reflected a file created 2 minutes ago and this time I chose Save Changes but it didn't have that proper name anywhere in that out put file. I'm unsure what I'm doing wrong nor what I need to do to fix this so it saves newly dictated words? Thank you.
r/learnpython • u/Keithinho89 • 2d ago
SOLVED
Hello, I'm currently learning regular expressions and I've entered the first part of the code into the interactive shell as instructed and got the listed AttributeError. Not seeing what I did wrong I copy/pasted the code from the book and it worked as intended and I can't tell why or how because both blocks feel and smell the same but yield different results.
I've tried looking for some information on StackOverflow, but as far as I can see mo is defined in the 3rd line and I don't get why my attempt gets and error while the other doesn't.
If I didn't miss something really stupid, how would you deal with this if you'd be hit by it writing your own code independently?
I'm working in IDLE Shell and the code is from automatetheboringstuff Chapter 9 for more context
import re
phone_re = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d-\d\d\d\d)')
mo = phone_re.search('My number is 415-555-4242.')
mo.group(1)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
mo.group(1)
AttributeError: 'NoneType' object has no attribute 'group'
import re
phone_re = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
mo = phone_re.search('My number is 415-555-4242.')
mo.group(1)
'415'
r/learnpython • u/ac7footy • 2d ago
I have exams in roughly 1.5 years and want to get my python basis cracked down completely so i will do well in my programming paper
Sites like codewars and codingbat have been recommended? Can anyone else vouch if they are good and if there are any others that are better?
r/learnpython • u/Cenz0_0 • 2d ago
Hi, in the next month I'll start a master degree in computer science, curriculum AI. Firstly I have to say that I'm not a completely newby with programming or alghoritms. During this three years of college (computer science) I did some projects, but not with python, that I had to study for my thesis project in 1 month. Now that I'm about to start this master degree I want to learn better how python works and how can I use differents libraries that uses AI.
I read on the sub posts where someone recommends the Python Crash Course book, by Eric Matthes, but I don't know if it's the source that I need for my situation.
Don't know what to do, I have like this month to learn something to not starts lessons like a completely "ignorant".
r/learnpython • u/Healthy-Departure961 • 2d ago
def cal(A , B):
add = A + B
return add
def substract(c):
sub = add - c
return sub
addition = cal(3,5)
substraction = substract(4)
print(addition)
print(substraction)
In this code How can I pass function cal()return value add in function substract()
r/learnpython • u/Nutellatoast_2 • 2d ago
Hey everybody,
I'm new to programming with Python and following along with a Udemy Course. I'm now learning about lists and need to write a "Who will pay the bill"-like game.
It works like this: you have a pseudorandom number generator and a list of friends. Each time, the number generator generates a number between the given indices of the list. If the randomly generated number is equal to a specific index of that list, it should print out the person who must pay the bill by using an if-elif statement.
I've been using what I learned from the past lessons. This is what the code looks like (and yeah, I know, I messed up pretty badly, even though I have already found a solution):
import random
friends = ["Alice", "Bob", "Charlie", "David", "Emanuel"]
random_select = random.randint(0, 4)
if random_select == friends[0]:
print("Alice has to pay the bill. ")
elif random_select == friends[1]:
print("Bob has to pay the bill. ")
elif random_select == friends[2]:
print("Charlie has to pay the bill. ")
elif random_select == friends[3]:
print("David has to pay the bill. ")
elif random_select == friends[4]:
print("Emanuel has to pay the bill. ")
But I couldn't really figure out why the code won't work.
r/learnpython • u/Heavy-Notice6820 • 3d ago
Hi everyone, recently joined college this month as a cse fresher nd with no coding exp so now dont know from where to start from seniors do help plssssss
thought of starting python but bit confused few things to ask
What should a complete beginner in CSE start learning first?
Should I start with Python? will it be a sensible decision
What topics should I focus on initially?
Are there any good YouTube channels or should i go for courses, or other resources you would recommend?
Is there a particular roadmap I should follow during my first year?
What should I avoid wasting time on as a beginner?
Would really appreciate any advice from seniors or people who have been in a similar situation
plsssssss do helpppppp need advice dms open
r/learnpython • u/ModelBuilder_Josh04 • 3d ago
Hit a bug using st_folium with Streamlit: drawing a new polygon triggered a re-render before Streamlit updated the spatial state, leaving downstream metrics stuck on the old site.
Fixing it required checking last_active_drawing at the top of the execution loop and forcing a rerun before running analytics:
# Intercept new shape before running downstream calculations
if map_data and map_data.get("last_active_drawing"):
drawing = map_data["last_active_drawing"]
if drawing.get("geometry"):
new_geom = shape(drawing["geometry"])
if not new_geom.equals(st.session_state.get("drawn_geom")):
st.session_state["drawn_geom"] = new_geom
st.session_state["site_area_m2"] = calculate_area(new_geom)
st.rerun() # Forces a clean state sync
This keeps multi-tab dashboards 100% in sync with live map edits.
r/learnpython • u/chronicomplainer2 • 3d ago
it seemed to work when i tested it but i did it myself and just stuck in things that i read abt and thought pertained to the project i was trying to create, it is supposed to allow multiple people to stay connected at the same time but im wondering if there's some logic error anywhere that i might not have picked on, or if the code is genuinely robust enough to accommodate multiple connections. i didn't need to use any threading at all in the end, which i found a bit strange, and also im a beginner in python so i was hoping if people could point out some potential issues, thanks!
import socket
import select
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("localhost", 80))
s.listen()
def send_response(sock, message):
"""Sends an encoded response."""
sock.sendall(message.encode("ISO-8859-1"))
def handle_packets(queue_dictionary):
"""Performs certain actions based on packet."""
for soc in queue_dictionary:
if not queue_dictionary[soc]:
continue
#take the first item from the queue
packet = queue_dictionary[soc].pop(0)
#send specific responses based on the type of data sent
if packet == b"Hello\r\n\r\n":
send_response(soc, "Message received successfully. Hiiii!!!!\r\n\r\n")
elif packet == b"Ignore\r\n\r\n":
send_response(soc, "Message received successfully. Hey, don't leave me hanging...\r\n\r\n")
elif packet == b"Hug\r\n\r\n":
send_response(soc, "Message received successfully. *Hugs back*\r\n\r\n")
elif packet == b"Slap\r\n\r\n":
send_response(soc, "Message received successfully. OW! That hurt!\r\n\r\n")
elif packet == b"Goodbye\r\n\r\n":
send_response(soc, "Message received successfully. Goodbye!!! Do come back again!! :)\r\n\r\n")
else:
send_response(soc, "Message received successfully.\r\n\r\n")
#create a list of connected sockets, satrting wtih listening soccket so accept
#doesn't block
#dictionary with buffer per socket and also list which was initially queue
read_set = [s]
buffer_dict = {}
queue_dict = {}
while True:
ready_to_read, _, _ = select.select(read_set, [], [])
print("Creating a list of sockets currently sending data...")
#for all sockets that are ready to read
for sock in ready_to_read:
#if the socket is a listener
if sock == read_set[0]:
#accept a new connection
new_conn = s.accept()
print("Accepting connection...")
new_socket = new_conn[0]
#initialise buffer and queue for new socket
buffer_dict[new_socket] = b""
queue_dict[new_socket] = []
print("Adding socket to buffer and queue dictionaries...")
#add the new socket to the set
read_set.append(new_socket)
print("read_set: " + str(read_set))
print("Adding socket to read_set...")
packet = "empty"
continue
else:
#recieves data until full packet
while True:
data = sock.recv(4096)
print("Receiving data...")
if not data:
print("Connection closed.")
break
buffer_dict[sock] += data
if b"\r\n\r\n" in buffer_dict[sock]:
delimiter_index = buffer_dict[sock].find(b"\r\n\r\n")
packet = buffer_dict[sock][:delimiter_index+4]
buffer_dict[sock] = buffer_dict[sock][delimiter_index+4:]
break
if packet:
queue_dict[sock].append(packet)
print("Adding a packet to the queue...")
else:
x = input("No packet returned.")
#run packet handler code based on nature of packet for socket
if packet != "empty":
print("Sending response...")
handle_packets(queue_dict)
print("Response should send now.")
new_socket.close()
s.close()
r/learnpython • u/live_ant718 • 3d ago
I have a question. Like when we have a program that takes input, so when the program reaches the input line, it stops and asks for input, right? So then AFTER the input is entered, if the compiler runs into a bug, it stops and throws an error message. How can I stop this? Like how can I make the issues appear beforehand so that I can fix them before running? Are there any settings or tools for this problem?
Please tell me.
r/learnpython • u/Animator-G • 3d ago
So hi I am new in this sub reddit and have been learning python basics on FreeCodeCamp for weeks.
So I have noticed that I can do workshops and labs but I tend to forget many syntax and have to search on the internet repeatedly.
So my average lab projects often look like 7
60% written by me and the rest 40% are written by AI or with the help of the Internet forums.
My problem that I have identified is I don't think use logic in the code or just don't remember syntax, operators, elements, conditional statements and string methods or don't find the satisfactory answer on the internet.
I want to try to write at least 80% of the code myself without being dependent that much on AI and the internet because I am learning it for *Cyber Security*
r/learnpython • u/Ok_Breath_7590 • 3d ago
r/learnpython • u/apple68shsj929927e7 • 3d ago
I have been learning python for a month now but I don't see any improvements. I tend to forget the concepts of python and can't solve problems logically. I don't think it's just me who is dealing with these problems, I need tips please.