Python Learning
5.76K subscribers
568 photos
2 videos
106 files
129 links
Python learning resources

Beginner to advanced Python guides, cheatsheets, books and projects.

For data science, backend and automation.
Join πŸ‘‰ https://rebrand.ly/bigdatachannels

DMCA: @disclosure_bds
Contact: @mldatascientist
Download Telegram
🐍 Python’s Hidden Loop Feature: for...else

πŸ‘‰ Did you know else isn't just for if statements?

Python has a unique feature almost never mentioned in beginner tutorials: you can attach an else block directly to a for or while loop.

πŸ”Ή How It Works

The else block executes ONLY if the loop finishes completely without hitting a break statement.

πŸ”Ή The Difference

❌ Traditional Way (Requires a messy flag variable):

found = False
for user in users:
if user == "Alex":
found = True
break

if not found:
print("User not found!")


βœ… Pythonic Way (Using for...else):

for user in users:
if user == "Alex":
print("User found!")
break
else:
print("User not found!")



πŸ”Ή Why Use It?

βœ”οΈ Eliminates unnecessary boolean flags (like found = True).
βœ”οΈ Cleaner, more readable syntax for search functions.
❀2πŸ‘1
python-cheat-sheet.pdf
155.6 KB
Python CheatSheet
❀2πŸ”₯1
⚑️ Python’s 1-Line Speed Booster: @lru_cache

πŸ‘‰ Did you know you can make slow Python functions run up to 100x faster by adding a single line of code?

Most tutorials skip functools.lru_cache, but it’s one of Python’s best built-in performance hacks.

πŸ”Ή How It Works

It automatically caches (remembers) the results of function calls. If you call the function with the same inputs again, Python skips the heavy computation and returns the saved answer instantly.

πŸ”Ή Code Comparison

❌ Slow (Re-calculates every single call):

def get_user_data(user_id):
# Imagine an expensive database query here
return fetch_from_db(user_id)


βœ… Very Fast (Remembers previous results):

from functools import lru_cache


@lru_cache(maxsize=128)
def get_user_data(user_id):
# Only runs ONCE per unique user_id
return fetch_from_db(user_id)



πŸ”Ή Use It to:

βœ”οΈ Speedup repetitive API calls, math calculations, or DB queries.
βœ”οΈ No third-party libraries needed (built into Python's standard library).
βœ”οΈ Prevent unnecessary server load.
❀1πŸ‘1