๐ Day 2/150 – Add Two Numbers in Python
Let’s explore different ways to do it.
1️⃣ Basic Addition (Direct Method)
This is the most straightforward way.
a = 10
b = 5
result = a + b
print(result)
✅ Simple
✅ Beginner-friendly
✅ Most commonly used
If you're just starting Python, this is your foundation.
2️⃣ Taking User Input
Now let’s make it interactive.
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Sum:", a + b)
Why int()?
Because input() always returns a string.
We convert it into an integer before adding.
๐ก This teaches:
Type conversion
Real-world program interaction
3️⃣ Using a Function
Functions make your code reusable.
def add_numbers(x, y):
return x + y
print(add_numbers(10, 5))
Why use functions?
Clean code
Reusability
Better structure
Important for larger projects
This is how professionals write code.
4️⃣ Using Lambda (One-Line Function)
For short operations, Python allows anonymous functions.
add = lambda x, y: x + y
print(add(10, 5))
When to use?
Quick operations
Functional programming
Passing functions as arguments
Short. Elegant. Powerful.
5️⃣ Using sum() Built-in Function
numbers = [10, 5]
print(sum(numbers))
sum() is useful when adding multiple values.
Example:
print(sum([1, 2, 3, 4, 5]))
This is more scalable.
6️⃣ Using Recursion
def add(a, b):
if b == 0:
return a
return add(a + 1, b - 1)
print(add(10, 5))
This method doesn’t use + directly in the usual way.
It demonstrates:
Recursion
Base case
Recursive case
Stack behavior
⚠️ Not practical for real-world addition, but great for understanding logic.
๐ฏ What Should You Actually Use?
| Situation | Best Method | ||
|---|---|---|---|
| Normal programs |
| ||
| Reusable logic | Function | ||
| Many numbers | sum() | ||
| Interview discussion | Recursion / Bitwise | ||
| Functional programming | Lambda |
๐ญ Why Learn Multiple Ways?
Because programming isn’t about memorizing syntax.
It’s about:
-
Understanding concepts
-
Improving problem-solving
-
Writing clean code
-
Thinking differently
The more ways you know, the sharper your logic becomes.
.png)

0 Comments:
Post a Comment