🐍 Stop Breaking Your Code Before It Even Runs You spent hours thinking about the logic. You wrote the script. You hit run... and it crashes immediately. Why? Sometimes, it’s as simple as what you named your variable. In Python, "Identifiers" (names for variables, functions, etc.) are the foundation of clean code. But they have strict rules. If you break them, Python breaks. Here is your cheat sheet for The 4 Cardinal Rules of Naming: 1️⃣ The "Number" Rule An identifier cannot start with a digit. ❌ 1variable (Syntax Error) ✅ variable1 (Perfect) 2️⃣ The "Special Char" Trap Keep it alphanumeric. Symbols like @, $, or % are forbidden. The only exception? The underscore (_). ❌ user@name ✅ user_name 3️⃣ The "Reserved" List You cannot use Python's keywords as names. These words (like if, else, for) already have a job. Don't confuse the interpreter! ❌ if = 10 ✅ is_value = 10 4️⃣ The "Case" Sensitivity Python sees capital letters differently. These are not the same variable: 🔸 Total 🔸 total (Treat them as two completely different strangers!) 🧠 Quick Quiz for the Comments: Which of the following variable names will throw an Error? 👇 A) my_data_2 B) _hiddenValue C) 2ndPlace D) DataValue Let’s see who knows their basics! 🚀 ♻️ Repost to save a beginner from a SyntaxError today. ➕ Follow me for more daily Python tips and tricks! I'm documenting my entire learning journey here. 📈 #Python #CodingTips #DataEngineering #ProgrammingBasics #LearnPython
Python Naming Conventions: 4 Cardinal Rules
More Relevant Posts
-
𝐍𝐮𝐦𝐏𝐲 𝐁𝐨𝐨𝐥𝐞𝐚𝐧 𝐓𝐫𝐚𝐩 I’m still at the very beginning of my Python journey. But even with my tiny amount of experience, I already hit a subtle NumPy trap that can easily sneak into real code. Python is full of surprises — even at the very beginning It happens when you create an untyped NumPy array and fill it with a function that should return booleans… …but sometimes returns 𝙉𝙤𝙣𝙚 when processing fails. At first, you expect a clean boolean array — because the function normally returns 𝙏𝙧𝙪𝙚 or 𝙁𝙖𝙡𝙨𝙚. But NumPy has other plans. Here’s the trap 👇 🟥 𝟏) 𝐔𝐧𝐭𝐲𝐩𝐞𝐝 𝐚𝐫𝐫𝐚𝐲 + 𝐚 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐭𝐡𝐚𝐭 “𝐬𝐡𝐨𝐮𝐥𝐝” 𝐫𝐞𝐭𝐮𝐫𝐧 𝐛𝐨𝐨𝐥𝐞𝐚𝐧𝐬 𝒂𝒓𝒓 = 𝒏𝒑.𝒆𝒎𝒑𝒕𝒚(10) # 𝒏𝒐 𝒅𝒕𝒚𝒑𝒆 𝒂𝒓𝒓[𝒊] = 𝒎𝒚_𝒇𝒖𝒏𝒄() # 𝑻𝒓𝒖𝒆 / 𝑭𝒂𝒍𝒔𝒆 ... 𝒐𝒓 𝑵𝒐𝒏𝒆 You expect a clean boolean array because the function usually returns 𝙏𝙧𝙪𝙚/𝙁𝙖𝙡𝙨𝙚. But if even one value is 𝙉𝙤𝙣𝙚, NumPy must pick a type that can hold all values. 🟦 𝟐) 𝐍𝐮𝐦𝐏𝐲 𝐬𝐢𝐥𝐞𝐧𝐭𝐥𝐲 𝐬𝐰𝐢𝐭𝐜𝐡𝐞𝐬 𝐭𝐨 𝐝𝐭𝐲𝐩𝐞=𝐨𝐛𝐣𝐞𝐜𝐭 𝒂𝒓𝒓𝒂𝒚([𝑻𝒓𝒖𝒆, 𝑭𝒂𝒍𝒔𝒆, 𝑵𝒐𝒏𝒆, ...], 𝒅𝒕𝒚𝒑𝒆=𝒐𝒃𝒋𝒆𝒄𝒕) Impact: no vectorization logical operations break masks behave unpredictably performance collapses You think you have a NumPy boolean array. You actually have a Python object array. 🟩 𝟑) 𝐓𝐡𝐞 𝐬𝐢𝐥𝐞𝐧𝐭 𝐜𝐨𝐧𝐯𝐞𝐫𝐬𝐢𝐨𝐧 𝐭𝐫𝐚𝐩 Trying to fix it: 𝒂𝒓𝒓 = 𝒏𝒑.𝒆𝒎𝒑𝒕𝒚(10, 𝒅𝒕𝒚𝒑𝒆=𝒃𝒐𝒐𝒍) 𝒂𝒓𝒓[𝒊] = 𝒎𝒚_𝒇𝒖𝒏𝒄() NumPy converts: 𝑵𝒐𝒏𝒆 → 𝑭𝒂𝒍𝒔𝒆 (silently) Impact: 👉you lose the meaning of “no result” 👉your data becomes wrong 👉the bug becomes invisible ⭐ 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 Same code. Same function. Two completely different arrays. NumPy’s dtype inference can hide subtle bugs — and I found this one with almost no Python experience. 𝐂𝐮𝐫𝐢𝐨𝐮𝐬 𝐭𝐨 𝐤𝐧𝐨𝐰: 👉 Have you ever run into this behavior? 👉 Or another NumPy dtype surprise? #python #numpy #datascience #cleanCode #devTips #programming
To view or add a comment, sign in
-
-
Today a friend asked me a simple question: “What will be the output?” T = (1, 2, 3, [4, 5]) try: T[3] += [6] except Exception as e: print(e) print(T) I was confident. Tuple => immutable List => mutable So it should just add 6 to the list… right? Well… Here’s the actual output: ~ 'tuple' object does not support item assignment ~ (1, 2, 3, [4, 5, 6]) Wait… 🤯 If an exception was raised, how did the list change? What’s really happening? T[3] += [6] is not one operation. Python roughly does this: 1. The Fetch: Python gets the list at T[3]. 2. The Mutation: It calls .__iadd__([6]). Because lists are mutable, this modifies the list in-place. The list is now [4, 5, 6]. 3. The Assignment: It tries to assign that list back to T[3]. Step 2 succeeds. ✔️ Step 3 fails. ❌ So the tuple stays immutable But the list inside it was already modified The Real Insight Tuple immutability means: 👉 You cannot change what the tuple references 👉 But you can mutate the object it references (if it’s mutable) Immutability in Python is about bindings and references — not deep contents. And a great reminder that understanding how Python executes operations under the hood makes you a stronger developer. Have you ever been surprised by Python’s behavior like this? #Python #SoftwareEngineering #ProgrammingConcepts #CleanCode #LearningInPublic
To view or add a comment, sign in
-
Ever wondered how Python knows what to do when you use + between two objects? Or how len() works on your custom class? The answer lies in magic methods (also called dunder methods). These are special methods wrapped in double underscores, and they're what make Python feel like magic. Here are a few that changed how I write code: __init__ — The constructor everyone knows. But it's just the beginning. __repr__ & __str__ — Control how your object looks when printed or logged. Debugging becomes 10x easier when your objects speak for themselves. __len__, __getitem__, __iter__ — Make your custom class behave like a built-in list or dictionary. Your teammates won't even know the difference. __enter__ & __exit__ — Power behind the with statement. Perfect for managing resources like files, DB connections, and locks. __eq__, __lt__, __gt__ — Define what "equal" or "greater than" means for your objects. Sorting a list of custom objects? No problem. __call__ — Make an instance callable like a function. This one unlocks some seriously clean design patterns. The real power of magic methods isn't just the syntax — it's that they let you write intuitive, Pythonic APIs that feel native to the language. When your custom class supports len(), iteration, and comparison naturally, your code becomes easier to read, test, and maintain. What's your favorite magic method? Drop it in the comments #Python #SoftwareEngineering #Programming #PythonTips #CleanCode #BackendDevelopment
To view or add a comment, sign in
-
-
📘 Day 3 — Lists, If Conditions, For Loops… and Why Indentation Matters! Today’s learning felt like the moment Python started behaving like a real analysis tool. I covered: 🔹 Lists → storing multiple values 🔹 If Conditions → applying logic 🔹 For Loops → automating repetition 🔹 Indentation → the rule that makes everything work First — Lists Just like a column in Excel, Python lets us store multiple values together: marks = [65, 72, 58, 90, 48] Second — If Condition This allows Python to make decisions based on rules: if mark > 60: print("Pass") else: print("Fail") Third — For Loop Instead of checking each value manually, Python can go through the whole list: for mark in marks: if mark > 60: print("Pass") else: print("Fail") Now the Most Important Part — Indentation In many tools, spacing is just for readability. But in Python, indentation defines the structure of the code. Python uses indentation to understand: ✔ What belongs inside the loop ✔ What belongs inside the condition ✔ Where logic starts and ends Notice how everything inside the loop is indented: for mark in marks: if mark > 60: print("Pass") If indentation is wrong, Python throws an error — even if the logic is correct. So the key rule I learned today: 👉 Same logic block = Same indentation (usually 4 spaces) Today felt like moving from “writing code” to “teaching Python how to think through data.” #PythonLearning #DataAnalyticsJourney #codebasics #OnlineCredibility
To view or add a comment, sign in
-
-
Day 17 – Strings, Lists & Practical Logic Building in Python Today’s session was a mix of real-world logic building and deeper practice with strings and lists in Python. I started with a simple electricity bill calculation program using conditional statements. It helped me understand how tier-based logic works in real-life scenarios and how to structure conditions properly using if-elif-else. Strings – More Practice Revised and practiced important string methods: upper() and lower() for case conversion isupper() and islower() for validation capitalize() vs title() replace() with control over number of replacements This reinforced how strings are immutable and how every operation returns a new modified string. Lists – Slicing & Methods in Depth Worked extensively on list operations and understood the difference between modifying and non-modifying methods. Slicing Practice: Normal slicing Step slicing Reverse slicing Skipping elements using step values List Methods Explored: append() → add single element extend() → add multiple elements from iterable insert() → add element at specific index remove() → remove first occurrence pop() → remove by index (returns removed value) clear() → empty the list index() → find position of element sort() → modifies original list sorted() → returns new sorted list reverse() → reverse list order join() → join list elements into a string I also observed: How insert() behaves with negative and out-of-range indexes Difference between sort() and sorted() How extend() works differently with list, tuple, and set Key Takeaways Understanding method behavior is more important than just memorizing syntax Some methods modify the original list, others return new values Real learning happens when testing edge cases Logic building is improving step by step Day 17 was more about strengthening fundamentals and building clarity in how Python handles data structures. #Python #PythonLists #PythonStrings #ProgrammingBasics #DataStructures #CodingPractice #DailyLearning #ProblemSolving #LearnToCode #SoftwareDevelopment
To view or add a comment, sign in
-
Ever feel like your code is "doing the work" but then immediately forgetting everything it just did? 🧠 If you’re a beginner learning Python, the difference between print and return is one of the biggest "Aha!" moments you'll have. Here is the breakdown using your example. 1. The "Show-and-Tell" (print) When you use print, the function calculates the answer and shouts it out to the console so you can see it. But that's it. It doesn't "save" the answer anywhere. Python def adding(a, b): print(a + b) adding(20, 12) # Output: 32 Think of it like: A chef cooking a meal, showing it to you, and then immediately throwing it in the trash. You saw it, but you can't eat it (or use it) later! 2. The "Hand-off" (return) When you use return, the function calculates the answer and hands it back to you. Now, you can store that answer in a variable and keep using it for other things. Python def adding_return(a, b): return a + b # We catch the value in a variable called 'result' result = adding_return(20, 12) # Now we can actually use it! print(result - 10) # Output: 22 Think of it like: A chef cooking a meal and putting it in a takeout box for you. You can take it home, add extra salt, or save it for tomorrow. 🔑 The Key Difference print is for Humans. It helps us see what’s happening during debugging. return is for Code. It allows different parts of your program to talk to each other and pass data around. Why this matters: If you tried to do adding(20, 12) - 10 with the first function, Python would give you an error. Why? Because the function didn't "give" you anything back to subtract from! #Python #CodingTips #LearnToCode #ProgrammingBeginner #SoftwareDevelopment #PythonBasics #TechEducation
To view or add a comment, sign in
-
🐍 I didn’t understand Python performance… until I learned THIS. I always heard: “Python is slow.” But no one explained *why*. Then I hit a real backend issue. Same logic. Same data. Different performance. That’s when it clicked 👇 🧠 Python is not slow. ❌ WRONG. The way we USE Python can be slow. Here’s what’s happening behind the scenes 👀 • Python runs on an interpreter • Code executes line by line • Each operation has overhead • Loops + heavy computation = pain 🐢 Example: Doing millions of calculations in a Python loop ❌ Letting optimized C libraries (like NumPy) do it ✅ 💡 The real lesson: ✨ Python shines in I/O (APIs, DB, files, network) ✨ Python struggles with raw CPU-heavy work ✨ Knowing this changes how you design systems Now I ask before writing code: ❓ Is this CPU-bound or I/O-bound? ❓ Should this be async? ❓ Should this move to another service? Python didn’t fail me. My understanding did. Once you know this, Python becomes a powerful backend weapon 🚀 #Python #BackendDevelopment #SoftwareEngineering #Performance #DeveloperLearning #TechExplained #ProgrammingConcepts
To view or add a comment, sign in
-
-
One-Line Sorting with Custom Lambda Key (Sort Integers by The Number of 1 Bits) 💯 || O(N log N) || Just tackled a fun bit-manipulation and sorting problem on LeetCode (Problem 1356), and I wanted to share a super clean, Pythonic way to solve it! 🐍 🎯 The Problem: Sort an array of integers based on the number of 1s in their binary representation. If two numbers have the same number of 1s, sort them by their decimal value. 💡 The Approach: Instead of writing a complex custom comparator, Python’s built-in sorting handles multi-level conditions beautifully. By passing a list [primary_condition, secondary_condition] to the key argument, Python sorts by the first element and automatically falls back to the second if there's a tie. Here is the one-liner: Python class Solution: def sortByBits(self, arr: List[int]) -> List[int]: return sorted(arr, key=lambda x: [bin(x).count('1'), x]) 📊 Complexity: Time: O(N log N) — Python's Timsort algorithm does the heavy lifting, and counting bits for 32-bit integers takes O(1) time. Space: O(N) — Using sorted() creates a new list. Pro-Tip: If you want to optimize for space, you can swap sorted(arr, ...) for arr.sort(...) to sort the array in-place! What is your favorite Python built-in function or one-liner tip? Let me know in the comments! 👇 #Python #LeetCode #Algorithms #CodingInterviews #SoftwareEngineering #DataStructures
To view or add a comment, sign in
-
🚀 Just published a Python package to PyPI! pip install human-regex-lib Here's the problem it solves 👇 Every developer has been here: You need to validate an email, extract a phone number, or match a date format. You open a new tab. You Google "regex for email". You copy-paste some cryptic 50-character string and you have no idea if it's even correct. 😅 There had to be a better way. human-regex-lib lets you write regex using plain English keywords. No memorizing. No Googling. No cryptic symbols. Just chain simple words together and it builds the pattern for you behind the scenes. It's fully chainable, zero dependencies, and works on Python 3.8+. Fully open source — the package and all tests are on GitHub. 🔗 PyPI: https://lnkd.in/g_NGyzxN 🔗 GitHub: https://lnkd.in/g6swaa96 If you've ever copy-pasted regex without understanding it — this one's for you. Drop a ⭐ on GitHub if you find it useful, and let me know what patterns you'd want added next! #Python #OpenSource #PyPI #RegularExpressions #100DaysOfCode #BuildInPublic #SoftwareDevelopment
To view or add a comment, sign in
-
-
Built a Python-based web scraper that collects top news headlines from a public website and stores them in a text file. The project uses HTTP requests to fetch HTML content and BeautifulSoup to parse and extract headline data automatically. This helped me practice web scraping, HTML parsing, and basic file handling in Python. GitHub: https://lnkd.in/gi56cKgZ #Python #WebScraping #BeautifulSoup #Automation #Learning
To view or add a comment, sign in
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development