Python OOP: Message Passing ✉️ 🤔What is message passing in python OOP? In Python message passing means an object calling a method on another object or in other words basically, sending a “message” to ask it to do something 👉 We can simply understand from the dog and cat examples below 👉 I used dog.bark and cat.meouw to indicate that a message must be passed to dog and cat object 👉 When we call p.call_dog(my_dog), the Person object “sends a message” to the Dog object, asking it to bark() 👉 dog.bark() executes inside the Dog object and same with the cat example ‼️Message Passing is a way for objects to communicate in OOP ------------------------- ☺️ 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 -------------------------- #messagepassing #objectorientedprogramming #pythonoop #OOP #oopfundamentals #OOPinpython
More Relevant Posts
-
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
-
-
Object Oriented Programming (OOP) In Python! ⚡ I will be honest, for beginners like me, OOP can be a little bit troublesome in the beginning. However, the best way to understand OOP concepts is to practice and experiment! ⚙️ Unless u wont do OOP urself, it will keep scaring u like a ghostie! 👻 😊 What I know so far about OOP in Python: 1. Classes & Objects 2. Class & Object Attrbutes 3. Constructors (__init__()) 4. Private & Public Attributes 5. Decorators (@staticmethod, @classmethod, @property) 6. MRO & Super Method 7. Inheritance (single, multi-level, multiple) 🤓Quick Note: We dont have to use OOP in all python projects, however as a beginner, its a good practice to know about OOP concepts right from the start 🤓 My Python OOP GitHub repo is up! Make sure to check it out and learn more about OOP in detail -------------------------- ☺️ 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 ------------------------- ⚡ 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 -------------------------- #objectorientedprogramming #OOP #ooppython #pythonprogramming #pytonforbeginners #pythonlanguage
To view or add a comment, sign in
-
Day 7 of My 30-Day Python Learning Challenge 👉 Python Modules & Packages – Organizing Code Like a Real Project** Today’s learning took Python from basic scripts to real-world project structure. Modules and packages are what turn simple Python code into scalable, reusable, and organized applications — exactly how professional developers build software. 🔧 1️⃣ What Are Modules in Python? A module is simply a Python file (.py) that contains reusable code — functions, classes, or variables. Instead of writing long scripts, you divide your logic into separate files and import them when needed. ✔ Helps keep code clean ✔ Makes debugging easier ✔ Encourages reusability ✔ Ideal for team projects Example: utilities.py def add(a, b): return a + b You can use this in any other file: import utilities print(utilities.add(5, 10)) 📝 2️⃣ How to Create Your Own Module 1. Create a Python file (example: math_operations.py) 2. Add functions inside it 3. Import it into your main script math_operations.py def multiply(x, y): return x * y main.py from math_operations import multiply print(multiply(4, 5)) This is how real applications stay structured and maintainable. 📦 3️⃣ Built-in Python Modules Python provides hundreds of built-in modules that save time and effort. Today, I explored some essential ones: ✔ math Used for mathematical calculations import math print(math.sqrt(25)) ✔ datetime Used to handle dates and time from datetime import datetime print(datetime.now()) ✔ random Used for generating random numbers import random print(random.randint(1, 10)) Instead of writing logic from scratch, these modules allow you to perform complex operations with one line of code. 📥 4️⃣ How to Import Functions Different ways to import: 1. Import the whole module import math 2. Import specific functions from math import sqrt 3. Import with alias (short name) import datetime as dt 4. Import everything (not recommended) from math import * Imports make your code readable and avoid repetition across multiple files. 📦 5️⃣ What Are Packages? A package is a collection of modules stored in a folder. Inside the folder, an __init__.py file tells Python “this folder is a package.” Packages help you group similar modules together for large projects. Example folder structure: analytics/ __init__.py data_cleaning.py data_visualization.py calculations.py This structure is used in real-world applications like Django, Flask, Pandas, NumPy, etc. 🏗️ 6️⃣ Structuring Large Projects Using Modules & Folders A scalable Python project usually follows this format: project/ │ ├── main.py ├── config/ │ └── settings.py ├── utils/ │ └── helpers.py ├── services/ │ └── api.py └── modules/ └── salary.py This helps in: ✔ Organizing code logically ✔ Working better with teams ✔ Making the project easier to maintain ✔ Promoting code reuse across multiple files
To view or add a comment, sign in
-
✨ Ever wondered what happens behind the scenes when you run your Python code? 👀 Python Interpreter 🐍 Before you get into the real work of writing programs with the Python programming language, it's important to understand how the Python Interpreter works. A Python Interpreter is a program that reads and executes Python code. Think of it as a translator that tells the computer: “𝘏𝘦𝘺, 𝘵𝘩𝘪𝘴 𝘪𝘴 𝘸𝘩𝘢𝘵 𝘸𝘦’𝘷𝘦 𝘣𝘦𝘦𝘯 𝘢𝘴𝘬𝘦𝘥 𝘵𝘰 𝘥𝘰.” 😅 The main job of the interpreter is to read and execute your Python code. Depending on your environment (setup), you might start the interpreter by clicking an icon or by typing 𝚙𝚢𝚝𝚑𝚘𝚗 in your command line. When it starts, you’ll see something like this: 𝙿𝚢𝚝𝚑𝚘𝚗 𝟹.𝟺.𝟶 (𝚍𝚎𝚏𝚊𝚞𝚕𝚝, 𝙹𝚞𝚗 𝟷𝟿 𝟸𝟶𝟷𝟻, 𝟷𝟺:𝟸𝟶:𝟸𝟷) [𝙶𝙲𝙲 𝟺.𝟾.𝟸] 𝚘𝚗 𝙻𝚒𝚗𝚞𝚡 𝚃𝚢𝚙𝚎 "𝚑𝚎𝚕𝚙", "𝚌𝚘𝚙𝚢𝚛𝚒𝚐𝚑𝚝", "𝚌𝚛𝚎𝚍𝚒𝚝𝚜" 𝚘𝚛 "𝚕𝚒𝚌𝚎𝚗𝚜𝚎" 𝚏𝚘𝚛 𝚖𝚘𝚛𝚎 𝚒𝚗𝚏𝚘𝚛𝚖𝚊𝚝𝚒𝚘𝚗. >>> Here’s what it means 👇🏽 ✨ The first few lines contain information about the interpreter and the operating system it’s running on. ✨ The version number (3.4.0) shows you’re using Python 3, if it begins with a 2, that means Python 2. ✨ The last line (>>>) is a prompt that indicates the interpreter is ready for you to enter code. For example, one of the first commands I ever typed in my interpreter was this simple calculation 👇🏽 >>> 1 + 1 2 You’ll get an instant result. That was my “aha” moment 😅, realizing that even the simplest command was a conversation between me and my computer through Python. If you’re using Windows, the same concept applies, but your display might look a bit different, and it may even show the bit your Python interpreter is running on (e.g., 64-bit). But once you see the >>> prompt, you’re good to go! 😎 So next time you see that display on your command line, you’ll know exactly what’s going on! 😎 Think of the interpreter just like a messenger delivering a package (your code) to the computer, so it can open it, understand the instructions, and take action. I hope this helps you understand it better 😊💻 💬 What was the first thing you ever typed or tried when you started learning Python? 🐍 #Python #LearningJourney #DataAnalytics #CodingJourney #KeepBuilding
To view or add a comment, sign in
-
-
💠 Python Control Flow & Conditional Statements :- 💠 What is Control Flow? ➜ Control flow in Python decides the order in which statements are executed based on conditions and loops. • Purpose / Use :- ➢ To make decisions in code ➢ To repeat tasks automatically (loops) ➢ To control program execution dynamically 🔹 if Statement :- ➜ Executes a block of code only if a condition is True. Example :- a = 10 if a > 5: print("a is greater than 5") Output :- a is greater than 5 🔸 if–else Statement :- ➜ Executes one block if the condition is True, otherwise executes the else block. Example :- num = int(input("Enter a number: ")) if num % 2 == 0: print("Even number") else: print("Odd number") Input: 7 Output :- Odd number 🔹 elif Ladder :- ➜ Used to check multiple conditions one after another. If one condition is True, the rest are skipped. Example :- marks = 82 if marks >= 90: print("Excellent") elif marks >= 75: print("Good") elif marks >= 60: print("Average") else: print("Needs Improvement") Output :- Good ➥ Use :- When you need to test several conditions in a sequence. 🔸 Nested if :- ➜ You can use an if statement inside another if. It helps in checking multiple layers of conditions. Example :- x = 10 if x > 5: if x < 15: print("x is between 5 and 15") Output :- x is between 5 and 15 ➥ Use :- When decision-making depends on another condition. 🔹 for Loop :- ➜ Used to repeat a block of code for each item in a sequence (like list, string, or range). Example :- for i in range(5): print(i) Output :- 0 1 2 3 4 ➥ Use :- Best for iterating through lists, tuples, strings, etc. ➢ Example with List :- fruits = ["apple", "banana", "cherry"] for f in fruits: print(f) Output :- apple banana cherry 🔸while Loop :- ➜ Executes a block while the condition is True. Used when you don’t know beforehand how many times the loop should run. Example :- count = 1 while count <= 5: print(count) count += 1 Output :- 1 2 3 4 5 ➥Use :- When looping depends on a condition that changes dynamically. 🔹Loop Control Statements :- Keyword Description break ⟶ Stops the loop immediately continue ⟶ Skips current iteration & moves to next pass ⟶ Placeholder — does nothing (used in empty loops or blocks) Example :- for i in range(5): if i == 3: continue print(i) Output :- 0 1 2 4 🧩 Quick Summary :- if ➜ check a condition if-else ➜ choose between two paths elif ➜ check multiple conditions nested if ➜ layered decisions for ➜ fixed iterations while ➜ condition-based iterations #Python #ControlFlow #IfElse #Loops #ProgrammingBasics #LogicBuilding #Developers #LearnPython #CodeNewbie #PythonLearning
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
-
🐍 String Manipulation Operations in Python: A Beginner’s Guide If you’re learning Python, mastering string manipulation is a must! Strings are everywhere, from user input to data processing, and knowing how to handle them makes your code cleaner and smarter 💡 Let’s explore the most common string operations in Python with examples 👇 🧩 1. Concatenation (Joining Strings) Use the + operator to join two or more strings. first_name = "Zahid" last_name = "Hameed" full_name = first_name + " " + last_name print(full_name) ✅ Output: Zahid Hameed 🔠 2. Changing Case You can easily change the case of your text using built-in methods. text = "hello python" print(text.upper()) print(text.lower()) print(text.title()) ✅ Output: HELLO PYTHON hello python Hello Python ✂️ 3. Slicing Strings Extract specific parts of a string using slicing. message = "Python Programming" print(message[0:6]) print(message[-11:]) ✅ Output: Python Programming 🔍 4. Finding and Replacing Find specific text or replace one word with another. sentence = "I love Java" new_sentence = sentence.replace("Java", "Python") print(new_sentence) ✅ Output: I love Python 📏 5. String Length Count the total number of characters in a string using len(). word = "Python" print(len(word)) ✅ Output: 6 💬 6. Splitting and Joining Split a string into words and join them back with a custom separator. data = "Python is fun" words = data.split() joined = "-".join(words) print(words) print(joined) ✅ Output: ['Python', 'is', 'fun'] Python-is-fun 💡 Pro Tip: Strings in Python are immutable — once created, they can’t be changed. Every operation returns a new string instead of modifying the original one. 🚀 Why Learn String Manipulation? String handling is essential for: ✅ Data cleaning ✅ Web scraping ✅ File handling ✅ Chatbots ✅ Text analytics 💬 Your Turn! Which string operation do you find most useful in Python? Share your thoughts in the comments 👇 #Python #LearnPython #PythonForBeginners #DataScience #ProgrammingTips #ZahidLearnsPython
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
-
-
𝐓𝐡𝐞 𝐆𝐡𝐨𝐬𝐭 𝐢𝐧 𝐭𝐡𝐞 𝐌𝐚𝐜𝐡𝐢𝐧𝐞 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
-
🔍 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
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