Showing posts with label Python Mistakes. Show all posts
Showing posts with label Python Mistakes. Show all posts

Friday, 16 January 2026

Day 30:Using == None Instead of is None


 

๐Ÿ Python Mistakes Everyone Makes ❌

Day 30: Using == None Instead of is None

Checking for None looks simple, but using the wrong comparison can lead to subtle bugs.


❌ The Mistake

value = None

if value == None:
print("Value is None")

This may work sometimes—but it’s not the correct way.


❌ Why This Is a Problem

  • ==checks value equality

  • Objects can override __eq__()

  • Comparison may return unexpected results

  • None is a singleton, not a value to compare


✅ The Correct Way

value = None

if value is None:
print("Value is None")

is checks identity, which is exactly what you want for None.


✔ Key Takeaways

✔ None exists only once in memory
✔ Use is None and is not None
✔ Avoid == for None checks


๐Ÿง  Simple Rule to Remember

๐Ÿ Compare to None using is, not ==

Day 29: Using map() Where List Comprehension is Clearer

 

๐Ÿ Python Mistakes Everyone Makes ❌

Day 29: Using map() Where List Comprehension Is Clearer

map() is powerful, but using it everywhere can make code harder to read. In many cases, a list comprehension is simpler and more Pythonic.


❌ The Mistake

numbers = [1, 2, 3, 4] squares = list(map(lambda x: x * x, numbers))
print(squares)

This works—but it’s not very readable.


❌ Why This Is a Problem

  • lambda inside map() reduces readability

  • Logic is harder to understand at a glance

  • Debugging is less intuitive

  • Goes against Python’s “readability counts” philosophy


✅ The Clearer Way

numbers = [1, 2, 3, 4] squares = [x * x for x in numbers]
print(squares)

Cleaner, clearer, and easier to maintain.


✔ When map() Makes Sense

  • When using a named function

  • When no complex logic is involved

squares = list(map(square, numbers))

๐Ÿง  Simple Rule to Remember

✔ Prefer list comprehensions for simple transformations
✔ Use map() only when it improves clarity
✔ Readability > cleverness
๐Ÿ Pythonic code is code others can easily read.

Wednesday, 14 January 2026

Day 28:Assuming finally won’t execute after return

 

๐Ÿ Python Mistakes Everyone Makes ❌

Day 28: Assuming finally Won’t Execute After return

This is a subtle Python behavior that surprises many developers.
Even after a return statement, Python still guarantees that the finally block runs.


❌ The Mistake

def example(): try: return "Success" finally: print("Cleanup code")

print(example())

Output:

Cleanup code
Success

Many expect the function to return immediately—but Python disagrees.


❌ Why This Fails?

  • finally is designed for guaranteed execution

  • Python executes finally before actually returning the value

  • This applies even if:

    • return is used

    • An exception is raised

    • break or continue is used

The function only returns after finally finishes.


✅ The Correct Understanding

Use finally when you must run cleanup code:

try: resource = open("file.txt") return resource.read() finally:
resource.close()

This ensures the file is closed—no matter how the function exits.


✔ Key Takeaways

✔ finally always executes
✔ It runs even after return
✔ Cleanup code belongs in finally


 Simple Rule to Remember

๐Ÿ finally = “run this no matter what”

Monday, 12 January 2026

Day 27: Comparing floats directly


 

๐Ÿ Python Mistakes Everyone Makes ❌

Day 27: Comparing Floats Directly

Floating-point numbers can look simple, but comparing them directly is one of the most common Python mistakes—especially for beginners.


❌ The Mistake

a = 0.1 + 0.2
print(a == 0.3) # False ๐Ÿ˜จ

Even though the math looks correct, the comparison fails.


✅ The Correct Way

import math a = 0.1 + 0.2
print(math.isclose(a, 0.3)) # True ✅


❌ Why This Fails?

  • Floats are stored in binary, not decimal

  • Some decimal numbers cannot be represented exactly

  • Small precision errors are introduced

  • Direct equality (==) checks exact matches

  • Results can be unexpected and buggy


๐Ÿง  Simple Rule to Remember

✔ Never compare floats using ==
✔ Use math.isclose() or a tolerance
✔ Think approximate, not exact

Comparing floats safely makes your code more reliable, accurate, and professional ๐Ÿš€

Sunday, 11 January 2026

Day 26: Using time.sleep() in Async Code

 

๐Ÿ Python Mistakes Everyone Makes ❌

Day 26: Using time.sleep() in Async Code

Async code is powerful—but one small mistake can completely block it.


❌ The Mistake

import time async def task(): print("Start") time.sleep(2)
print("End")

Looks harmless, right?
But this breaks async behavior.


๐Ÿค” Why This Is a Problem

  • time.sleep() blocks the entire event loop

  • No other async tasks can run during the sleep

  • Your “async” code becomes sync and slow

In async code, blocking = ๐Ÿšซ performance.


✅ The Correct Way

Use asyncio.sleep() instead:

import asyncio async def task(): print("Start") await asyncio.sleep(2)
print("End")

This pauses without blocking, allowing other tasks to run.


❌ Why the Mistake Is Dangerous

  • Freezes concurrent tasks

  • Ruins scalability

  • Causes confusing performance issues

  • Defeats the purpose of async programming


๐Ÿง  Simple Rule to Remember

✔ Never use time.sleep() in async code
✔ Always use await asyncio.sleep()
✔ Blocking calls don’t belong in async functions

๐Ÿ Async rule: If it blocks, it doesn’t belong in async def.

Day 25: Wrong Use of or in Conditions

 

Day 25: Wrong Use of or in Conditions

This is a classic Python gotcha that trips up beginners and even experienced developers.


❌ The Mistake

x = 3 if x == 1 or 2:
print("x is 1 or 2")

You might expect this to run only when x is 1 or 2…
But it always runs, no matter what x is.


๐Ÿค” Why This Happens

Python reads the condition like this:

if (x == 1) or (2):
  • x == 1 → True or False

  • 2 → always True (non-zero values are truthy)

So the whole condition is always True.


✅ The Correct Way

Option 1: Compare explicitly

if x == 1 or x == 2: print("x is 1 or 2")

Option 2 (Recommended): Use in

if x in (1, 2):
print("x is 1 or 2")

Cleaner, safer, and more Pythonic ✅


❌ Why the Mistake Is Dangerous

  • Conditions behave incorrectly

  • Bugs are hard to notice

  • Logic silently fails

  • Leads to unexpected program flow


๐Ÿง  Simple Rule to Remember

✔ or does not repeat comparisons
✔ Use in for multiple equality checks
✔ If it reads like English, it’s probably wrong ๐Ÿ˜„

# Think like Python, not English if x in (1, 2):
...

๐Ÿ Pro tip: When checking multiple values, in is almost always the best choice.

Saturday, 10 January 2026

Day 24:Thinking dict.keys() returns a list

 

Day 24: Thinking dict.keys() Returns a List

This is a very common misunderstanding especially for beginners. While dict.keys() looks like a list, it actually isn’t one.


❌ The Mistake

data = {"a": 1, "b": 2, "c": 3} keys = data.keys()
print(keys[0]) # ❌ TypeError

Why this fails: dict.keys() does not return a list.


✅ The Correct Way

data = {"a": 1, "b": 2, "c": 3}

keys = list(data.keys())
print(keys[0]) # ✅ Works

If you need indexing, slicing, or list operations—convert it to a list.


❌ Why This Fails

  • dict.keys() returns a dict_keys view object

  • View objects are:

    • Not indexable

    • Dynamically updated when the dictionary changes

  • Treating it like a list causes errors


๐Ÿง  Simple Rule to Remember

✔ dict.keys() ≠ list
✔ Convert to a list if you need indexing
✔ Use it directly in loops for better performance

for key in data.keys():
print(key)

๐Ÿ Pro tip: View objects are efficient and memory-friendly use lists only when necessary.

Friday, 9 January 2026

Day 23: Using Recursion Without a Base Case

 

๐Ÿ Python Mistakes Everyone Makes ❌

Day 23: Using Recursion Without a Base Case

Recursion is powerful, but without a base case, it becomes dangerous. A recursive function must always know when to stop.


❌ The Mistake

def countdown(n): print(n)
countdown(n - 1)

This function keeps calling itself endlessly.


✅ The Correct Way

def countdown(n): if n == 0: # base case return print(n)
countdown(n - 1)

Here, the base case (n == 0) tells Python when to stop making recursive calls.


❌ Why This Fails

  • No condition to stop recursion

  • Function keeps calling itself forever

  • Leads to RecursionError: maximum recursion depth exceeded

  • Can crash your program


๐Ÿง  Simple Rule to Remember

✔ Every recursive function must have a base case
✔ The base case defines when recursion ends
✔ No base case → infinite recursion


๐Ÿ Pro tip: Always ask yourself, “When does this recursion stop?”

Monday, 5 January 2026

Day 22 : Ignoring Traceback Messages

 

๐Ÿ Python Mistakes Everyone Makes ❌

Day 22: Ignoring Traceback Messages

When your Python program crashes, the traceback is not noise — it’s your best debugging guide. Ignoring it slows you down and turns debugging into guesswork.


❌ The Mistake

print("Program crashed ๐Ÿ˜ต")

Reacting to errors without reading the traceback means you’re missing critical information about what actually went wrong.


✅ The Correct Way

Traceback (most recent call last): 
File "app.py", line 5, in <module>
 print(numbers[5])
 IndexError: list index out of range

This message clearly tells you:

  • What error occurred (IndexError)

  • Where it happened (file name and line number)

  • Why it happened (index out of range)


❌ Why Ignoring Tracebacks Fails

    Tracebacks explain exactly what went wrong
  • They show where the error occurred

  • Ignoring them leads to guesswork debugging

  • You miss valuable learning opportunities


๐Ÿง  Simple Rule to Remember

✔ Always read the full traceback
✔ Start from the last line (that’s the real error)
✔ Use it as your step-by-step debugging guide


๐Ÿ Pro tip: The traceback is Python trying to help you don’t ignore it!

Saturday, 3 January 2026

Day 21:Catching exceptions too broadly


๐Ÿ Python Mistakes Everyone Makes ❌

Day 21: Catching Exceptions Too Broadly

Handling errors is important, but catching everything can hide real problems.


❌ The Mistake

try: result = 10 / x
except:
print("Something went wrong")

This catches all exceptions, including ones you didn’t expect.


❌ Why This Fails

  • Hides the real error

  • Makes debugging difficult

  • Can mask serious bugs

  • Swallows unexpected exceptions


✅ The Correct Way

try: result = 10 / x
except ZeroDivisionError:
print("Cannot divide by zero")

Catch only the exceptions you expect.


๐Ÿง  Simple Rule to Remember

✔ Catch specific exceptions
✔ Avoid bare except:
✔ Let unexpected errors fail loudly


Friday, 2 January 2026

Day 20: Not using with for file handling

 

Day 20: Not Using with for File Handling

File handling is common in Python, but many developers forget to use the safest and cleanest approach.


❌ The Mistake

file = open("data.txt", "r") data = file.read()
file.close()

This works only if everything goes right.
If an error occurs before file.close(), the file stays open.


❌ Why This Fails

  • Files consume system resources

  • Forgetting close() causes resource leaks

  • Can lead to file locks

  • Makes error handling harder


✅ The Correct Way

with open("data.txt", "r") as file:
data = file.read()

Using with ensures the file is always closed, even if an exception occurs.


๐Ÿง  Simple Rule to Remember

✔ Always use with when working with files
✔ Safe, clean, and Pythonic

Wednesday, 31 December 2025

Day 19:Using global variables unnecessarily


 

๐Ÿ Python Mistakes Everyone Makes ❌

๐Ÿ Day 19: Using Global Variables Unnecessarily

Global variables may look convenient, but they often create more problems than they solve—especially as your code grows.


❌ The Mistake

count = 0 def increment(): global count
count += 1

This function depends on a global variable and modifies it directly.


❌ Why This Is a Problem

Using globals:

  • Makes code harder to debug

  • Causes unexpected side effects

  • Breaks function reusability

  • Couples logic tightly to external state


✅ The Correct Way

def increment(count): return count + 1

count = increment(count)

Now the function is predictable, testable, and reusable.


✔ Why This Is Better

✔ Functions depend only on inputs
✔ No hidden state
✔ Easier to test and debug
✔ Cleaner design


๐Ÿง  Simple Rule to Remember

๐Ÿ Functions should depend on arguments, not globals
๐Ÿ Pass data in, return data out

Day 18:Ignoring enumerate()

 

๐Ÿ Python Mistakes Everyone Makes ❌

๐Ÿ Day 18: Ignoring enumerate()

When looping through a list, many developers manually manage counters—without realizing Python already provides a cleaner and safer solution.


❌ The Mistake

items = ["a", "b", "c"] i = 0 for item in items:
print(i, item)
i += 1

This works, but it’s not ideal.


❌ Why This Is a Problem

Manually managing counters:

  • Adds unnecessary code

  • Increases the chance of off-by-one errors

  • Makes the loop harder to read


✅ The Correct Way

items = ["a", "b", "c"]

for i, item in enumerate(items):
print(i, item)

Cleaner, clearer, and safer.


✔ Key Benefits of enumerate()

✔ Automatically tracks the index
✔ No manual counter needed
✔ Improves readability
✔ Reduces bugs


๐Ÿง  Simple Rule to Remember

๐Ÿ Use enumerate() when you need both index and value

Day 17:Assuming list copy = deep copy


 

๐Ÿ Python Mistakes Everyone Makes ❌

๐Ÿ Day 17: Assuming list.copy() = Deep Copy

Copying lists in Python can be tricky especially when nested lists are involved.


❌ The Mistake

a = [[1, 2], [3, 4]] b = a.copy() b[0].append(99)
print(a)

You might expect a to remain unchanged, but it doesn’t.


❌ Why This Fails?

list.copy() creates a shallow copy.
That means:

  • The outer list is copied

  • Inner (nested) lists are still shared

So modifying a nested list in b also affects a.


✅ The Correct Way

import copy a = [[1, 2], [3, 4]] b = copy.deepcopy(a)

b[0].append(99)
print(a)

Now a stays untouched because everything is fully copied.


✔ Key Takeaways

✔ list.copy() → shallow copy
✔ Nested objects remain shared
✔ Use deepcopy() for independent copies


๐Ÿง  Simple Rule to Remember

๐Ÿ Shallow copy → shared inner objects
๐Ÿ Deep copy → fully independent copy

Day 16:Modifying a list while looping over it

 

๐ŸPython Mistakes Everyone Makes ❌

Day 16: Modifying a List While Looping Over It

One common Python pitfall is changing a list while iterating over it. This often leads to skipped elements and unexpected results.


❌ The Mistake

numbers = [1, 2, 3, 4] for n in numbers: if n % 2 == 0: numbers.remove(n)

print(numbers)

This code does not behave as expected.


✅ The Correct Way

numbers = [1, 2, 3, 4] for n in numbers[:]: # loop over a copy if n % 2 == 0: numbers.remove(n)

print(numbers)

By looping over a copy of the list, the original list can be safely modified.


❌ Why This Fails?

When you modify a list while looping over it, Python’s iterator gets out of sync.
This causes elements to be skipped or processed incorrectly.


✔ Key Points

  • Modifying a list during iteration causes logic bugs

  • Iteration order changes when elements are removed


๐Ÿง  Simple Rule to Remember

  • Don’t modify a list while looping over it

  • Loop over a copy or create a new list


๐Ÿ”‘ Key Takeaway

If you need to filter or modify a list, prefer:

  • looping over a copy (numbers[:])

  • or using list comprehensions for cleaner, safer code

Day 15:Misunderstanding bool("False")

 

๐ŸPython Mistakes Everyone Makes ❌

Day 15: Misunderstanding bool("False")

Many beginners assume the string "False" evaluates to False.
In Python, that’s not true.


❌ The Mistake

print(bool("False"))

Output:

True

This often surprises new Python developers.


✅ The Correct Way

value = "False"
result = value.lower() == "true"
print(result)

Output:

False

Here, you explicitly check the meaning of the string, not just its existence.


❌ Why This Fails?

In Python, any non-empty string is truthy, even "False".

bool() checks emptiness, not the word’s meaning.


✔ Key Points

  • bool() checks if a value is empty or not

  • "False" is still a non-empty string

  • Meaning must be checked manually


๐Ÿง  Simple Rule to Remember

  • Non-empty string → True

  • Empty string → False


๐Ÿ”‘ Takeaway

Never rely on bool() to interpret string values like "True" or "False".
Always compare the string content explicitly.

Tuesday, 30 December 2025

Day 13: Expecting range() to Return a List ❌

Python Mistakes Everyone Makes ❌

Day 13: Expecting range() to Return a List

Many beginners assume range() gives a list. It doesn’t.


❌ The Mistake

numbers = range(5)
print(numbers[0])

✅ The Correct Way

numbers = list(range(5))
print(numbers[0])

Convert it to a list if you actually need one.


❌ Why This Fails?

range() returns a range object, not a list.
It’s iterable but doesn’t store all values in memory.


✔ Key Points

  • range() → returns a range object

  • Use list(range()) when a real list is required


๐Ÿง  Simple Rule to Remember

  • range() is memory-efficient

  • It behaves like a sequence, not a list

 

Monday, 29 December 2025

Day 12: Not closing files

 



๐ŸPython Mistakes Everyone Makes ❌

Day 12: Not Closing Files

Opening files is easy in Python—but forgetting to close them is a common mistake.


❌ The Mistake

file = open("data.txt", "r")
content = file.read()

The file is opened but never closed.


✅ The Correct Way

with open("data.txt", "r") as file:
content = file.read()

Using with ensures the file is closed automatically.


❌ Why This Fails?

Open files consume system resources.
If you don’t close them, it can lead to memory leaks and file locks.


✔ What Can Go Wrong?

  • Files may stay open longer than needed

  • Can cause issues in larger applications


๐Ÿง  Simple Rule to Remember

  • Always use with open(...)

  • Python will close the file for you


Day 11:Using += thinking it creates a new object

 


๐Ÿ Python Mistakes Everyone Makes ❌

Day 11: Using += Thinking It Creates a New Object

Many Python beginners assume += always creates a new object.
That’s not always true.


❌ The Mistake

a = [1, 2, 3]
b = a a += [4]

print(b)

Output:

[1, 2, 3, 4]

❌ Why this surprises people?

Because += modifies the object in place for mutable types like lists.

  • a and b both reference the same list

  • Using += changes the original object

  • Both variables see the change


✅ The Correct Understanding

a = [1, 2, 3] b = a.copy() a += [4]

print(b)

Output:

[1, 2, 3]

Now a and b are different objects.


๐Ÿง  Simple Rule to Remember

  • += on mutable objects → modifies in place

  • += on immutable objects → creates a new object

Example:

x = 5
x += 1 # new integer object created

✅ Key Takeaway

+= does not always create a new object.
Understanding mutability helps avoid unexpected bugs.



Day 10: Assuming 0, "", [] are errors

 

๐ŸPython Mistakes Everyone Makes ❌

Day 10: Assuming 0, "", and [] are Errors

One common Python mistake is treating empty or zero values as errors.


❌ The Mistake

x = 0 if not x:
print("Error occurred")

At first glance, this looks fine. But it’s misleading.


✅ The Correct Way

x = 0 if x is None: print("Error occurred") else: print("Valid value")
❌ Why This Fails?

Because 0, "", and [] are valid values, not errors.
Using if not x: only checks emptiness, not whether something actually went wrong.


✔ What if not x Really Means

  • It checks if a value is falsy

  • It does not mean an error occurred


๐Ÿง  Simple Rule to Remember

Falsy values in Python:

1.  0

2.""(empty string)

3.[](empty list)

4.{}(empty dict)

5.None

6.False 

Falsy ≠ Error


๐Ÿ”‘ Key Takeaway

Use is None when checking for missing or invalid data.
Use if not x only when you truly mean empty.

Popular Posts

Categories

100 Python Programs for Beginner (118) AI (181) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (28) Azure (8) BI (10) Books (261) Bootcamp (1) C (78) C# (12) C++ (83) Course (84) Coursera (299) Cybersecurity (29) Data Analysis (25) Data Analytics (16) data management (15) Data Science (242) Data Strucures (15) Deep Learning (99) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (18) Finance (9) flask (3) flutter (1) FPL (17) Generative AI (51) Git (9) Google (47) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (220) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (12) PHP (20) Projects (32) Python (1238) Python Coding Challenge (970) Python Mistakes (30) Python Quiz (396) Python Tips (5) Questions (3) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (45) Udemy (17) UX Research (1) web application (11) Web development (8) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)