Backend
Python Functions: Why They changed My code
SameerQaisar17 Dev.to (EN Zone)
2 views
Quick Info
Topic: Functions in Python
Target Audience: Beginners who know loops and if-else
Goal: Understand why functions exist and how to write one
1. Introduction
"I used to write the same code over and over. Copy, paste, tweak one word. Then I learned about functions — and my code got 10x shorter. Here's how they work and why I use them everywhere now."
2. The Problem (Without Functions)
print("Hello, Ali!")
print("Hello, Sara!")
print("Hello, Ahmed!")
print("Hello, John!")
print("Hello, Emma!")
Problem: If I want to change “hello” to “hi”, I have to edit 5 lines. Imagine 100 lines
3. The Solution (With Functions)
def greet(name):
return f"Hello, {name}!"
print(greet("Ali"))
print(greet("Sara"))
print(greet("Ahmed"))
print(greet("John"))
print(greet("Emma"))
Output:
Hello, Ali!
Hello, Sara!
Hello, Ahmed!
Hello, John!
Hello, Emma!
4. How it works (Line by Line)
Line 1: def greet(name): — This defines a function called greet that takes one input: name.
Line 2: return f"Hello, {name}!" — This returns a greeting with the name inserted.
Line 4: print(greet("Ali")) — This calls the function with "Ali" and prints the result.
5. Real Example (My Practise)
python
def add_numbers(a, b):
return a + b
result = add_numbers(5, 3)
print(result)
Output:
8
6. What I learned
Functions let me reuse code instead of repeating it
def starts a function
return sends the value back
I can pass argument(inputs) into a functions
If I need to change behavior, I change it in one place
Conclusion
Functions seemed like extra work at first. Now I can't write code without them. They made my scripts cleaner, shorter, and easier to fix.
Read original: https://dev.to/sameerqaisar17/python-functions-why-they-changed-my-code-1516
← Previous
Fixing AI Agent Lies: detect AI agent deceptive behavior
Next →
AI Security Scanning Needs Evidence, Not Just More Agents
Related
Python: Loops
Backend
1
DEV Community
From Physical Racks to Intelligent Modules: How the Meaning of Infrastructure Has Fundamentally Shifted
Backend
2
Dev.to (EN Zone)
Four Ways to Survive a Network Split
Backend
2
Dev.to (EN Zone)
The fifteen ways a Google Play subscription breaks quietly
Backend
5
DEV Community
Comments0
No comments yet — be the first