r/learnpython • • 21h ago

Ask Anything Monday - Weekly Thread

7 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 • • 2h ago

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

10 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 • • 7h ago

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

7 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 • • 7h 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 • • 3h 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 • • 4h 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 • • 6h 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 • • 19h 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

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

2 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 • • 1d ago

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

3 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 • • 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 • • 1d 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

finally understood print vs return (this bank analogy saved me)

80 Upvotes

I've been stuck on the difference between print and return for the last few days while learning to code, and it finally clicked for me today. Figured I'd post it here in case anyone else is hitting the same roadblock because it drove me crazy for a bit.

Basically, print() is just a display case. It shows the result on the screen so you can physically look at it, but the rest of your program can’t actually do anything with it. It’s just text sitting on a monitor.

On the other hand, return acts like a courier. It passes the actual data back into the program behind the scenes so another function or variable can grab it and keep working with it.

The easiest way to think about it is a bank account. If you have a function that checks your balance, print() is just the screen showing you the numbers. return is the ATM actually putting the cash into your hand so you can go buy something else with it.

Hopefully this helps someone else save a few hours of confusion!


r/learnpython • • 1d 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 • • 1d 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

WHAT SHOULD I DO? (I am lost)

7 Upvotes

So, here is how it goes. I had a feeling that i need to learn a programming language, and thought there could be no better one at this particular moment other than python. I started with the help of gpt, about 8 or 9 days ago, everyday I learnt something new and practiced lil stuff of the previous day. On day 6, i had no more motivation to continue. I wanna get back at learning it.

There are the stuff ik a lil about:
1. Variables
2. List
3. Loop(For and while)
4. Return

I know very basic stuff about these, mostly i have forgotten stuff. Help to get into a routine. Also Tell me in what order i should learn python???


r/learnpython • • 1d ago

Multiplayer tetris using sockets

4 Upvotes

I have a college assignment to make a multiplayer tetris game (2 players) using TCP sockets, client and server and all that. The idea is the server doing most of the stuff, chosing new pieces, handling the translation of position of the pieces, with the clients being responsible for most the rendering/display part and getting the inputs(I think so at least, that's what I'm trying to do), but I'm having a hard time with it.

I can't seem to think of a way to have the client call to the server to send a new piece to the clients, and if I don't know how to do even that then I don't know how to do anything else (making the back and forth for controlling the pieces, both for the player of the client and the preview of the game of the player 2, and all the rest), tho I hope if I can understand how to do one thing I would be able to make the others, but I really don't even know how to do this.

I know I need to use threads on this, tho I don't really know how to do it, I'm still fairly green on python too so, if anyone could give some help in any way with this it would be much appreciated.


r/learnpython • • 1d 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


r/learnpython • • 2d ago

terminal doubles when i use "import other_file"

2 Upvotes

this is part of the code that relevant to the issues

import arayuz as aFile

def harita_oku():
    with open("harita.txt") as h:
        harita_temp = [satir.strip("\n") for satir in h.readlines()]
    if not harita_temp:
        raise ValueError("harita dosyası boş")
    x_temp = len(harita_temp[0])
    y_temp = len(harita_temp)
    if all(len(l) != x_temp for l in harita_temp):
        raise ValueError("harita satırları eşit değil")
    return harita_temp , (x_temp,y_temp)


harita, izgara = harita_oku()


print(harita)
print(izgara)

this is the terminal output

['##############', '#.R......s.k.#', '#.R...t....k.#', '##############']
(14, 4)
['##############', '#.R......s.k.#', '#.R...t....k.#', '##############']
(14, 4)

and what it prints without "import arayuz as aFile"

['##############', '#.R......s.k.#', '#.R...t....k.#', '##############']
(14, 4)

how to i fix this?


r/learnpython • • 2d ago

Feeling stuck transitioning from basic Python/DSA to FastAPI — is this the right next step, or am I missing something?

1 Upvotes

Hey everyone,

I’m currently trying to figure out my next move in programming and could use some advice.

Here is where I stand right now:

  • Current Knowledge: I know Python syntax, for loops, functions, and some basic programming concepts.
  • DSA: I have solved around 45 DSA problems, though I mostly had to look at solutions to get through them.
  • The Goal: I eventually want to build real projects and get into open-source contributions.

I figured building web apps using FastAPI was the logical next step, but I'm running into a wall. I tried Telusko’s FastAPI course, and honestly, I didn't understand most of it—things like what is actually happening under the hood or why the @ symbol (decorators) is used completely threw me off. I tried another video tutorial too, but I'm only grasping about half of what's going on.

My questions for you all:

  1. Is FastAPI too early for me right now? Should I master something else first before jumping into backend frameworks?
  2. If I should learn FastAPI, how do I clear up these massive gaps? (Especially concepts like decorators, asynchronous code, and type hints that seem to fly right over my head)

Any advice, roadmap corrections, or beginner-friendly resource recommendations would mean a lot. Thanks!


r/learnpython • • 2d ago

Need help with empty strings or lists

0 Upvotes

I just started learning python and I’m confused on when to use empty string or empty list. Also when should you call that empty string in a loop or outside of the loop?


r/learnpython • • 2d ago

Starting the pandas/data-analysis phase of my learning — what was the first real dataset you actually analyzed (not Iris or Titanic)?

1 Upvotes

I'm a second-year BCA (AI/ML) student in Jaipur, self-studying Python alongside college. I'm wrapping up the basics + NumPy phase and about to start pandas, and honestly the thing I'm stuck on isn't the syntax — it's what to practice on.

Every tutorial points me at Iris or Titanic, and they feel like toy problems at this point. I want a dataset that actually feels like something I'd want to finish and maybe show later — something with messy real-world data where the interesting part is the analysis, not just following the notebook step by step.

So for those of you who've been through this phase: what was the first dataset you analyzed for real? Where did you find it (Kaggle, government open data, scraped your own, something else)? And what would you suggest for someone still early in pandas — go big, or pick something small and actually finish it?


r/learnpython • • 2d ago

weird error that I don't know how to fix

0 Upvotes

Hi! I keep getting this error whenever I try to use append or extend. I have gap_m and mgaps as empty lists, I have used extend before w similar data and it worked fine so I am unsure why it is no longer working

AttributeError                            Traceback (most recent call last)
Cell In[42], line 33
     30
 gap_m = []
     31
 mgaps = []       
---> 33 mass_gap_calc(df)

Cell In[42], line 29, in mass_gap_calc(df)
     27
 mgaps = np.diff(msort)
     28
 gap_m.append((msort[:-1]))
---> 29 mgaps.append(mgaps)

AttributeError: 'numpy.ndarray' object has no attribute 'append'

r/learnpython • • 2d ago

GUI framework for a little software project for school

5 Upvotes

Hi!
I (an old-ish person) went back to uni, and for an assignment I have to - over the course of a couple of months - do a mock software project. With my professor I decided on a (desktop) program that reads (different) text files, analyzes them using different criteria, highlights potentially problematic parts (e.g. sentences that are very long), and also uses a traffic light system. It should be possible to assess the text using only one criterion, several of them, or all of them. Since my programming knowledge is limited (and I refuse to let agentic AI do everything, even though we are allowed to use it - but I want to learn something and understand!), I am not required to implement a huge back-end with web servers, databases and the like (luckily, since my database and SQL knowledge is rusty, although I took a fundamental class on it years ago). However, a GUI is absolutely required. So far, I have a bit of a CLI program that reads text and compares texts. It's not much, but it's honest code...

My professor said I am free to choose whatever GUI framework, as long as it is a fitting one...and I am a bit overwhelmed. I have only used tkinter in the past - a little bit. The looks felt a bit "outdated", and I am not sure how nice, e.g., a traffic light system would look if created using it. I know there are many other GUI frameworks, but I am a bit intimidated by their steep learning curves.

More on my background: Of course, a web app would also be a possibility (in spite of me trying to avoid the back-end stuff), but I don't know much about web development, nor have I ever used Flask (except for some tiny Docker demos) or Django and the like. In the past, I used Python mainly for Data Analysis and a bit of Data Science, while I learned writing little CLI programs using Java and C. Also, years ago, I learned about Javascript, HTML/CSS, PHP, node.JS and Express, and a bit of PHP; I also took a class on PWAs (written mainly in Javascript, using Lit and Ionic), which of course resulted in (mobile) apps with a GUI. But all of this is not the Python project my professor and I talked about.

Do you have any suggestions for me concerning Python GUI frameworks or approaches that feel "intuitive" to learn (of course, I am willing to invest in learning - but if the learning curve is too steep, I might just not be able to "get it")? Or is the web app route THE way to go?

Thanks in advance!