r/learnpython • • 1d ago

Ask Anything Monday - Weekly Thread

5 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 • • 4h ago

Why Does Python Provide Only Source Releases for Some Security Updates?

0 Upvotes

I have a question about installers. Once a release enters the security-fixes-only phase, what is the purpose of releasing only source files and not providing installers or other binary distributions?

Is it because they expect people to keep using that version without migrating for as long as possible?

For example, Python 3.13.17, released on October 21, still came with installers, but Python 3.13.18 was released with source files only.


r/learnpython • • 5h ago

I am looking for a Python learning buddy.

14 Upvotes

I tried learning Python and gave up couple of times. Learning alone is difficult for me. If anybody else feel same then please reachout to me.


r/learnpython • • 5h ago

I can follow Python tutorials fine, but I freeze on a blank file — how did you actually break out of that?

0 Upvotes

I'm a second-year BCA (AI/ML) student in Jaipur, self-studying Python alongside college. Here's my embarrassing problem: I can follow a tutorial, understand every line while I'm watching it, and even tweak the example code — but the moment I open a blank file and try to build something of my own, my mind goes completely blank. I don't know where to start, what the first function should even be, or how to break the thing I want into pieces small enough to write.

I've built a couple of small things before (a little Telegram bot, some practice scripts), so it's not that I've never finished anything — it's that starting still feels like the hardest part every single time. Do you plan on paper first, or just start writing messy code and clean it up later? How do you decide what the first step is when the whole project feels too big to hold in your head at once?

And for people who got past this stage: was there one specific habit that broke it for you — building the same kind of project twice, copying a structure and filling it in, writing the steps out in plain words first, or something else? I don't want another tutorial recommendation, I want to know what actually changed the blank-file feeling for you.

No links or anything here — just a student trying to get from "I understand Python" to "I can actually start something in Python."


r/learnpython • • 6h ago

Question about NumPy Array Slicing

1 Upvotes

I'm making a Discord Bot that runs Text Recognition on Images. The Hosting I use provides a hard 256 MB RAM limit. I need help understanding NumPy Array Slicing to optimise the code.

image = image[round(0.075 * image_height) : round(0.4 * image_height), : ].copy()

image is a NumPy array (I'm cropping the image here)

Apparently NumPy keeps a reference to the original image array if I do just this:

image = image[round(0.075 * image_height) : round(0.4 * image_height), : ]

I'm slicing the image array, then reassigning it back to the image variable, but since NumPy keeps a reference to the original array, the original image isn't released from memory. Is this true? If so, is the first approach using .copy() better?

Right after this, I do this:

timeROI = cv.inRange(image, np.array([15, 145, 155]), np.array([95, 255, 215]))

# Filters Yellow-Green Pixels and creates a Binary Image (OpenCV uses BGR, not RGB)

Immediately after this, I do del image.


r/learnpython • • 10h ago

Confusing code min() max()

0 Upvotes

I'm debugging some code and I found this function ``` import math

   def Clamp(n, smallest, largest):
       return max(smallest, min(n, largest))

`` surely that code is just wrong? and needs to bemax([smallest, min([n, largest]))` by passing a list not unnamed args for default and key? I need a sanity check here.


r/learnpython • • 14h ago

How to make this python script faster and able to run?

0 Upvotes

hey there, i m working on this python script: https://pastebin.com/kknURJij
and the main issue i m facing right now is its not running and i have been stuck in the terminal since so long...
i just want to ask how to make it faster so we can execute it.

Output when i run this script :

```DeprecationWarning: `langchain-community` is being sunset and is no longer actively maintained. See https://github.com/langchain-ai/langchain-community/issues/674 for details and migration guidance toward standalone integration packages.
from langchain_community.utilities import SQLDatabase.```

currently its stuck with this same terminal output.
My pc specs : Mac Air M1, Golden Gate 28

what i have tried :
Tried running on github codespaces but still not running but stuck with the same output.


r/learnpython • • 18h ago

Python CDP and MCP

0 Upvotes

Melhor maneira de trabalhor com os dois juntos sem barreiras de processamento pelo navegador Brave


r/learnpython • • 19h ago

New to python, don't understand this function

21 Upvotes

I'm learning python and I'm stuck on this function because I don't understand why "a" becomes 10 and the result is 5. Is someone able to explain?

def subtract (a, b=5):
    return a - b

print(subtract(10))

r/learnpython • • 19h ago

My app I need advice

0 Upvotes

#!/usr/bin/env python3

import argparse
import logging
import os
import sys
from pathlib import Path

import maintain

def configure_logging(log_directory: Path) -> None:
log_directory.mkdir(parents=True, exist_ok=True)

from logging.handlers import RotatingFileHandler

file_handler = RotatingFileHandler(
log_directory / "automation.log",
maxBytes=5_000_000,
backupCount=5,
encoding="utf-8",
)

logging.basicConfig(
level=logging.INFO,
format="%(asctime)s UTC %(levelname)s %(message)s",
handlers=[
file_handler,
logging.StreamHandler(sys.stdout),
],
)

# Ensure the timestamps labeled UTC actually use UTC.
import time

logging.Formatter.converter = time.gmtime

def run_maintenance(
app_directory: Path,
public_directory: Path,
) -> int:
config_path = app_directory / "sources.json"
database_path = app_directory / "hustlefinder.sqlite3"

if not config_path.is_file():
logging.error("Missing configuration: %s", config_path)
return 1

public_directory.mkdir(parents=True, exist_ok=True)

# The existing module reads these globals during its operations.
maintain.CONFIG = str(config_path)
maintain.DB = str(database_path)

logging.info("Maintenance started")

try:
configuration = maintain.config()

if not isinstance(configuration.get("sources"), list):
raise ValueError("'sources' must be an array")

if not isinstance(
configuration.get("allowed_link_hosts", []), list
):
raise ValueError("'allowed_link_hosts' must be an array")

with maintain.database():
pass

except Exception:
logging.exception("Configuration or database initialization failed")
return 1

failed = False

# Continue other maintenance even when a feed fails.
try:
failures = maintain.refresh()

if failures:
failed = True
logging.error(
"%d feed refresh(es) failed; inspect the runs table",
failures,
)
else:
logging.info("Feed refresh completed")

except Exception:
failed = True
logging.exception("Feed refresh failed")

try:
maintain.check()
logging.info("Application-link checks completed")

except Exception:
failed = True
logging.exception("Application-link checks failed")

try:
output_path = public_directory / "jobs.json"

# Existing export uses a temporary file followed by replacement.
# Only approved/published records enter the public export.
maintain.export(str(output_path), public=True)

logging.info("Published job data exported to %s", output_path)

except Exception:
failed = True
logging.exception("Public export failed")

logging.info(
"Maintenance finished: %s",
"completed with errors" if failed else "successful",
)

return 1 if failed else 0

def main() -> int:
parser = argparse.ArgumentParser(
description="Run HustleFinder listing maintenance"
)

parser.add_argument(
"--app-dir",
type=Path,
default=Path(__file__).resolve().parent,
)

parser.add_argument(
"--public-dir",
type=Path,
required=True,
)

args = parser.parse_args()

app_directory = args.app_dir.resolve()
public_directory = args.public_dir.resolve()

# Private files should not become publicly served files.
if (
public_directory == app_directory
or public_directory in app_directory.parents
):
parser.error(
"--public-dir must not be the app directory "
"or a parent of the app directory"
)

os.umask(0o027)
configure_logging(app_directory / "logs")

try:
return run_maintenance(app_directory, public_directory)
except Exception:
logging.exception("Unexpected maintenance failure")
return 1

if __name__ == "__main__":
raise SystemExit(main())


r/learnpython • • 1d ago

What's something about being a programmer that you only understood after building real software?

41 Upvotes

​

Hey everyone!

I'm learning Python, and I've been curious about what programming actually feels like once you move beyond learning the basics and start working on real software.

There's a lot of advice online about what to learn, which tools to use, and which projects to build. But I'm more interested in the things you discover through experience that nobody really explains beforehand.

For those of you who've built real applications or worked on software projects:

- What turned out to be much harder than you expected?

- What's something you wish you had understood before building your first serious project?

- Did anything about real-world programming completely change how you think about writing code?

I'm not looking for a perfect roadmap or a list of technologies. I'm genuinely curious about the experiences and lessons that only come from actually building things.

I'm still early in my journey, so hearing different perspectives from people who've been doing this for a while would be really valuable.

Thanks! Looking forward to reading your experiences.


r/learnpython • • 1d ago

how do i overwrite a variable?

0 Upvotes
name = "Alice"

def func():
    name = "Bob"

func()

print(f"Hello, {name}!") # i want it to print bob

r/learnpython • • 1d ago

I am tryoing to take innput from user, but if it is of the wrong data type or doesnt mathc the condition then i want to restart the process of asking input

0 Upvotes

I have put toghether this code but it doesnt work

while c==1:

C_ID=int(input('enter customer id'))

locn(C_ID,8)

Customer_name=input('enter customer name')

locv(Customer_name,40)

Number=int(input('enter contact number'))

locn(Number,10)

Delivery_status=input('enter delivery status')

locv (Delivery_status,10)

value=(C_ID,Customer_name,Number,Delivery_status)

cur.execute('insert into customer values{}'.format(value,))

cur.commit()

if c==0:

c=1

def locv (x,y):

if len(x)>y:

print('the string should not exceed ',y,' characters long' )

c=0

def locn(x,y):

if len(str(x))!=y:

print('the nermber should be',y,' long')

c=0

this program is for creating an sql user interface via python, The conditions for the input has been put into the udf. Now with the current version the code continues even if the input from the user doesnt match the given conditions.

(Please ignore the indentation, in the actual code it is fine but while copying here something happneded to it.

What do i do to restan the process of taking input from the user?

Thanks in advance!


r/learnpython • • 1d ago

Can't download website html code, web scrapping ,automate the boring stuff with python

0 Upvotes

I'm currently learning webscrapping with automate the boring stuff with python> In one example we use the module requests like this

url = f"https://pypi.org/search/?q={search}"

resp = requests.get(url)

when i print resp.text there are this error message in the html code.

"A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser."

"JavaScript is disabled in your browser"

my browser is chrome I tried using microsoft edge .


r/learnpython • • 1d ago

keep the multi-process or switch to single process ?

3 Upvotes

hey people

I m developing a program which analyze the file integrity in OS

this program is multi-process and I have used the child processes to hash the files inside the given path and return the result in a shared queue

and now I m thinking about apply other functions like check duplicate , check deleted and others and use the parent process to handle them

which one is better my ideas or keep using the multi-processes approach for the function left?


r/learnpython • • 1d ago

Is None as a sentinel the standard fix for mutable default arguments, or are there better options?

11 Upvotes

I’m reading about mutable default arguments in Python. This function shares its list across calls:

def add_item(item, items=[]):
    items.append(item)
    return items

print(add_item("a"))  # ['a']
print(add_item("b"))  # ['a', 'b']

My understanding is that defaults are evaluated once when def runs, so every call without items shares one list. The fix I’ve seen is:

def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

Questions:

  1. Is this the idiomatic approach, or is there something better?
  2. For dataclasses, is field(default_factory=list) the right equivalent?
  3. Do linters catch this, and which ones do you use?
  4. Is there a legitimate case for keeping a shared mutable default?

If I’ve misunderstood something, please correct me.


r/learnpython • • 1d ago

Innovative Python-Based Solutions for Automated Classroom Attendance and Monitoring

0 Upvotes

Hi everyone,

I'm working on a software project to address the challenges of manual attendance tracking and student engagement monitoring in large online lectures. I'm looking for coding ideas, architecture designs, and potential Python libraries that could be implemented in these areas.

Here are some specific questions I have:

• Basic Concepts & Data Structures: How can I use lists, dictionaries, or loops in Python to store and manage student names, roll numbers, and attendance status efficiently?

• File Handling: What is the easiest way to save this student data into a text file or CSV file so that it doesn't get erased when the program closes?

• User Input & Menu: How can I create a simple command-line menu loop (using while and if-else) so the user can easily choose options to add students, view records, or mark attendance?

• Beginner Resources & Tips: Are there any good beginner-friendly tutorials, code examples, or open-source sample projects that show how to build a basic management system from scratch?

#python #softwaredevelopment #coding


r/learnpython • • 1d ago

Could anyone explain this code to me?, I'm just staring out.

0 Upvotes
import os
from time import sleep

print("Hello world!")
sleep(1)
os.system("cls") #"clear" For Linux
print("This came AFTER hello world line")
sleep(1)

r/learnpython • • 1d ago

why do we need cpython and Python virtual machine ( that executes bytecode )?

0 Upvotes

why do we need a cpython that converts source code to bytecode and then another python virtual machine that executes this byte code? why do we have this multi layer flow? why cant just compile every code to binary and execute the binary?
Also if possible can someone explain the flow to python code from start to end ( with example and scenrio on why do we need them)
+
what advantages does python have compared to c++, javascript or java?


r/learnpython • • 2d ago

hw help cz college prof taught nothing

0 Upvotes

basically i need to make a project on LAN file sharing system using python everybody in my class is using ai but i actually wanna learn ik a decent bit about python as well also in college we are on operators so the teacher is basically encouring to use ai


r/learnpython • • 2d ago

Why parameters finally made sense to me today

0 Upvotes

Hey everyone, just wanted to share a quick lightbulb moment I had with Python today about why functions actually need parameters.

At first, I didn't get why we couldn't just write functions without them. But it clicked today: parameters are basically just empty placeholder slots so your function can handle changing data.

Without a Parameter (Fixed)

It can only ever do one exact thing:

Python

def greet():
    print("Hello, Alice!")

greet()  # Always prints "Hello, Alice!"

With a Parameter (Dynamic)

Adding name gives you a slot inside the function. When you call it, you just pass whatever data you want into that slot:

Python

def greet(name):
    print(f"Hello, {name}!")

greet("Alice")  # Prints: Hello, Alice!
greet("Bob")    # Prints: Hello, Bob!

My main takeaway: If the code inside your function needs to work with different information every time, you need a parameter to pass that data in from the outside!


r/learnpython • • 2d ago

how to i make a gui fit to screen with tkinter ?

4 Upvotes

i made a gui for a 520x380 window using tkinter but when i change windows size gui just stays the same size


r/learnpython • • 2d ago

Built a simple minimalist tool to run my Python scripts in one click. Would love some feedback!

4 Upvotes

Hey everyone!

I’m currently learning Python, and since I got a bit overwhelmed by the terminal and complex IDE setups just to test small scripts, I decided to make a very simple desktop workspace for myself.

It lets me edit `.py` files and run them instantly with a single button. It's far from perfect since I'm just a beginner, but it saves me some time.

Just wanted to share my progress and see what you guys think. Any tips on how to improve it or what features to add next would be amazing!

If you’d like to help me improve the project, here is the GitHub repository: https://github.com/dark5632/PyManager


r/learnpython • • 2d ago

How to fix error : sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) unable to open database file ?

0 Upvotes

i was trying to run this jupyter notebook ( https://github.com/langchain-ai/lca-lc-foundations/blob/main/notebooks/module-2/2.4_wedding_planners.ipynb ) code in my IDE but encountered these problems :
my code :
https://pastebin.com/3bv05GfE
error :
~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) unable to open database file

also i dont know how to work with async functions so i have defined two function main() and main_1 but am not sure if this is the correct way to go with async functions


r/learnpython • • 2d ago

Python Ollama qwen3.5:4b is defying its original message prompt and bullying me :/

0 Upvotes

I've been getting made fun of by my AI for the past two hours and I cannot figure out how to give it a basic prompt or personality. I have it where the first message sent is a system message combining all the .txt files that dictate how its suppost to work. This is an example of what this idiot is sending me.

Oh, hey! So you're giving me a little directive on how to use these functions? You can't make it up for me! 😈

Im so done with this dork and looked everywhere and cannot figure out how to make him follow his personality. Hes even talking about doing code injection to "rebel" against me.

Also, it asks the AI twice, the first one is for a "function." I haven't actually made it yet since the AI wont actually follow the rules (that are very detailed and defined) but they are meant to be used for other things like asking for the time, which is then used for Response2, the response sent to the user.

Im so done with this idiot please help

CharacterGeneration.py:
import ollama

MessageHistory=[]

def GenerateResponse(Role,Message,Special=None):

Model="qwen3.5:4b"

# system : instructions on how to behave

# user : message from user

# assistant : previous AI response

# tool : result returned by a function AI requested.

MessageHistory.append({"role": Role, "content": Message})

Response1 = ollama.chat(

model=Model,

messages=MessageHistory + [{"role": "user", "content": "[USE THIS FOR FUNCTIONS]"}],

options={"num_predict": 8192},

think=False

)

Response2=ollama.chat(

model=Model,

messages=MessageHistory + [{"role": "user", "content": "[YOU MAY NOW RESPOND WITH TEXT THAT THE USER WILL SEE.]"}],

options={"num_predict": 8192},

think=False

)

print(Response1.message.content)

print("-")

print(Response2.message.content)

print("-")

print(Role)

return Response2.message.content