I Confused print and return for Months. Here’s What Finally Clicked
The simple Python mental model that turned my “silent” functions into powerful tools.
There are moments in programming where you feel like the computer is gaslighting you. For me, one of the first was writing a Python function that looked perfect—no errors, no warnings—but somehow “did nothing.”
I’d run my code, stare at the screen, and mutter: “Why won’t you just work?”
Spoiler: the bug wasn’t Python. The bug was me. I didn’t understand the difference between print
and return
.
And if you’re new to Python, you’ve probably fallen into the same trap.
My First "Silent" Function
My first attempt at a function to add two numbers looked like this:
def add(x, y):
print(x + y)
It seemed to work perfectly. When I called add(2, 3)
, the number 5
appeared on the screen. Success!
, I thought.
But the moment I tried to do something else with that number, my code blew up.
result = add(2, 3)
print(result + 10)
Python slapped me with a TypeError
. Apparently, I was trying to add 10
to... None
. I sat there thinking: “None
? What None
? I saw the 5
on the screen. Where did it go?”
The truth is, print
was playing a trick on me. It lit up the screen for me, the human, but left my function empty-handed.
print
Is for You, return
Is for the Program
The fix was painfully simple. I needed to return
the value instead of print
ing it.
def add(x, y):
return x + y
Now, the function gives back a real value, so my program could use it.
result = add(2, 3)
print(result + 10) # Output: 15
This was the day I realized: print
is for me, the human. return
is for the program.
Think of it this way:
print
is a monologue. It speaks directly to the user (you).return
is a dialogue. It speaks to other parts of your code.
The Debugging "Flashlight"
I still use print
—a lot. It’s the cheapest flashlight you’ve got for debugging. When a variable’s value is a mystery, I’ll sprinkle print
statements to peek inside.
def calculate_total(prices):
total = sum(prices)
print("DEBUG:", total) # My flashlight
return total
This is a great use of print
. The trick is knowing when to stop. Debugging with print
is fine. Building logic around print
is where the wheels fall off. It’s a flashlight, not an electrical outlet.
Final Takeaway
Mastering the difference between print
and return
is a turning point. It's when you stop writing functions that only talk to you and start writing functions that can be composed, reused, and scaled. That’s when Python stops being a toy and starts being a tool.
So next time your function “does nothing,” remember: it might not be Python that’s broken. It might just be you, staring at a flashlight where you should have had a dialogue.
Aaron Rose is a software engineer and technology writer at tech-reader.blog and the author of Think Like a Genius.
Comments
Post a Comment