🔍 Python's Hidden Gem: Short-Circuit Evaluation with Operand Return Ever wondered why Python's "or" and "and" operators are more powerful than they seem? Unlike Java or C++, they don't just return True/False – they return the actual values! Short-circuit evaluation means that logical operators like and and or stop evaluating as soon as the result of the expression is known. In Python, these operators don’t just return True or False; they actually return the operand that determined the result — that’s what is meant by operand return. Python's logical operators ("or" and "and") return one of the actual operands, not necessarily True or False. The "or" Operator - - Returns the first truthy value it encounters - If all values are false, returns the last value The "and" Operator in Python - - Returns the first false value it encounters - If all values are truthy, returns the last value ``` # OR examples print(None or [1, 2, 3]) # [1, 2, 3] - returns first truthy print("hello" or "world") # "hello" - returns first truthy print(False or 0 or [] or {}) # {} - all falsy, returns last print(42 or False) # 42 - returns first truthy # AND examples print([1, 2] and "text") # "text" - all truthy, returns last print("text" and None) # None - returns first falsy print(5 and 10 and 20) # 20 - all truthy, returns last print(0 and [1, 2, 3]) # 0 - returns first falsy # Check if user exists AND has valid credentials OR is admin user = get_user(username) access_granted = (user and user.password == password) or is_admin # Returns: user object if password matches, False if not, or True if admin ``` False Values in Python (the complete list) : False None 0 (integer zero) 0.0 (float zero) 0j (complex zero) "" (empty string) [ ] (empty list) ( ) (empty tuple) { } (empty dict) set( ) (empty set) range(0) (empty range) Truth Values in Python (everything else!) : True Any non-zero number: 1, -1, 3.14, 2+3j Any non-empty string: "hello", "0", " " (even a space!) Any non-empty collection: [1, 2], (1,), {"a": 1} Any object or instance (by default) Functions, classes, modules ⚡ Why This Matters: - Reduces code complexity - Eliminates nested if-else pyramids - Makes default value handling elegant - Improves code readability dramatically #Python #CleanCode #CodingTips #SoftwareDevelopment
How Python's "or" and "and" Operators Work
More Relevant Posts
-
𝐓𝐡𝐞 𝐆𝐡𝐨𝐬𝐭 𝐢𝐧 𝐭𝐡𝐞 𝐌𝐚𝐜𝐡𝐢𝐧𝐞 Python is a memory safe language, right? After all, it's listed as memory‑safe language in the 2014 CISA recommendations. We trust Python's automatic GC (Garbage Collector) to tidy up, but sometimes, the GC is blinded. It’s not about poor coding (even though that can certainly be a factor); it’s about Python’s fundamental, hidden engine: 𝐑𝐞𝐟𝐞𝐫𝐞𝐧𝐜𝐞 𝐂𝐨𝐮𝐧𝐭𝐢𝐧𝐠. This is the core mechanism that keeps track of every variable. If a reference count never hits zero, Python thinks the object is still needed. The code looks fine, but deep down, a forgotten pointer is hoarding gigabytes of memory. A reference cycle occurs when two or more objects refer to each other, forming a closed loop. For example, object A refers to B, and object B refers back to A. Even if no external code is referencing A or B anymore, their internal counter never drops to zero because they are holding each other hostage. Python's Garbage Collector (GC) runs periodically to break these cycles, but: - It is 𝐧𝐨𝐭 𝐠𝐮𝐚𝐫𝐚𝐧𝐭𝐞𝐞𝐝 to run immediately. - It creates a significant 𝐩𝐞𝐫𝐟𝐨𝐫𝐦𝐚𝐧𝐜𝐞 𝐬𝐩𝐢𝐤𝐞 when it does run. - It can be 𝐝𝐢𝐬𝐚𝐛𝐥𝐞𝐝 or 𝐝𝐞𝐥𝐚𝐲𝐞𝐝 by other code execution. If you are dealing with complex data structures, caches, or deeply nested class hierarchies, you are building the perfect hiding spot for a tenacious reference cycle. You need to be proactive, don't wait for the GC to save the day! 1. Use 𝘸𝘦𝘢𝘬𝘳𝘦𝘧: When designing data structures where objects need to point to each other (like parent-child relationships), use the built-in 𝘸𝘦𝘢𝘬𝘳𝘦𝘧 module. A weak reference does not increase an object's reference count, allowing the other object in the cycle to be collected properly. 2. Inspect with 𝘨𝘤: Use the 𝘨𝘤 module to investigate. 𝘨𝘤.𝘨𝘦𝘵_𝘰𝘣𝘫𝘦𝘤𝘵𝘴() can show you all managed objects, and 𝘨𝘤.𝘤𝘰𝘭𝘭𝘦𝘤𝘵() lets you manually trigger the cleanup process to see if it fixes your memory spike (revealing an existing cycle). 3. Profile with 𝘵𝘳𝘢𝘤𝘦𝘮𝘢𝘭𝘭𝘰𝘤: This module tracks memory allocation down to the specific line of code that allocated it. Run your service with 𝘵𝘳𝘢𝘤𝘦𝘮𝘢𝘭𝘭𝘰𝘤 enabled to pinpoint the exact function and data structure responsible for the leak. Not using these suggestions doesn't mean you're a bad developer, or that your code is lacking. Python's memory model is not the same as writing code, or even engineering scalable services . You have to be a real coding geek (like the ones in Kratos Core) to even be interested in this - but it could really make a difference!
To view or add a comment, sign in
-
✨ The Python Story – Episode 8: The Global Interpreter Lock (GIL) ✨ If Episode 7 was about why Python is called “slow,” today we dive into one of the biggest reasons behind that reputation — and one of Python’s most misunderstood features: the Global Interpreter Lock, or simply, the GIL. 🧠 When Guido van Rossum created Python, his goal was to make a simple, safe, and readable language. But there was one tricky problem — memory management. Python uses reference counting to track how many variables point to an object in memory. When no references remain, that memory is freed. It’s clean and elegant — but not thread-safe. If two threads update those counts at the same time, chaos can occur — corrupted memory or random crashes. Guido’s fix? A simple yet powerful idea — the Global Interpreter Lock. 💡 What exactly is the GIL? The GIL is a mutex — a lock that allows only one thread to execute Python bytecode at a time in a process. Even if your computer has 8 cores, only one runs Python code at once; others wait. That sounds limiting — and it is, for CPU-heavy work — but it also made Python safe, stable, and easy to extend with C libraries. For Guido, simplicity and reliability mattered more than theoretical speed. ⚙️ So does that mean Python can’t do multi-threading? Not really. Threads in Python still handle I/O-bound tasks well. When one thread waits for input/output — reading files, APIs, databases — the GIL is released so another thread can run. That’s why frameworks like Flask, FastAPI, and Scrapy manage thousands of concurrent operations. But for CPU-bound tasks — image processing, ML, or crunching data — the GIL becomes a bottleneck. 🚀 Workarounds Developers learned to work around the GIL: 🔹 Use multiprocessing to run multiple processes instead of threads. 🔹 Offload heavy work to NumPy, Cython, or C extensions. 🔹 Use asyncio for efficient concurrency. Despite its limits, these techniques made Python incredibly versatile — from automation scripts to large-scale systems. 🧩 The road to “No GIL” Recently, Python’s community has been working toward a GIL-free future. Python 3.13 introduced an experimental “no-GIL” build, a huge leap for true multi-threaded Python. And in Python 3.14, it gets practical — you can now disable the GIL at runtime for the new free-threaded build! 🎉 python -X gil=0 your_script.py # or PYTHON_GIL=0 The same lock that once symbolized simplicity may soon be unlocked in the name of progress. 🔓 📌 Next Sunday – Episode 9: Memory & Garbage Collection in Python 🧹 How Python keeps programs clean behind the scenes — reference counting, garbage collection, and what really happens when you call del. ⚡ Fun Fact: Run a multi-threaded CPU task in Python and watch — only one core hits 100%, while the rest relax. 😅 #python #ThePythonStory #StoryOfPython #programming #developers #PythonInternals
To view or add a comment, sign in
-
Python Tuple Packing and Unpacking 🐍 In Python, tuples are more than just immutable lists. They are powerful tools that make your code cleaner, more readable, and incredibly Pythonic. And the concepts of tuple packing and unpacking are at the heart of writing elegant Python code. 🔹 Tuple Packing: Packing means grouping multiple values into a single tuple variable. Python makes this seamless: my_tuple = 1, 2, 3, 4, 5 👉Values are packed into a tuple 👉This allows you to store multiple values in a single variable, return multiple values from a function, or pass collections around without extra boilerplate. 🔹 Tuple Unpacking: 👉Unpacking is the reverse: extracting tuple elements into individual variables in a single, readable line. a, b, c = (10, 20, 30) print(a, b, c) 👉Output: 10 20 30 💡 Why Tuple Packing & Unpacking Matters? 1. Makes code more readable than indexing elements manually. 2. Enables returning multiple values from functions effortlessly. 3. Works beautifully with loops, function arguments, and nested data structures. ✨ Pro Tip: Tuple unpacking is especially powerful when swapping variables without a temporary placeholder: x, y = y, x No extra line, no temp variable—just clean, Pythonic magic. -------------------------- 🤓 Check Out More About Tuple Packing and Unpacking in my Python Lists Repo down below! -------------------------- ☺️ Here are Python (Beginner to Intermediate) GitHub Repos for you: 📁Python Variables: https://lnkd.in/e9rjz-_D 📁Python Operators: https://lnkd.in/e6hzgHSn 📁Python Conditionals: https://lnkd.in/egQNGZBF 📁Python Loops: https://lnkd.in/eezUg_-y 📁Python Functions: https://lnkd.in/eKdU6nex 📁Python Lists: https://lnkd.in/eZ8KiQNs ------------------------- ⚡ Follow my learning journey: 📎 GitHub: https://lnkd.in/ehu8wX85 🔗GitLab: https://lnkd.in/eiiQP2gw 💬 Feedback: I’d love your thoughts and tips! 🤝 Collab: If you’re also exploring Python, DM me! Let’s grow together! -------------------------- 📞Book A Call With Me: https://lnkd.in/e23BtnR9 -------------------------- #pythontuples #tuplepackingandunpacking #pythonforbeginners #pythonlanguage #pythonfordatascience
To view or add a comment, sign in
-
-
🐍 Pythonic Idioms: A Core Driver of Python’s Popularity Python’s rise to dominance in the programming world isn’t just about its versatility—it’s about its philosophy. At the heart of this philosophy lies the concept of Pythonic idioms: elegant, readable, and concise coding patterns that make Python code feel natural and intuitive. 📜 A Brief History Python was created by Guido van Rossum in the late 1980s and released in 1991. From the beginning, it emphasized simplicity and readability. This ethos was later captured in the Zen of Python by Tim Peters—a collection of 19 guiding principles that define what it means to write “Pythonic” code. Some favorites: Beautiful is better than ugly Simple is better than complex Readability counts These principles laid the foundation for Pythonic idioms, which evolved as best practices within the community. 🎯 Why Pythonic Idioms Matter Pythonic idioms were introduced to: Promote clarity and readability Encourage consistency across codebases Improve performance and efficiency Reduce errors and complexity They serve as a shared language among Python developers, making collaboration smoother and code more maintainable. ✅ Benefits of Pythonic Idioms Readable & Maintainable: Easier to understand and debug. Concise: Express logic in fewer lines. Performant: Often faster than verbose alternatives. Community-Driven: Reinforced by PEP 8 and Python’s culture. 🧰 Examples of Pythonic Idioms Here are some idioms that every Python developer should know: # List Comprehension squares = [x**2 for x in range(10)] # Dictionary Comprehension expensive = {k: v for k, v in prices.items() if v > 0.4} # Enumerate for i, item in enumerate(['a', 'b', 'c']): print(i, item) # Zip for name, age in zip(names, ages): print(f"{name} is {age} years old") # Truthiness if items: print("List is not empty") # EAFP try: value = my_dict['key'] except KeyError: value = None # Context Manager with open('file.txt') as f: content = f.read() # Throwaway Variable for _, value in enumerate(data): process(value) # Safe Dictionary Access value = my_dict.get('key', default_value) # Conditional Expression status = "active" if is_enabled else "inactive" 📈 Impact on Python’s Popularity Research shows that Pythonic idioms: Boost developer productivity Improve code comprehension Drive adoption across industries Serve as a hallmark of expert-level Python They’re not just stylistic—they’re strategic. 🏁 Final Thoughts Pythonic idioms are a big reason why Python is loved by beginners and experts alike. They make code elegant, maintainable, and powerful. Whether you're just starting out or refining your craft, embracing Pythonic idioms will elevate your coding style and help you think more clearly about your solutions. 💬 What’s your favorite Pythonic idiom? 👇 Share it in the comments and let’s celebrate clean code! #Python #CleanCode #SoftwareEngineering #Pythonic #CodingTips #DeveloperExperience #ZenOfPython #ProgrammingPhilosophy
To view or add a comment, sign in
-
-
#AI #ML #Post8🧠 Invoke Python from C# using Python.Runtime ✅️Python.Runtime is the core library of Python.NET, a bridge between C# (.NET) and Python. It allows your C# code to embed the Python interpreter, run Python code, and interact with Python objects just like native C# objects. Think of it as a “translator” between C# and Python. --- ⚙️ Installation You can install it via NuGet: ✅️dotnet add package Python.Runtime --- 🧩 Key Components of Python.Runtime Let’s break down the main classes and methods you’ll use: 1. PythonEngine This is the core interface for controlling the embedded Python interpreter. Common methods: ✅️PythonEngine.Initialize() Starts the Python interpreter ✅️PythonEngine.Shutdown() Stops the interpreter and frees resources ✅️PythonEngine.Exec(string code) Executes a block of Python code ✅️PythonEngine.RunString(string code) Runs a single Python expression and returns the result ✅️PythonEngine.ImportModule("module_name") Imports a Python module --- 2. Py.GIL() In Python, the Global Interpreter Lock (GIL) ensures only one thread executes Python bytecode at a time. ✅ Example: using (Py.GIL()) { // Interact with Python here } When the using block ends, the GIL is automatically released. --- 3. PyObject A wrapper around Python objects. You can use PyObject to reference, call, or convert Python data. --- 4. Py.Import() Used to import Python modules from C# just like import in Python. --- 🧠 Example: Calling a Python function from C# Let’s say you have this Python file (myscript.py): # myscript.py def multiply(a, b): return a * b Here’s the C# code that uses Python.Runtime to call it: using System; using Python.Runtime; class Program { static void Main() { // Initialize Python interpreter PythonEngine.Initialize(); using (Py.GIL()) { // Import your Python script (make sure it's in the same folder or on sys.path) dynamic script = Py.Import("myscript"); // Call the function dynamic result = script.multiply(5, 10); Console.WriteLine($"Result from Python: {result}"); } PythonEngine.Shutdown(); } } --- ⚙️ How It Works Internally 1. PythonEngine.Initialize() loads the Python C API into your .NET process. 2. The embedded interpreter behaves exactly like a normal Python runtime (you can import any installed package). 3. Objects are wrapped as PyObject so you can use them in C#. 4. Python.NET automatically converts between basic .NET and Python types: int ↔ int double ↔ float string ↔ str List<T> ↔ list --- 💡 Tips & Notes ✅️Python must be installed on your system (and PYTHONHOME or PYTHONPATH should be correctly set if needed). ✅️You can specify a specific Python version with: Environment.SetEnvironmentVariable("PYTHONNET_PYDLL", @"C:\Python311\python311.dll");
To view or add a comment, sign in
-
-
🚀 My First Python Menu-Driven Project — Simple Calculator 🧮 Today, I’m excited to share my very first menu-driven Python project — a Simple Calculator! 🎉 This project helped me understand how to make interactive programs using loops, conditions, and exception handling. 💡 What I learned: ✅ Creating functions and reusing them effectively ✅ Using while loops to keep programs running until the user chooses to exit ✅ Handling user input safely with try and except blocks ✅ Implementing menu-driven logic for multiple operations ✅ Using Python’s eval() function carefully for BODMAS rule evaluation ✅ Formatting output using f-strings 🧩 Features of My Calculator: 1️⃣ Addition 2️⃣ Subtraction 3️⃣ Multiplication 4️⃣ Division (with ZeroDivisionError handling) 5️⃣ Percentage Calculation 6️⃣ Power Operation 7️⃣ BODMAS Expression Evaluation 8️⃣ Exit Option Here’s a small preview of my code 👇 def menu(): print('### Simple Calculator ###') print('1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\n5. Percentage\n6. Power\n7. BODMAS\n8. Exit') while True: try: menu() choice = int(input('Enter the number (1-8): ')) except ValueError: print('Invalid input! Enter a number.') continue if choice in {1,2,3,4,5,6}: num1 = float(input('Enter number 1: ')) num2 = float(input('Enter number 2: ')) if choice == 1: print('Addition:', num1 + num2) elif choice == 2: print('Subtraction:', num1 - num2) elif choice == 3: print('Multiplication:', num1 * num2) elif choice == 4: print('Division:', num1 / num2 if num2 != 0 else 'Cannot divide by zero!') elif choice == 5: print('Percentage of num1:', num1 / 100, '%') print('Percentage of num2:', num2 / 100, '%') elif choice == 6: print('Power:', num1 ** num2) elif choice == 7: bodmas = input('Enter expression: ') print('BODMAS Result:', eval(bodmas)) elif choice == 8: print('Thank you for using my calculator!') break else: print('please enter between 1 to 8 only!') 🎯 My Learning Goal: I’m continuously improving my Python skills to build a strong foundation for Data Science and Machine Learning. This small step motivates me to take on bigger projects like database systems, data visualization, and ML models soon! 💪 👩💻 If you’re also learning Python, let’s connect and share knowledge! 💬 Suggestions and feedback are always welcome. #Python #CodingJourney #BeginnerProject #MenuDrivenProgram #WomenInTech #LearningInPublic #DataScience #dataAnalyst #engineeringinkannada simple_output:
To view or add a comment, sign in
-
-
✨ The Python Story – Episode 7: Why People Call Python “Slow” ✨ Python is loved for its simplicity — but often teased for one thing: “Python is slow.” You’ve probably heard it, maybe even said it. But have you ever wondered why people say that? Let’s go back to the beginning. ⏳ When Guido van Rossum designed Python in 1989, he had a clear vision — a language that made coding easy to write, easy to read, and fun to use. He wasn’t chasing speed — he was chasing simplicity. “The time of a developer is more important than the time of a machine.” – Guido van Rossum Back then, computers were getting faster every year. Guido believed the future would belong to languages that valued human efficiency over machine efficiency. So Python made a few conscious trade-offs — the very reasons people call it “slow” today. 💡 1️⃣ Python is interpreted, not compiled Python doesn’t go straight to machine code like C or C++. It first compiles to bytecode (.pyc) and then executes line by line in a virtual machine. That flexibility and portability cost time — like having a translator between you and the computer. 💡 2️⃣ Python is dynamically typed No need to declare types — Python figures it out as it runs. It’s great for productivity but adds runtime overhead. Dynamic typing = freedom for you, extra work for the machine. 💡 3️⃣ The Global Interpreter Lock (GIL) To keep memory safe, only one thread can run Python bytecode at a time — even on multi-core CPUs. (We’ll explore this fully in Episode 8!) 💡 4️⃣ Readability over raw optimization Lists, dictionaries, and exceptions make Python beautiful and expressive — but all that elegance adds processing under the hood. 🚀 And here’s the truth: Python’s “slowness” rarely matters. For most real-world work — web apps, AI, scripting, automation — the bottleneck isn’t Python’s speed; it’s the network, database, or human time. And when performance does matter, Python calls faster languages like C, C++, or Rust using libraries such as NumPy or TensorFlow. That’s Python’s magic: It may not be the fastest to run, but it’s the fastest to build with. ⚡ 📌 Next Sunday – Episode 8: The Global Interpreter Lock (GIL) We’ll uncover what the GIL really is, why Guido introduced it, and how it affects Python on multi-core systems. ⚡ Fun Fact: Python compiles your code into portable bytecode — saved in the __pycache__ folder every time you run a program! #python #ThePythonStory #StoryOfPython #programming #developers #PythonInternals
To view or add a comment, sign in
-
Python: Awesome language, lots of use-cases. I have used python for 5-6 years, and I think it’s a good language to use and misuse. Yesterday I revising my datastructures and algorithms, and wanted to make a red-black-tree. I did it in C, thought to myself "I don‘t care about the intricacies I need to understand it at a high level first" So i used Python Python isn‘t a language that fits my definition of recreational programming. Python has all these fancy features, and it enables you to not take care when you program (but you _should_ care. Here you can afford to not care though, unlike in C), and furthermore with metaclasses using __new__ (a constructor for classes, not instances as far as i know) and dynamic classes (type taking 3 arguments, the name __class__, the parents of which it inherits, and the dictionary of methods and properties), you get this… mess…, you can overwrite and override everything, and forcibly one-line-ify literally the entire source code, you can make recursive lists for crying out loud My goal isnt to learn the craft, my goal is to learn the *art* of the craft, and for that i need recreational use languages. My definition of recreational language is "is the representation of the entity relatable at a lower level". For Python, Java, JavaScript, TypeScript the answer is a clear No. Another addition to my arbitrary ruleset is "How much nonsense does it add?" Not lack, add. Not having strings is nonsense, bounds checks, allowing buffer overflows etc, that’s nonsense, but that isn‘t _added_. Convenience fixes are added to fix these things, which is awesome, but C doesn‘t add its problems. It just doesn‘t add solutions. Another "paradigm" of my recreational language checklist is "How much abstraction are you willing to take?" C is high level in that regard, but the code has a clear correspondence to the generated assembly Summary: - Is the representation of the entity relatable at a lower level (if you were to take everything apart layer by layer, when would things stop existing) - How much "extra" does it add? (What features are there that are useful but don‘t match the 99% usecase Python: metaclasses, name mangling with match, hacking the import resolver, etc for example. I am not good enough in Java, I just artificially don‘t like the language. JSFuck, and TypeScript types are turing complete.) - How much abstractions are you willing to take? (In my case very little. The job of the compiler is to compile, not make me dinner and sing me to sleep. If I make a mistake, this is my fault. Compile the code. This is what I installed you for. You are here to compile code, not tell me that I am bad at programming. I know that) I went back to C and it felt good again. Maybe I just am too far gone in the C rabbit hole, or maybe I am just saying 3000 characters worth of cope and skill issue. If this post offends you because I dunked on your favourite language, make 100 C compilers out of spite Have a great day everyone
To view or add a comment, sign in
-
Python Iteration Using iter() and next() 🤔What is Iteration in Python? 👉 Iteration in Python is the process of accessing elements of a collection one by one 🌀 When using iter() and next(): 👉iter() → creates an iterator object from an iterable (like a list, tuple, or string). 👉next() → retrieves the next element from the iterator, one at a time. ‼️When the iterator has no more elements, next() raises StopIteration, signaling the end. ------------------------- ☺️ Here are Python (Beginner to Intermediate) GitHub Repos for you: 📁Python Variables: https://lnkd.in/e9rjz-_D 📁Python Operators: https://lnkd.in/e6hzgHSn 📁Python Conditionals: https://lnkd.in/egQNGZBF 📁Python Loops: https://lnkd.in/eezUg_-y 📁Python Functions: https://lnkd.in/eKdU6nex 📁Python Lists & Tuples: https://lnkd.in/eZ8KiQNs 📁Python Dictionaries & Sets: https://lnkd.in/eDmgj7pc 📁Python OOP: https://lnkd.in/eJFupCiK 📁Python DSAs: https://lnkd.in/ebR3rjkt ------------------------- ⚡ Follow my learning journey: 📎 GitHub: https://lnkd.in/ehu8wX85 🔗 GitLab: https://lnkd.in/eiiQP2gw 💬 Feedback: I’d love your thoughts and tips! 🤝 Collab: If you’re also exploring Python, DM me! Let’s grow together! -------------------------- 📞Book A Call With Me: https://lnkd.in/e23BtnR9 -------------------------- #iteration #pythonprogramming #iterationinpython #pythonforbeginners
To view or add a comment, sign in
More from this author
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