Day 18: Scope and Precision — The Limits of Logic 🌐 As your programs grow, you'll start having variables with the same names in different places. How does Python know which one to use? And when doing math, how many decimals can Python actually "remember"? 1. Local vs. Global Scope Think of Scope as the "area of visibility" for a variable. Global Scope: Variables defined at the top level (outside any function). They can be read from anywhere in your script. Local Scope: Variables defined inside a function. They only exist while that function is running. Once the function ends, the variable is deleted. 💡 The Engineering Lens: Avoid using too many Global variables. If every function can change a variable, it becomes a nightmare to track down bugs. Keep data "Local" whenever possible! 2. The LEGB Rule: Python’s Search Engine When you call a variable name, Python searches in a very specific order to find it. This is the LEGB rule: Local: Inside the current function. Enclosing: Inside any nested "parent" functions. Global: At the top level of the file. Built-in: Python’s pre-installed names (like len or print). 3. Precision: The Decimal Limit When you use a Float (a decimal number), Python has to fit that number into a fixed amount of memory. Maximum Precision: Python floats are typically "double-precision" (64-bit). This means they can hold about 15 to 17 significant decimal digits. The Default: When you perform a calculation, Python will show as many decimals as are relevant, but it stops being accurate after that 15–17 digit mark. 💡 The Engineering Lens: Because of this limit, 0.1 + 0.2 often equals 0.30000000000000004. If you are building a banking app or a scientific tool where you need infinite precision, don't use floats! Use Python’s decimal module instead. #Python #SoftwareEngineering #CleanCode #ProgrammingTips #DataPrecision #LearnToCode #TechCommunity #PythonDev
Python Scope and Precision Limits
More Relevant Posts
-
I used to think strings were the “easy” part of Python… today proved me wrong. 🐍 Day 04 of my #30DaysOfPython journey was all about strings, and honestly, this topic felt way more powerful than I expected. A string is basically any data written as text — and it can be written using single quotes, double quotes, or triple quotes. Triple quotes also make multiline strings super easy. Today I explored: 1. len() to check length 2. Concatenation to join strings together 3. Escape sequences like \\n, \\t, \\\\, \\', \\" 4. Old style formatting with %s, %d, %f 5. New style formatting with {} 6. Indexing and unpacking characters 7. Reversing a string with str[::-1] And then came the string methods… that part felt like unlocking a toolbox: capitalize(), count(), startswith(), endswith(), find(), rfind(), format(), index(), rindex(), isalnum(), isalpha(), isdigit(), isnumeric(), isidentifier(), islower(), isupper(), join(), strip(), replace(), split(), title(), swapcase() What hit me today was this: strings are everywhere. Names, messages, input from users, file data, logs, even the little things we ignore at first. So yeah — not “just text.” More like one of the most important building blocks in programming. Github Link - https://lnkd.in/gUkeREkz What was the first Python topic that looked simple but turned out to have way more depth than expected? #Python #LearnPython #CodingJourney #30DaysOfPython #Programming #DeveloperJourney
To view or add a comment, sign in
-
Today's topic: recursion. A function that calls itself. Sounds simple, right? Here are two ways to add up a list of numbers: Without recursion — honest, reliable, easy to follow: python def suma(lista): suma = 0 for i in range(0, len(lista)): suma = suma + lista[i] return suma print(suma([6,3,4,2,10])) # 25 With recursion — elegant, almost poetic... and a little terrifying: python def suma(lista): if len(lista) == 1: return lista[0] else: return lista[0] + suma(lista[1:]) print(suma([6,3,4,2,10])) # 25 Same result. Two completely different roads to get there. The recursive version looks more "pro" — but if you forget to define when it stops, the function calls itself forever. Literally. Forever. 💀 So yes, it's getting challenging. And yes, recursion feels more elegant to write. But I'm not ready to fully trust something that could loop into oblivion if I blink wrong. Lesson of the day: simple is not the same as bad. And documenting the moments that confuse you? That's part of learning too. #Python #LearningToCode #DaysOfCode #PythonProgramming #CodingJourney #Recursion #BeginnerCoder #TechLearning #CodeNewbie #LinkedInLearning
To view or add a comment, sign in
-
-
🚀 Solved: Group Anagrams Problem (LeetCode) Today I worked on an interesting problem — grouping anagrams efficiently using Python. 💡 Approach: I used a hashmap (dictionary) where: The key is the sorted version of each word The value is a list of words (anagrams) matching that key Example: "eat", "tea", and "ate" → all become "aet" after sorting → grouped together 🧠 Key Insight: Sorting each string gives a unique identifier for all its anagrams. ⚙️ Time Complexity: Sorting each word takes O(k log k) For n words → O(n * k log k) 📦 Space Complexity: O(n * k) for storing grouped anagrams ✅ Result: Accepted ✔️ Runtime: 5 ms (faster than ~99% submissions) 📈 Growth & Consistency: Improving step by step by solving problems daily and focusing on writing clean and optimized code. Small consistent efforts are helping me build stronger problem-solving skills and deeper understanding of DSA. 🔁 Staying consistent is the real game changer! #Python #DSA #LeetCode #Coding #ProblemSolving #Consistency #Growth #LearningJourney
To view or add a comment, sign in
-
-
📅 Day 5 of Python — and today was all about putting knowledge to the test! 💪 Instead of learning something new, I took on a full practice session covering everything I've studied so far on Python's core data structures. 🧪 Here's what I worked through: ✅ Lists — creating, slicing, methods like append(), extend(), insert(), pop(), remove(), and sort() ✅ List Comprehensions — squares, filters, tuple pairs, and more ✅ Tuples — declaration, immutability (yes, I triggered the TypeError 😅), unpacking, and zip() ✅ Sets — deduplication, membership checks, add/remove/discard, and set operations like union, intersection, difference & symmetric difference ✅ Dictionaries — key-value access, get(), items(), keys(), values(), nested dicts, and updating/deleting entries ✅ Dictionary Comprehensions — building mappings with filters ✅ Applied Problems — frequency maps, common elements using sets, zip() with conditional logic The practice set had 30+ exercises and solving each one back-to-back really helped solidify the concepts rather than just reading about them. Key takeaway from today: You don't truly understand a concept until you've broken it, debugged it, and fixed it yourself. 🔧 On to Day 6! 🚀 #Python #100DaysOfCode #DataStructures #LearningInPublic #CodingJourney #PythonProgramming
To view or add a comment, sign in
-
Day 24: Iterators — The Engine Behind the Loop ⚙️ In Python, we often talk about "looping over data." But how does Python actually keep track of where it is in a list of 1 million items? It uses the Iterator Protocol. 1. Iterable vs. Iterator (The "Book" vs. The "Bookmark") Iterable: Any object you can loop over (List, String, Dictionary). Think of it as a Book. It contains all the data, but it doesn't "know" which page you are on. Iterator: A special object that represents a stream of data. Think of it as a Bookmark. It knows exactly where you are and what comes next. 2. The Tools: iter() and next() You can turn any Iterable into an Iterator using these two built-in functions: iter(my_list): Creates the "Bookmark" for that list. next(my_iterator): Moves the bookmark to the next "page" and returns the value. numbers = [10, 20] my_iter = iter(numbers) print(next(my_iter)) # Output: 10 print(next(my_iter)) # Output: 20 # print(next(my_iter)) # Error: StopIteration (The book is finished!) 3. Does it store data in memory? 🧠 This is the "Senior Engineer" secret. Lists/Tuples store all their data in memory at once. If you have 1 billion numbers, your RAM will crash. Iterators (and specifically Generators) are "Lazy." They don't store the whole list; they only calculate or fetch the next item when you ask for it. 💡 The Engineering Lens: This is why we use Iterators for massive datasets (like reading a 10GB log file). We process one line at a time, keeping our memory usage near zero! 4. The StopIteration Exception When an iterator runs out of items, it doesn't return None or 0. It raises a StopIteration error. 💡 The Engineering Lens: A for loop is actually just a "Fancy While Loop" that calls next() repeatedly and automatically handles the StopIteration error so your program doesn't crash. #Python #SoftwareEngineering #ComputerScience #MemoryManagement #Iterators #LearnToCode #CodingTips #TechCommunity #BackendDevelopment
To view or add a comment, sign in
-
🚀 Solved another problem on LeetCode: Concatenation of Array Today I worked on a simple yet important array problem that focuses on understanding how data structures behave in Python. Problem Summary: Given an integer array "nums", create a new array "ans" such that: 👉 "ans = nums + nums" (i.e., the array is repeated twice) 💡 My Approach: I used Python’s built-in list concatenation: "return nums + nums" ⚡ Why this approach is best? - No loops required - Clean and readable code - Uses optimized internal operations 📊 Complexity Analysis: • Time Complexity: O(n) • Space Complexity: O(n) 🔁 Comparison with other approaches: 🔸 Using loops → More lines of code, less readable 🔸 Using append() → Slightly slower due to repeated operations 🔸 Using list comprehension → Still less direct My approach is the most efficient and pythonic way to solve this problem. 🧠Key Learning: Sometimes the simplest solution is the most powerful. Knowing built-in operations can save time and improve code quality. Consistency in DSA is the key 🔥 #LeetCode #DSA #Python #CodingJourney #ProblemSolving #Code
To view or add a comment, sign in
-
-
🚀 Day 9 of #100DaysOfCode — Finding the Sum of the Smallest Numbers in Python Today I explored two different approaches to solve a simple but important problem: 👉 Find the sum of the smallest N numbers in a list ✅ Approach 1: Pythonic & Efficient numbers = [5, 2, 9, 1, 7] n = 2 result = sum(sorted(numbers)[:n]) print(result)🔹 How it works: sorted(numbers) → sorts the list[:n] → picks the smallest n elementssum() → adds them up💡 Clean, readable, and perfect for most use cases. ✅ Approach 2: Manual Logic (Without Built-ins) arr = [5, 2, 9, 4, 3, 5] N = 2 total = 0 data = len(arr) for k in range(N): min_index = 0 for i in range(1, data): if arr[i] < arr[min_index]: min_index = i total += arr[min_index] arr[min_index] = float('inf') print("Sum of smallest", N, "numbers:", total)🔹 How it works: Repeatedly finds the smallest elementAdds it to totalMarks it as used (by setting to infinity)💡 Great for understanding core logic and algorithm design 🔍 Key Takeaways ✔️ Built-in functions save time and reduce complexity ✔️ Manual approach helps strengthen problem-solving skills ✔️ Always balance readability vs control 💬 Best Comment Insight “Don’t just learn shortcuts — understand what’s happening under the hood. That’s where real growth happens.” #Python #CodingJourney #30DaysOfCode #LearnToCode #Programming #Developers #ProblemSolving #PythonBasics
To view or add a comment, sign in
-
Stop writing try/finally blocks. Use context managers instead. I see this pattern everywhere in Python codebases: connection = get_db_connection() try: result = connection.execute(query) finally: connection.close() Nothing wrong with it — until you have 15 resources to manage across your project. Here's the cleaner version with contextlib: from contextlib import contextmanager @contextmanager def db_connection(): conn = get_db_connection() try: yield conn finally: conn.close() with db_connection() as conn: result = conn.execute(query) Why this is better: → Resource cleanup logic lives in ONE place → You can't forget to close — it's automatic → Stack multiple with a single `with` statement → Works with async too (`@asynccontextmanager`) My favorite use case: temporary environment changes in tests. @contextmanager def override_settings(**kwargs): old = {k: getattr(settings, k) for k in kwargs} for k, v in kwargs.items(): setattr(settings, k, v) try: yield finally: for k, v in old.items(): setattr(settings, k, v) Small abstraction. Massive reduction in bugs. What's your favorite Python pattern that most people underuse? 👇 #Python #Programming #BackendDevelopment #SoftwareEngineering #CleanCode
To view or add a comment, sign in
-
💡 𝗪𝗵𝘆 𝗱𝗼𝗲𝘀 𝗣𝘆𝘁𝗵𝗼𝗻 𝗸𝗲𝗲𝗽 𝘁𝗮𝗹𝗸𝗶𝗻𝗴 𝘁𝗼 𝗶𝘁𝘀𝗲𝗹𝗳? 🐍🤔 If you've ever looked at a Python class, you’ve definitely seen it… 👉 that mysterious first parameter: `self` At first, it feels unnecessary. Like… why is Python repeating itself? --- 🏠 Think of a class as a *house blueprint* The blueprint says: "A house has a front door." But the blueprint doesn’t *have* a door. When you build 100 houses, each house needs to know: 👉 which door belongs to *it* --- 🏷️ That’s exactly what `self` does It’s like an **address tag** for each object. When you write: `self.name = name` You’re telling Python: 👉 “Store this value in THIS specific object.” --- 🙄 But why do we have to write it every time? Because Python follows: 👉 *Explicit is better than implicit* It doesn’t guess. It makes you be clear. --- 🍲 Imagine this: A waiter walks into a crowded restaurant and shouts: “HERE IS YOUR SOUP!” No table number. No context. Chaos. That’s your code **without `self`** ❌ --- ✅ With `self`: • Every object knows its own data • No confusion • Clean, readable code --- 🚀 Pro tip: You can name it anything (`this`, `me`, even `ketchup`) But don’t. 👉 Stick to `self` — your teammates will thank you --- 🙏 Special thanks to my mentor Sai Kumar Gouru 🏫 Learning with Frontlines EduTech (FLM) --- 💬 What confused you the most when learning OOP? #Python #OOP #Programming #CodingForBeginners #SoftwareEngineering #PythonTips #LearnToCode
To view or add a comment, sign in
-
-
🔥 Day 3 of #PythonLearningSeries Hey everyone 👋 Welcome to Day 3! So far, we’ve learned: ✔ How to print output ✔ Variables & data types Today, let’s make our programs more interactive 😄 👉 Input & Output in Python 📌 What is Output? Output means displaying something to the user. We already used this: print("Hello, World!") 👉 print() is used to show output on the screen. 📌 What is Input? Input means taking data from the user. In Python, we use: 👉 input() 💻 Example: name = input("Enter your name: ") print("Hello", name) 👉 What happens here? The program asks for your name You type something It prints a message using your input 🧠 Important Concept: 👉 By default, input() takes data as a string Even if you enter a number, Python treats it as text. ⚠️ Common Beginner Mistake: age = input("Enter your age: ") If you try: print(age + 5) ❌ This will give an error (or wrong result) ✔️ Correct way: age = int(input("Enter your age: ")) print(age + 5) 📌 Type Conversion (Very Important) We convert input into different data types: 👉 int() → Integer 👉 float() → Decimal 👉 str() → String 💻 Example: num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) print("Sum is:", num1 + num2) ✨ Your Turn! 📍 Practice Task: 1️⃣ Ask user for their name and age 2️⃣ Print: "Hello [name], you are [age] years old" 3️⃣ Take two numbers and print their sum 🤔 Quick Question: What will be the type of this input? value = input("Enter something: ") 👉 String or Integer? Comment your answer 👇 🚀 You’re building real logic now—great progress! 🔁 Follow me for Day 4: Operators in Python #Python #LearnPython #CodingJourney #Programming #Beginners #Tech #100DaysOfCode
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