Python Learning
Ir al canal en Telegram
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
Mostrar más5 758
Suscriptores
+224 horas
-137 días
-7730 días
Archivo de publicaciones
5 758
Repost from Programming Quiz Channel
Topic: Python
🔍 Quick look before the question:
def outer():
x = 10
def inner():
nonlocal x
x += 5
return x
return inner
f = outer()
print(f())
print(f())5 758
🐍 Python’s Secret Memory Saver:
__slots__ ⚡️
👉 Most Python tutorials teach you Object-Oriented Programming (OOP) using self.variable = value. But almost none mention what happens under the hood or how it can quietly eat up your RAM.
When you create thousands or millions of object instances, Python’s default behavior wastes a massive amount of memory. Here is how __slots__ fixes that.
——————————
🔹 1. The Hidden Problem with Default Python Classes
By default, Python stores an object's attributes in a dynamic dictionary called __dict__.
👉 Why this is a problem:
❌ Dictionaries are flexible, but extremely memory-heavy.
❌ Every single instance gets its own dictionary overhead.
❌ If you instantiate 100,000 objects, your application’s RAM usage skyrockets.
——————————
🔥 2. The Solution: __slots__
__slots__ tells Python:
Do not create a dynamic
__dict__ for this class. Only allow these specific attribute names.—————————— 🔹 3. Standard Class vs. Slotted Class ❌ Standard Class (Uses Heavy
__dict__):
class DataPoint:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
✅ Optimized Class with __slots__:
class DataPoint:
# Restrict attributes & eliminate __dict__
__slots__ = ("x", "y", "z")
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
——————————
📊 4. The Real-World Impact
By adding that single line of code (__slots__):
✔️ ~60% to 70% reduction in memory usage across large object lists.
✔️ Faster attribute access (up to 20% faster speed because Python skips dictionary lookups).
——————————
⚠️ 5. The Trade-Off (What You Must Know)
Because __slots__ locks down your object structure:
❌ You cannot dynamically add new attributes at runtime (e.g., point.new_var = 10 will throw an AttributeError).
——————————
❔ 6. When Should You Use It?
✔️ Working with huge datasets or simulation objects in memory.
✔️ Building high-performance backend microservices.
✔️ Designing lightweight data structures (like custom Nodes, Vectors, or Points).5 758
🚀 50 Python Project Ideas
Whether you're a beginner or an experienced Python developer, building projects is the fastest way to improve your skills. Here's a curated list of 50 Python project ideas!
🟢 Beginner
1. Calculator
2. To-Do List App
3. Number Guessing Game
4. Password Generator
5. Dice Rolling Simulator
6. Rock Paper Scissors Game
7. Countdown Timer
8. Unit Converter
9. Digital Clock
10. Contact Book
11. Expense Tracker
12. BMI Calculator
13. QR Code Generator
14. Quiz Application
15. Hangman Game
🟡 Intermediate
16. Weather App (API)
17. Currency Converter
18. URL Shortener
19. File Organizer
20. PDF Merger & Splitter
21. Bulk Image Resizer
22. YouTube Video Downloader
23. Web Scraper
24. Email Automation Tool
25. News Aggregator
26. Markdown to HTML Converter
27. Flashcard Learning App
28. Voice Assistant
29. Chat Application
30. Music Player
🔴 Advanced
31. AI Chatbot
32. Face Recognition Attendance System
33. Object Detection with YOLO
34. Sentiment Analysis Tool
35. Fake News Detector
36. Stock Price Prediction
37. Recommendation System
38. Resume Screening System
39. AI Image Caption Generator
40. Handwritten Digit Recognition
⚡️ Automation & Dev Tools
41. Website Uptime Monitor
42. Automated Backup Tool
43. File Encryption Tool
44. Network Port Scanner
45. Password Manager
46. Typing Speed Tester
47. Clipboard Manager
48. WiFi Password Viewer (For Your Own Device)
49. API Testing Tool
50. Personal Finance Dashboard
💡 Which project are you planning to build next? Let us know in the comments! 👇
5 758
🧠 dict.get() in Python
Suppose you have this dictionary.
user = {
"name": "Alice",
"age": 24
}
Now you try to access a key that doesn't exist.
print(user["email"])
🔻Python raises:
KeyError: 'email'Sometimes that's exactly what you want. A missing key should crash the program. But often, a missing value is perfectly normal. Instead of checking manually:
if "email" in user:
email = user["email"]
else:
email = None
🟢 Python provides:
email = user.get("email")
If the key exists, you get its value.
If it doesn't, you get None instead of a crash.
You can even choose a default value.
email = user.get("email", "Not provided")
👉 get() isn't shorter just for the sake of being shorter. It expresses the idea that a missing key is expected.5 758
🐍 Python Type Checking
🔹 What is Type Checking?
Type checking is the process of checking the data type of a value or variable. Python provides several ways to do this.
age = 17
name = "Ted"
skills = ["Python", "AI", "Data Science"]
print(type(age)) # <class 'int'>
print(type(name)) # <class 'str'>
print(type(skills)) # <class 'list'>
🔹 Using isinstance()
isinstance() is often more useful when you want to check whether a value belongs to a particular type.
age = 17
if isinstance(age, int):
print("Age is an integer")
🔹 Type Hints
Python also supports type hints, which make your code easier to understand and allow tools such as IDEs and static type checkers to detect potential problems.
def calculate_total(price: float, quantity: int) -> float:
return price * quantity
Here:
price: float → expected to be a decimal number
quantity: int → expected to be an integer
-> float → expected return type
📌 Key takeaway:
Python is dynamically typed, but that doesn't mean you should ignore types. Using type(), isinstance(), and type hints can make your Python code more reliable and easier to maintain.5 758
⚡️ Why Is This Loop So Slow?
Imagine you're checking whether thousands of usernames exist.
for username in usernames:
if username in banned_users:
...
If banned_users is a list, Python checks one element at a time.
Alice? Bob? Charlie? David? ...For every lookup. Now imagine
banned_users is a set. Python doesn't search one by one. It uses a hash table to jump directly to where the value should be.
That's why changing this:
banned_users = [...]into this:
banned_users = {...}
can dramatically speed up membership checks without changing the rest of your code.5 758
📖 Reading Python Error Messages
Suppose you see this.
TypeError: can only concatenate str (not "int") to strInstead of panicking, read it from left to right. TypeError → The operation uses the wrong data type. str → Python found a string. int → It also found an integer. 👉 You're trying to combine two incompatible types.
5 758
📚 10 Python Modules You Probably Didn't Know Existed
1.
textwrap - Format long blocks of text.
2. difflib - Compare files or strings.
3. fractions - Work with exact fractions.
4. decimal - High precision decimal arithmetic.
5. calendar - Generate calendars programmatically.
6. uuid - Generate unique IDs.
7. secrets - Create cryptographically secure tokens.
8. pprint - Print nested data structures beautifully.
9. platform - Detect operating system information.
10. getpass - Securely read passwords from the terminal.5 758
⚡️ append() vs extend()
These two methods look similar, but they do completely different things.
numbers = [1, 2, 3]
numbers.append([4, 5])
print(numbers)
Output:
[1, 2, 3, [4, 5]]Now compare it with:
numbers = [1, 2, 3]
numbers.extend([4, 5])
print(numbers)
Output:
[1, 2, 3, 4, 5]👉
append() adds one object.
👉 extend() adds every element.
This small difference causes countless beginner bugs.5 758
📦 What Should You Learn After Python Basics?
✅ Functions & Modules
⬇️
✅ Object-Oriented Programming
⬇️
✅ File Handling
⬇️
✅ Exception Handling
⬇️
✅ Virtual Environments
⬇️
✅ Git & GitHub
⬇️
✅ Choose a Path:
• Web Development
• Automation
• Data Science
• Machine Learning
• Cybersecurity
• Backend APIs
Python is just the language.
Your specialization is what turns it into a career.
5 758
Python Script to Retrieve Saved Wi-Fi Passwords (Windows)
Someone requested this… We thought it might help.
import subprocess
def get_wifi_passwords():
# To get list of all saved Wi-Fi profiles
profiles_data = subprocess.check_output(['netsh', 'wlan', 'show', 'profiles']).decode('utf-8', errors="ignore").split('\n')
profiles = [line.split(":")[1].strip() for line in profiles_data if "All User Profile" in line]
print("\nSaved Wi-Fi Networks & Passwords:\n" + "-"*40)
for profile in profiles:
try:
# To get password for each profile
profile_info = subprocess.check_output(
['netsh', 'wlan', 'show', 'profile', profile, 'key=clear']
).decode('utf-8', errors="ignore").split('\n')
password = [line.split(":")[1].strip() for line in profile_info if "Key Content" in line]
print(f"Network : {profile}")
print(f"Password: {password[0] if password else 'None / Open Network'}\n")
except:
print(f"Network : {profile}")
print("Password: Unable to retrieve\n")
if __name__ == "__main__":
get_wifi_passwords()
💻 How to use the above code:
1. Open any text editor (Notepad, VS Code, etc.)
2. Copy and paste the code above
3. Save the file as wifi_passwords.py
4. Open Command Prompt or PowerShell as Administrator
5. Navigate to the folder where you saved the file
6. Run the command:
python wifi_passwords.py
✅ The script will list all the Wi-Fi networks that are saved on your computer along with their passwords.
⚠️ This only works for networks that are already saved on your Windows PC. It cannot crack or find passwords of networks you have never connected to.5 758
Python Notes for AI was requested by one of you. And here it is...
You can drop any future resource requests here.
5 758
🧠 Think Like Python
Suppose you want to know if a username exists.
🔻 Many beginners write:
found = False
for user in users:
if user == "Alex":
found = True
break
🟢 Python gives you a simpler solution.
found = "Alex" in users
Less code. More readable. Usually faster to understand.
Whenever Python has a built-in way to express an idea, prefer it.5 758
Repost from Programming Quiz Channel
What exception does Python raise when you divide by zero?
