General
Python Functions: Why They changed My code
0 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
Related posts
The Ford Privacy Promise: You're in Control of Your Data
0Hacker News

115 Blog Posts To Learn About Movies
0HackerNoon
Music Through Your Cheekbones: How Bone-Conduction Headphones Work and Why They Sound Different
0HackerNoon
Turning elementary arithmetic into an enterprise-wide operational capability
0Hacker News New
Anthropic's growth just flattened
0Hacker News New
h1: A Taste of the Bitter Lesson in Automated Theorem Proving
0Hacker News New