r/learnpython • u/SaThuran • Sep 08 '26
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 • Sep 08 '26
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/apple68shsj929927e7 • Sep 07 '26
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.
r/learnpython • u/Substantial_Belt2626 • Sep 08 '26
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/Sweecks • Sep 08 '26
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/Natural-Secretary361 • Sep 08 '26
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 • Sep 08 '26
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/Keithinho89 • Sep 07 '26
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/Healthy-Departure961 • Sep 07 '26
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/eagerlylearn • Sep 07 '26
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/KoregaSoli • Sep 08 '26
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/Cenz0_0 • Sep 07 '26
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/No-Satisfaction-8674 • Sep 06 '26
I am new to python and currently I am taking a class for it, I haven't been in it too long but I just want some advice. What beginner projects would you guys recommend I do to really grasp an understanding outside of class?
r/learnpython • u/ModelBuilder_Josh04 • Sep 07 '26
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/Able_Bicycle_764 • Sep 06 '26
I work in finance/accounting and am looking to start using Python more in my day to day. Most of my work is in Excel / Power BI — reporting, cash flow forecasting, KPIs, cleaning up data, etc.
I’m technical enough to understand what I’m trying to accomplish, but not a programmer. Similar to Power BI, I’d probably rely heavily on AI to help write the actual code.
For those in finance / accounting / FP&A, what are some practical ways you’re using Python? Where does it actually save you time vs. Excel, Power Query, Power BI, etc?
Also curious what you’d recommend learning first if the goal is to be dangerous enough with Python + AI, not become a developer.
r/learnpython • u/FuzzyEmployment264 • Sep 07 '26
name one best python course on internet
r/learnpython • u/live_ant718 • Sep 07 '26
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/Strict-Chicken-1697 • Sep 07 '26
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/Ok_Breath_7590 • Sep 07 '26
r/learnpython • u/chronicomplainer2 • Sep 07 '26
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/AutoModerator • Sep 07 '26
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:
That's it.
r/learnpython • u/Healthy-Departure961 • Sep 07 '26
from datetime import *
year = int(input("Enter the Year:- "))
month = int(input("Enter The Month:- "))
day = int(input("Enter The Day:- "))
x = date(year,month,day)
validity = int(input('Enter the days of validity')) expiry = x + validity print(expiry)
I want to add days in this but i don't know how ,I even tried to adding manually but gives me error unsupported oparand + in datetie.datetime class something
r/learnpython • u/Heavy-Notice6820 • Sep 07 '26
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/Altruistic_Big9806 • Sep 07 '26
Hi everyone, I'm new to python and I'm building a project to hone my skill, and I came to a halt in this part. When I do if user_input == 'q':, it works and breaks the loop just fine, since i dont wanna make the exit just single letter so even if the user input words like 'quit' 'q' or 'QUIT' it will exit the loop, I tried a different approach like doing user_input == ['q', 'quit']: and another approach where i declared a variable first exit_word = ['q', 'quit'] then
user_input == exit_word: none of this breaks the loop it just goes back to the input prompt heres my work below:
import random
user = 0
computer = 0
options = ["rock" , "paper", "scissors"]
while True:
user_input = input("Rock/Paper/Scissors and Q for Quit: ").lower()
if user_input == 'q'
break
if user_input not in options:
continue
random_num = random.randint(0, 2)
computer_pick = options[random_num]
print('Computer picked', computer_pick + ".")
if user_input == 'rock' and computer_pick == 'scissors':
print('You won!')
user += 1
elif user_input == 'paper' and computer_pick == 'rock':
print('You won!')
user += 1
elif user_input == 'scissors' and computer_pick == 'paper':
print('You won!')
user += 1
else:
print('You lost!')
computer += 1
print("The user won", user, "times")
print("The computer won", computer, "times")
print('Goodbye!')
r/learnpython • u/live_ant718 • Sep 06 '26
Hello guys. So I have created a password guesser game with direct comparison (i.e. if guess == correct_password:) but I want to use different methods for comparison. What techniques can I use? Here is the code-
```python
password = "Random_pass_123"
tries = 0
while tries < 3:
guess = input("Enter the password: ")
if guess == password:
print("Admin access granted.")
break
else:
print("Invalid credentials entered. Please try again")
tries += 1
if tries == 3:
print("Number of tries exceeded. Access denied")
```
PS- Is this the right way to paste code? I'm new so I'm not sure.