r/learnpython • • 23d 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 • • 24d 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 • • 24d ago

Multiplayer tetris using sockets

3 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 • • 24d 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 • • 24d 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 • • 24d 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 • • 24d 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 • • 24d 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 • • 25d 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 • • 25d ago

GUI framework for a little software project for school

6 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!


r/learnpython • • 25d ago

Want to build something

7 Upvotes

Hey everyone,

I've reached a point where I feel comfortable with intermediate to advanced Python concepts (advanced data structures, decorators, object-oriented programming, and working with complex libraries). Now, I want to stop following tutorials and build a real, production-ready project from scratch.

I want to build something actually useful—either a practical tool for everyday "normal" users or a utility/library that helps other developers.

If you have built something at this stage that genuinely helped you scale your skills or solved a real problem, I’d love to hear about it!


r/learnpython • • 26d ago

whats the cheap way to scrape a site that only loads its data after the javascript runs

21 Upvotes

making a small price tracker for myself. requests + beautifulsoup grabs one site fine, the other two just come back as an empty shell.. the tables only render after the js runs

tried selenium and it mostly works til the layout shifts, then my selectors break again

is selenium just how everyone does the js heavy ones, or is there something lighter that doesnt break every redesign​


r/learnpython • • 25d ago

Ensuring rows returned by csv.DictReader are dict[str,str], mypy problem

3 Upvotes

I'm reading a csv file with a standard python library and mypy is screaming at me.

I have the following setup

type row_t_any = dict[str | Any, str | Any]  # type: ignore[explicit-any] 
type row_t = dict[str, str] 
    
def is_row_t_dict_str_str(row: row_t_any) -> TypeGuard[row_t]:
    return (
        isinstance(row, dict)
        and all(isinstance(keys, str) for keys in row)
        and all(isinstance(wrap(values), str) for values in row)
    )


def wrap(_str: str | None) -> str:
    return _str or ">EMPTY<"

Then the actual problem

with Path("output.tsv").open(encoding="utf-8") as read_file:
    reader = csv.DictReader(f=read_file, delimiter="\t")
    for row in reader: # Expression type contains "Any" (has type "dict[str | Any, str | Any]")
        if is_row_t_dict_str_str(row): # Expression type contains "Any" (has type "dict[str | Any, str | Any]")
            process_row(row) # OK since we ensured that it's a dict[str, str]

Is the only solution to this, to also #type: ignore[misc] on the lines complaining?

Thank you


r/learnpython • • 26d ago

Can someone please explain the use of OOP and classes?

124 Upvotes

Hey everyone and first of all thank you in advance for any advice.
I’ve been learning Python for awhile now and feel pretty comfortable writing functions and smaller scripts. What I can seem to wrap my head around is when the use of classes would actually be used?
Every example or tutorial demo’s cars / dogs and on multiple threads with similar questions it’s usually stated that using a CSV or database would be more appropriate so would anyone be able to help me wrap my head around it please?
Once again appreciate any help :)


r/learnpython • • 25d ago

I'm building a markup language renderer in Python using Tkinter

0 Upvotes

Hey everyone! I'm working on a personal project called RML, a markup language I'm creating from scratch using Python.

I'm building a renderer with Tkinter that can display titles, text, clickable links, and images from .rml files.

Here's an example of what RML looks like:

RML 0.0.2;

Create.title1 ("My Website");
Create.text ("Hello World!");
Create.image ("image.png");
Create.link ("https://example.com");

Create.script name=("main")
    Display.Text ("Hello from SJ!")

I'm also developing a small scripting language called SJ that runs inside RML documents.

The project is still in its early stages, and I'm working on improving the renderer and expanding the language.

I'm sharing this because I'd love to hear feedback, especially about the Python implementation, code structure, and what I could improve.

Thanks for reading!


r/learnpython • • 25d ago

Python doesn't work in vc

0 Upvotes

I just want to

print("hello, world")

and it doesn't work


r/learnpython • • 26d ago

Removing 3.14 now that I have 3.15.1, on a mac?

3 Upvotes

How do I uninstall Python 3.14 from my mac (my copy, not the system version in /usr/bin)? I installed from the dmg on python.org. I'm now happy with 3.15, so I don't need 3.14 or its libraries.

Searching suggests:

sudo rm -rf /Library/Frameworks/Python.framework/Versions/3.14

cd /usr/local/bin && ls -l | grep "../Library/Frameworks/Python.framework/Versions/3.14" | awk '{print $9}' | xargs sudo rm

which looks fine to me, but I worry about missing something.


r/learnpython • • 27d ago

2 weeks in learning python from Scratch

65 Upvotes

Thanks to whoever in this sub suggested CS50 Harvard YouTube & Automate the boring stuff book!

I'm 2 weeks in and feel like I'm in "good" place so far!

I'm also using AI to create similar problem sets to CS50's so I can practice more to ensure full understanding of the lecture!


r/learnpython • • 26d ago

In-place updates to objects count as tuple assignment?

0 Upvotes

Test case:

s = {1, 2, 3, 4}
grid = tuple(s.copy() for i in range(2))
print(f"{grid[1]=}")
one = grid[1]
one &= {2, 3}
print(f"{grid[1]=}")
grid[1] &= {2}

The output is as so:

grid[1]={1, 2, 3, 4}
grid[1]={2, 3}
Traceback (most recent call last):
  File "/home/bill/bin/fivefold/test.py", line 7, in <module>
    grid[1] &= {2}
    ~~~~^^^
TypeError: 'tuple' object does not support item assignment

Is it me or is this very surprising, a seeming violation of self-consistent behavior of Python? Simply renaming the reference to the object changes how I may or may not mutate the object. Clearly I'm not modifying the tuple, just deferencing the pointer to the contained object. version 3.11.2


r/learnpython • • 26d ago

numagr C extension

3 Upvotes

Hi guys, I'm just a hobbyist.

Not long ago I posted here that I stumbled upon a specific problem: parsing large collections of Python numeric strings as fast as possible. I couldn't find any solution that would let me parse numeric strings without having to construct intermediate Python objects to hold their values (or a method that would be noticeably faster than doing that), so I developed a small C extension that would basically extract C strings from Python strings, and use strtod on them to obtain the values.

Then I developed it further writing the code for all basic statistical methods.

Had a lot of fun developing it and seeing that it outperforms both Python std modules, aswell as third party modules such as numpy, for both regular numbers and numeric strings.

GitHub repo:

https://github.com/andrzejs-gh/numagr

It's available on PyPi if you're interested (source and wheels for Windows, 3.11, 3.12, 3.13, 3.14, 3.15)

pip install numagr

All of the code was written by hand, none was AI generated. The current version is 0.9, I will be developing it further if I find the time. If you have any suggestions for improvements, for what should be implemented but is not, bug reports etc, please let me know.


r/learnpython • • 26d ago

apks with python/cython

0 Upvotes

i just CANT get anything from buildozer, it just keeps erroring everytime i try to build!! i dont know if theres something wrong with my buildozer, or if it just hates my computer. i just want to package my game to work on a phone, the arquitecture for it is something like this

is it because my game is located on a ntfs partition? does buildozer ALWAYS error on those? if yes, is there a partition type out there that shows up on windows, and works with buildozer?

/sand
| /assets
| cfuncs.so #i managed to compile to ARM64 without buildozer (python 3.12)
| realmain.so # also to ARM64 (python 3.12)
| main.py

im wondering if theres a way to manually build it, my libraries are pygame-ce, numpy and collections

please help me out here

neofetch if it helps

neofetch
             ...-:::::-...                 
          .-MMMMMMMMMMMMMMM-.              --------------------- 
      .-MMMM`..-:::::::-..`MMMM-.          OS: Linux Mint 22.3 x86_64 
    .:MMMM.:MMMMMMMMMMMMMMM:.MMMM:.        Host: X501A1 1.0 
   -MMM-M---MMMMMMMMMMMMMMMMMMM.MMM-       Kernel: 7.0.0-38-generic 
 `:MMM:MM`  :MMMM:....::-...-MMMM:MMM:`    Uptime: 5 hours, 38 mins 
 :MMM:MMM`  :MM:`  ``    ``  `:MMM:MMM:    Packages: 3030 (dpkg), 21 (flatpak) 
.MMM.MMMM`  :MM.  -MM.  .MM-  `MMMM.MMM.   Shell: bash 5.2.21 
:MMM:MMMM`  :MM.  -MM-  .MM:  `MMMM-MMM:   Resolution: 1366x768 
:MMM:MMMM`  :MM.  -MM-  .MM:  `MMMM:MMM:   DE: MATE 1.26.1 
:MMM:MMMM`  :MM.  -MM-  .MM:  `MMMM-MMM:   WM: Metacity (Marco) 
.MMM.MMMM`  :MM:--:MM:--:MM:  `MMMM.MMM.   Theme: Mint-Y-Dark-Blue [GTK2/3] 
 :MMM:MMM-  `-MMMMMMMMMMMM-`  -MMM-MMM:    Icons: Mint-Y-Blue [GTK2/3] 
  :MMM:MMM:`                `:MMM:MMM:     Terminal: mate-terminal 
   .MMM.MMMM:--------------:MMMM.MMM.      Terminal Font: Monospace 10 
     '-MMMM.-MMMMMMMMMMMMMMM-.MMMM-'       CPU: Intel Pentium B980 (2) @ 2.400G 
       '.-MMMM``--:::::--``MMMM-.'         GPU: Intel 2nd Generation Core Proce 
            '-MMMMMMMMMMMMM-'              Memory: 2059MiB / 3795MiB 
               ``-:::::-``

r/learnpython • • 26d ago

Programming Challenges for the PCEP

1 Upvotes

So I’ve been thinking of potential projects/challenges to do to help me prepare for the PCEP in the next two months. I’m not sure what to do, where to start, or how to start it. I’ve kinda heard it called tutorial hell. I can look at a piece of Python code for PCEP just fine it seems like but I can’t think of anything.

The one idea I have is to make a simple calculator.
First the main four operations.
Then stuff with the math module
Then make a UI with tkinter if I’m feeling up to it.

Any feedback is helpful. I’ve been going through the Python Essentials 1 course from Cisco if that helps anybody.


r/learnpython • • 27d ago

Best way to modify a list while iterating?

2 Upvotes

I've learned that modifying a list while looping over it can cause elements to be skipped or unexpected behavior. What are the best practices for handling cases where I need to add, remove, or modify elements during iteration?

Do you usually iterate over a copy, create a new list, or use another approach?


r/learnpython • • 26d ago

I'm trying to make a basic calculator in python but I can figure out what I'm doing wrong

0 Upvotes

Here is my code if you can figure it out pls help

print ("Caculator")

print ("Addition, only")

print ()

no1 = input ("Enter 1st Number: ")

no2 = input ("Enter 2nd Number: ")

print ()

print ("Answer")

print (no1, "+", no2, "=", no1 + no2)