Backend
Python Functions: Why They changed My code
SameerQaisar17 Dev.to (EN Zone)
22 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
The benchmark everyone cited for "fastest backend" was archived in March, and the reason is the interesting part
Backend
56
Dev.to (EN Zone)
Finding Exoplanets in Noisy Data with Machine Learning
Backend
46
DEV Community
How to automatically find the batch size when using Accelerate with FSDP2? [D]
Backend
43
Reddit r/MachineLearning
Cross-Chain Bridge Risk Assessment: Aave V3
Backend
36
DEV Community
Comments0
No comments yet — be the first