IndentationError: unexpected indent – Python

If you are learning Python, you may have seen this error:

IndentationError: unexpected indent

Unlike many other languages, indentation is part of Python syntax.
This error appears when Python finds spaces or tabs where it does not expect them.

Let’s understand this in the simplest way.


What Does This Error Mean?

Python found extra spaces or tabs at the beginning of a line where they are not allowed.

In Python, indentation must follow strict rules.
You cannot add random spaces like in Java or JavaScript.


❌ Example 1 – Extra Space at the Start

 print("Hello World")

Output

IndentationError: unexpected indent

✅ Fix

Remove the extra space:

print("Hello World")

❌ Example 2 – Indent Without a Block

name = "Alice"
print(name)

Python does not expect indentation after a normal statement.

✅ Fix

name = "Alice"
print(name)

❌ Example 3 – Mixing Tabs and Spaces

def show():
print("Hello") # tab
print("World") # spaces

Mixing tabs + spaces confuses Python.

✅ Fix

Use only spaces (recommended):

def show():
print("Hello")
print("World")

❌ Example 4 – Wrong Indentation Level

if True:
print("Hi")

Code inside if must be indented.

✅ Fix

if True:
print("Hi")

🧠 Why Python Is Strict About Indentation

In Python, indentation:

  • Defines code blocks
  • Replaces { } used in other languages
  • Makes code more readable

So Python treats wrong indentation as a syntax error.


✅ Simple Rules to Avoid This Error

  1. Do not add spaces at the beginning randomly
  2. Indent only after:
    • if, for, while, def, class, try
  3. Use either spaces OR tabs — never both
  4. Recommended: use 4 spaces per indent

🛠 Best Practice in VS Code / Editors

  • Enable: Convert tabs to spaces
  • Set indentation to 4 spaces
  • Turn on: Show whitespace

🎯 Interview One-Liner

IndentationError: unexpected indent occurs when Python finds indentation at a place where it is not syntactically allowed.


✨ Final Thought

Python is basically saying:

“I didn’t ask for indentation here!”

Fix the spaces → error gone 🚀

SyntaxError: unterminated string literal – Python

If you are learning Python, one of the first errors you may see is:

SyntaxError: unterminated string literal

This error looks scary, but the reason is very simple:

Python found the start of a string but could not find where it ends.

Let’s understand this with easy examples.


❌ Why This Error Happens

In Python, strings must start and end with the same quote:

  • 'single quotes'
  • "double quotes"

If Python cannot find the closing quote, it throws:

👉 SyntaxError: unterminated string literal


🧪 Example 1 – Missing Closing Quote

message = "Hello World

Output

SyntaxError: unterminated string literal

✅ Fix

message = "Hello World"

🧪 Example 2 – Mixed Quotes

text = "Python is fun'

Started with double quote "
Ended with single quote '

Python gets confused → error.

✅ Fix

Use the same quotes:

text = "Python is fun"

or

text = 'Python is fun'

🧪 Example 3 – Multiline String Mistake

info = "This is line one
This is line two"

Normal quotes cannot span multiple lines.

✅ Fix 1 – Use Triple Quotes

info = """This is line one
This is line two"""

✅ Fix 2 – Use newline character

info = "This is line one\nThis is line two"

🧪 Example 4 – Quote Inside String

msg = "It's a nice day"

This works because outer quotes are double quotes.

But this fails:

msg = 'It's a nice day'

✅ Fix

Use escape character:

msg = 'It\'s a nice day'

or switch quotes:

msg = "It's a nice day"

🧠 Simple Rules to Avoid This Error

  1. Always close strings with the same quote you opened.
  2. For multiline text → use triple quotes.
  3. If your text contains quotes → use:
    • opposite quotes, or
    • escape character \.

✅ Quick Checklist

MistakeSolution
Missing quoteAdd closing quote
Mixed quotesUse same quote type
Multiline stringUse """ """
Quote inside textEscape or change quote

🎯 Interview One-Liner

“SyntaxError: unterminated string literal occurs when Python cannot find the closing quote of a string.”


✨ Final Thought

This error is not about logic —
it’s just Python saying:

“Hey, you started a string… but never told me where it ends!”

Fix the quotes → error gone 🚀

Understanding JavaScript sort() with a Simple Example

Let’s look at this JavaScript code:

const values = [32, 25, 120];
const result = values.sort();
console.log(result);

✅ Output

[120, 25, 32]

At first glance, this output feels wrong, right?
Why didn’t JavaScript sort the numbers in ascending order?

Let’s understand why this happens.


How sort() Actually Works in JavaScript

By default, JavaScript’s sort() method:

Converts elements to strings and compares them lexicographically (dictionary order).

This is the key reason for the unexpected result.


Step-by-Step Explanation

Original array:

[32, 25, 120]

JavaScript internally converts numbers to strings:

["32", "25", "120"]

Now it sorts them alphabetically:

  • "120" comes before "25" → because "1" < "2"
  • "25" comes before "32" → because "2" < "3"

So the final order becomes:

["120", "25", "32"]

Converted back to numbers:

[120, 25, 32]

Important Warning

This behavior can easily cause bugs, especially when sorting numbers.

Do NOT rely on default sort() for numeric sorting.


Correct Way to Sort Numbers

To sort numbers properly, you must provide a compare function.

Ascending Order

values.sort((a, b) => a - b);
console.log(values);

✅ Output:

[25, 32, 120]

Descending Order

values.sort((a, b) => b - a);
console.log(values);

✅ Output:

[120, 32, 25]

Why Does JavaScript Work This Way?

JavaScript was originally designed to sort strings.

So:

  • Sorting names → works perfectly
  • Sorting numbers → needs extra instruction

This is why the compare function exists.


Key Takeaways

  • array.sort() sorts strings by default
  • Numbers are converted to strings internally
  • Always use a compare function for numeric sorting
  • sort() mutates the original array

Interview One-Liner

JavaScript’s sort() method sorts values as strings by default, so numeric sorting requires a custom compare function.


✨ Final Thought

This is one of the most common JavaScript interview traps.

If you understand this:

  • You avoid bugs
  • You write safer code
  • You stand out in interviews

Small detail. Big impact 🚀


Microservices Best Practices (A Practical Guide)

Microservices architecture helps teams build scalable, flexible, and independently deployable systems.
But without the right practices, microservices can quickly become harder than a monolith.

This blog covers proven microservices best practices that work in real-world systems.


1. Keep Services Small and Focused

Each microservice should:

  • Do one business function
  • Have a single responsibility
  • Be easy to understand and maintain

❌ Bad:

One service handling users, orders, and payments

✅ Good:

  • User Service
  • Order Service
  • Payment Service

2. Each Service Owns Its Data

A microservice should own its own database.

❌ Don’t:

  • Share databases between services

✅ Do:

  • One database per service
  • Communicate via APIs

This avoids tight coupling and unexpected failures.


3. Use API-Based Communication

Services should communicate using:

  • REST APIs
  • gRPC
  • Messaging (Kafka, RabbitMQ)

Avoid:

  • Direct database access between services

4. Implement Service Discovery

In microservices, services scale up and down dynamically.

Use service discovery so services can:

  • Find each other automatically
  • Avoid hard-coded IPs or URLs

Examples:

  • Eureka
  • Consul
  • Kubernetes Service Discovery

5. Design for Failure

Failures are normal in distributed systems.

Best practices:

  • Use Circuit Breakers
  • Add timeouts
  • Implement retries with limits

Goal:

Fail fast and recover gracefully


6. Apply Rate Limiting

Protect your services from:

  • Traffic spikes
  • Abuse
  • Overload

Rate limiting ensures:

  • System stability
  • Fair usage

7. Centralized Logging and Monitoring

With many services, debugging becomes difficult.

Use:

  • Centralized logs (ELK, Loki)
  • Metrics (Prometheus)
  • Tracing (Jaeger, Zipkin)

This helps:

  • Identify failures quickly
  • Monitor system health

8. Secure Your Services

Security is critical in microservices.

Best practices:

  • Use API gateways
  • Implement authentication & authorization
  • Secure service-to-service communication (JWT, mTLS)

Never trust internal traffic blindly.


9. Make APIs Idempotent

Clients may retry requests due to network issues.

Design APIs so:

  • Multiple identical requests produce the same result
  • Duplicate actions are avoided

Especially important for:

  • Payments
  • Order creation
  • Updates

10. Use Auto Scaling

Traffic changes over time.

Auto scaling:

  • Adds resources during high load
  • Removes resources during low usage

This improves:

  • Performance
  • Cost efficiency

11. Test Services Independently

Test at multiple levels:

  • Unit tests
  • Integration tests
  • Contract tests

Each service should be:

  • Testable
  • Deployable independently

12. Avoid Over-Engineering

Microservices are powerful, but not always necessary.

Avoid microservices if:

  • Team is very small
  • Application is simple
  • No scaling requirement

Start simple, evolve when needed.


Summary: Microservices Best Practices Checklist

  • ✔ Small, focused services
  • ✔ Independent databases
  • ✔ API-based communication
  • ✔ Service discovery
  • ✔ Fault tolerance
  • ✔ Rate limiting
  • ✔ Centralized logging
  • ✔ Strong security
  • ✔ Idempotent APIs
  • ✔ Auto scaling

🎯 Final Thought

Microservices are not about splitting code —
they are about splitting responsibility wisely.

When designed correctly, microservices bring scalability, resilience, and faster development.


How Optional Chaining (?.) Saves You from Runtime Errors

While working with JavaScript objects, we often access nested properties.
But what if one property doesn’t exist?

👉 That’s where optional chaining (?.) comes to the rescue.


❌ The Common Problem

Consider this example:

const user = {};
console.log(user.profile.name);

❌ This throws an error:

Cannot read properties of undefined

Why?
Because profile does not exist, and JavaScript tries to read name from undefined.


✅ The Solution: Optional Chaining (?.)

Now look at this:

const user = {};
console.log(user.profile?.name);

✅ Output:

undefined

No error.
The program continues smoothly.


What Does ?. Actually Do?

In very simple words:

If the value exists → access it
If it doesn’t → stop and return undefined

That’s it. No crash. No exception.


Very Simple Real-Life Analogy

Imagine asking someone:

“If you have my book, please give it.
If not, that’s okay.”

Optional chaining behaves the same way 😄


Simple API Response Example

const response = {
data: {
user: {
name: "Raj"
}
}
};
console.log(response.data?.user?.name); // Raj
console.log(response.data?.user?.age); // undefined

Instead of breaking the app, JavaScript safely returns undefined.


Before vs After Optional Chaining

❌ Old Way (Using &&)

const name = user && user.profile && user.profile.name;

✅ Modern Way (Optional Chaining)

const name = user.profile?.name;

✔ Cleaner
✔ Easier to read
✔ Less error-prone


⚠️ Important Things to Remember

  • Optional chaining only reads values
  • It does not create properties
  • It works only with:
    • Objects
    • Arrays
    • Functions

❌ This is invalid:

user.profile?.name = "Raj";

Optional Chaining with Arrays

const users = [];
console.log(users[0]?.name);

✅ Output:

undefined

No error even if the array is empty.


When Should You Use Optional Chaining?

✅ API responses
✅ Nested objects
✅ Data from backend
✅ Dynamic data

❌ When you are sure the value always exists


Interview One-Liner

Optional chaining (?.) allows safe access to nested properties without throwing errors when values are null or undefined.


Final Thoughts

Optional chaining may look small, but it prevents big runtime crashes.

One operator.
Cleaner code.
Fewer bugs.

That’s the power of ?.


If this post is helpful to you don’t forget to like and subscribe !!