Why -1 % 5 Is 4 in Python (But -1 in C/Java) We all learn that % means “remainder”. But here’s something interesting: In Python: -1 % 5 Result: 4 In C, C++, or Java: -1 Same math. Different answers. Why? Python thinks in circles. C/C++/Java think in straight lines. First Understand Modulo Like a Circle. Forget division for a moment. Think of numbers arranged in a circle: 0 → 1 → 2 → 3 → 4 → (back to 0) This is mod 5. It means numbers are allowed to stay only between: 0 and 4 Now ask: If you move 1 step backward from 0, where do you land? You wrap around to: 4 So mathematically: -1 mod 5 = 4 Because modulo means: “Wrap the number into the range 0 to n-1” Python’s Rule: Python follows the mathematical definition. > Result stays inside 0 to n-1 > Sign follows the divisor (positive, here 5) So: -1 % 5 = 4 -2 % 5 = 3 -6 % 5 = 4 Always wrapped into the positive range. C / C++ / Java’s Rule: These languages think differently. They: > Keep the sign of the first number (negative, here -1) > Allow negative remainders So: -1 % 5 = -1 No wrapping. #Python #Programming #ComputerScience #ContinuousLearning
Python vs C/Java Modulo Math: Why -1 % 5 = 4
More Relevant Posts
-
Python 3.15 might be shipping one of the most exciting performance tools Python has added in a while, that too right after the GIL-free release. It is called Tachyon. Python is adding a new statistical sampling profiler under `profiling.sampling` called Tachyon, and the positioning is what caught my attention: - attach to a running Python process - no code changes - no restart - designed for low-overhead profiling - supports outputs like flamegraphs, speedscope-compatible stacks, Firefox Profiler, heatmaps, live TUI, async-aware views, and even opcode-level profiling The docs go even further and describe it as capable of sampling at up to 1,000,000 Hz and suitable for production performance debugging. With ML pipeline domination and RESTful servers now written increasingly in Python, this profiler will be a great addition. No longer will the notion of “run a profiler locally and hope the issue reproduces” carry on, and profiling becomes a first-class citizen, as in languages like Java. This is from the Python 3.15 alpha docs, so details may change before final release. But this is absolutely worth watching. A big thanks to the Python Software Foundation and Hugo van Kemenade for the updates and articles. Read more in the link below: https://lnkd.in/eUJ3C4N7 #Python #Python315 #Performance #Profiling #SystemsEngineering #Observability #Backend #SoftwareEngineering
To view or add a comment, sign in
-
Python GIL explained: why it exists and how it affects multithreading Many developers hear about the Python GIL and assume one thing: “Python can't use multiple CPU cores.” But the reality is a bit more nuanced. What the GIL actually is The Global Interpreter Lock (GIL) is a mutex inside CPython that ensures only one thread executes Python bytecode at a time. Even if your program has multiple threads, only one can run Python code simultaneously. Example: Thread A → running Thread B → waiting Thread C → waiting This means Python supports threads, but they take turns executing code. Why Python has the GIL The main reason is memory management. CPython relies heavily on reference counting for garbage collection. Every Python object tracks how many references point to it. When the count reaches zero, the object can be safely removed from memory. If multiple threads updated these counters simultaneously, memory corruption could occur. The GIL prevents this by ensuring only one thread modifies Python objects at a time. Trade-off: simpler interpreter design safer memory management faster single-thread performance How the GIL affects multithreading The limitation mainly impacts CPU-bound workloads. Example: def compute(): for i in range(10_000_000): pass Running this across multiple threads does not give real parallelism because threads must wait for the GIL. Thread A → holds GIL Thread B → waiting Thread C → waiting The workload becomes effectively serialized. Why Python threads still work well for web servers Python threads still scale well for I/O-bound tasks. Examples: API requests database queries file operations While a thread waits for I/O, the interpreter releases the GIL, allowing another thread to run. That's why frameworks like FastAPI and Django can handle many concurrent requests. Common ways developers work around the GIL 1️⃣ Multiprocessing Each process has its own interpreter and its own GIL. 2️⃣ Native extensions Libraries like NumPy or PyTorch run heavy computations in C/C++ and release the GIL. 3️⃣ Async I/O Libraries like asyncio allow thousands of concurrent tasks in a single thread. ## Interesting development: Python without the GIL Simple visual model Threads → Queue → GIL → CPU Only one thread can pass through the GIL and execute Python bytecode. Question for the community: How do you handle CPU-bound workloads in Python? multiprocessing distributed workloads native extensions #Python #PythonProgramming #BackendDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
-
💡 My Python Learning Notes (Simple but Powerful Concepts) While learning Python and programming fundamentals. I realized something interesting the most powerful concepts are often the simplest ones. Few ideas that really stood out to me 👇 1. Integer A data type that represents whole numbers without fractions. Simple, but essential for calculations and logic in programming. 2. String A sequence of characters used to represent textual information everything from user input to messages like "Hello World". 3. Immutable Data Types Some data types cannot be changed after they are created. Instead of modifying them, Python creates a new object in memory. Understanding this helps write more predictable and efficient code. 4. Interpreter vs Compiler Interpreter (Python, JavaScript, Ruby): • Executes code line by line • Easier to debug • Slightly slower execution Compiler (C, C++, Go, Java): • Translates the entire program at once • Faster execution • Errors appear after compilation 5. Python Execution Flow Source Code → Syntax Check → Bytecode → Python Virtual Machine → Output Example: print("Hello World") ➡ Output: Hello World 📌 My biggest takeaway: Programming is not just about writing code it's about understanding how the computer actually thinks and processes instructions. #Python #Programming #DataAnalytics #AI #ContinuousLearning #TechLearning
To view or add a comment, sign in
-
-
📌 Python Basics Every Beginner Should Practice 🐍 Sometimes strong programmers are built from simple basics. Here are some easy Python snippets I practiced today 👇 # 1️⃣ Even or Odd Check num = 7 print("Even" if num % 2 == 0 else "Odd") # 2️⃣ Sum of List Elements numbers = [1, 2, 3, 4, 5] print("Sum:", sum(numbers)) # 3️⃣ Length of String name = "Mansi" print("Length:", len(name)) # 4️⃣ Largest of Two Numbers a, b = 10, 20 print("Largest:", a if a > b else b) # 5️⃣ Print Numbers from 1 to 5 for i in range(1, 6): print(i) # 6️⃣ Check Positive, Negative or Zero num = -3 if num > 0: print("Positive") elif num < 0: print("Negative") else: print("Zero") # 7️⃣ Simple Multiplication Table n = 5 for i in range(1, 6): print(n, "x", i, "=", n * i) # 8️⃣ Reverse a String text = "Python" print(text[::-1]) ✨ Learning step by step towards Data Science Consistency > Perfection 🚀 #Python #CodingBasics #LearnInPublic #FutureDataScientist
To view or add a comment, sign in
-
Today I learned something in Python that genuinely surprised me… In languages like Java or C++, if you mark a variable as private, it’s strictly enforced. You simply can’t access it from outside the class. But in Python? -- 𝗡𝗼𝘁𝗵𝗶𝗻𝗴 𝗶𝘀 𝘁𝗿𝘂𝗹𝘆 𝗽𝗿𝗶𝘃𝗮𝘁𝗲. Even if you use __variable, you can still access it using name mangling if you know the class name. At first, I’ll be honest — this felt wrong. I thought: “Why would a language not let me fully protect my data?” But then I came across a simple line that completely changed my perspective: “𝗣𝘆𝘁𝗵𝗼𝗻 𝗶𝘀 𝗺𝗮𝗱𝗲 𝗳𝗼𝗿 𝗮𝗱𝘂𝗹𝘁𝘀.” And suddenly… it made sense. Python doesn’t enforce strict access control because it follows a different philosophy: • We are all responsible developers • We respect conventions • We don’t break things just because we can In Python: _variable → means “this is internal, please don’t touch” __variable → adds name mangling (stronger hint, not a lock) But ultimately… • It’s based on trust, not restriction • And honestly, that’s kind of powerful. Instead of forcing rules, Python assumes: “You know what you’re doing.” 𝗠𝘆 𝘁𝗮𝗸𝗲𝗮𝘄𝗮𝘆: Good code isn’t just about what a language allows or restricts… It’s about discipline, readability, and intent. #Python #Programming #SoftwareEngineering #Coding #Developers #Learning #CleanCode
To view or add a comment, sign in
-
When I was in my first year of university, I used to “trick” my friends with programming questions just to prove that I knew a bit more than them 😎 Looking back, I realize it didn’t really make me cool but it did make me curious about how languages actually work under the hood. One of the questions I asked was: Is it possible to increment or decrement the loop control variable inside a for loop in Python based on a condition? The answer is NO . WHY ? In Python, a for loop works like this: it takes values one by one from a sequence (for example, range(10) gives numbers from 0 to 9). Each time the loop runs, Python automatically assigns the next value to the variable i. So even if we change i inside the loop (like i = i + 1), it doesn’t matter. In the next iteration, Python will again replace i with the next value coming from range(10). That’s why we cannot control the loop variable this way in Python the loop is controlled by the sequence, not by our manual changes. But in languages like C++ or Java, the loop variable is part of the loop control itself. When we change i inside the loop, we are directly changing the value that the loop will use in the next step. So the loop behavior actually changes. Python: The loop controls i. C++ / Java: we control i . One thing I’ve learned is that true understanding comes from curiosity , and sharing that journey makes the experience even better. Adding a quick proof here code on the left, output on the right. The top part is Python, and the bottom part is C++.
To view or add a comment, sign in
-
-
🚀 Day 17/30 – Python OOPs Challenge 💡 Method Overloading in Python In some languages (like Java), we can create multiple methods with the same name but different parameters. That is called Method Overloading. But what about Python? 🤔 🔹 Important: Python does NOT support traditional method overloading directly. If we write: ``` class Test: def show(self): print("First") def show(self): print("Second") ``` Only the second method will work. Output: Second The first one gets overwritten. 🔹 So how do we achieve overloading in Python? We use: - Default arguments - Variable-length arguments (*args) 🔹 Example using default arguments: ``` class Calculator: def add(self, a, b=0, c=0): print(a + b + c) c1 = Calculator() c1.add(5) c1.add(5, 10) c1.add(5, 10, 15) ``` 🔹 What happened here? Same method name → different number of arguments → works fine. This is how Python handles method overloading. 📌 Key takeaway: Python achieves method overloading using *default arguments or args. 👉 Day 18: Abstraction in Python (coming tomorrow) 👍 Like | 💬 Comment | 🔁 Share 📍 Follow me to learn Python OOP step by step #Python #OOP #LearningInPublic #30DaysOfPython #CodingJourney
To view or add a comment, sign in
-
Excel users get frustrated seeing errors while trying Python in Excel or while practicing Python separately (if they are new to Python) First, remember that every programmer sees errors daily. This is the reason Stack Overflow is one of the most visited developer platforms in the world. If you are coming from Excel with no prior programming experience, understanding why the error occurred makes you faster and more confident. Here are common errors new Python users face 👇 SyntaxError Missing colon, bracket, indentation issue. Python is strict about structure. NameError Using a variable that hasn’t been defined yet. TypeError Trying to combine incompatible types. Example: adding a number to text. IndexError Trying to access a position that doesn’t exist in a list or dataframe. KeyError Trying to access a column or dictionary key that isn’t present. AttributeError Calling a method that doesn’t exist for that object. ValueError Correct type, but inappropriate value (e.g., invalid input). ImportError / ModuleNotFoundError Python can’t find the library you’re trying to use. Shift your mindset from “Why is this breaking?” to “What is Python trying to tell me?” Errors are actually structured hints, if we observe carefully, we learn how that particular language works. What other errors confused you when you started? #Excel_Python #LearnersWorld
To view or add a comment, sign in
-
🧠 Python Concept: dict.get() vs Direct Access Accessing dictionary values safely. ❌ Direct Access student = {"name": "Asha", "age": 20} print(student["grade"]) Output KeyError: 'grade' If the key doesn’t exist, Python throws an error. ✅ Using dict.get() student = {"name": "Asha", "age": 20} print(student.get("grade")) Output None No crash. No error. ⚡ Provide a Default Value student = {"name": "Asha", "age": 20} print(student.get("grade", "Not Available")) Output Not Available 🧒 Simple Explanation 📚 Imagine asking a librarian for a book 📚 Direct access →Imagine if the book isn't there, they shout an error 😅 📚 get() → They calmly say “Not available.” 💡 Why This Matters ✔ Prevents crashes ✔ Cleaner error handling ✔ Safer dictionary access ✔ Very common in real projects 🐍 Small Python features often prevent big problems 🐍 dict.get() helps you safely access dictionary values without crashing your program. #Python #PythonTips #PythonTricks #AdvancedPython #CleanCode #LearnPython #Programming #DeveloperLife #DailyCoding #100DaysOfCode
To view or add a comment, sign in
-
-
Understanding Data in Python: Literals and Types When we write code, we are constantly working with different types of data. In Python, these fixed values are called Literals. Understanding them is key to writing bug-free programs! Here is a quick breakdown of the most common types: 1. Numbers (Integers & Floats) Integers (ints): These are whole numbers like 256 or -1. No decimals allowed. Floats: These are numbers with a fractional part, like 1.27. Even 2.0 is considered a float in Python. 2. Number Systems Computers don't just use the decimal system (Base 10). Python also lets us work with: Binary: Base 2 (uses only 0s and 1s). Octal: Base 8. Hexadecimal: Base 16 (uses numbers 0-9 and letters A-F). 3. Working with Strings & Quotes Ever wondered how to put a quote inside a sentence? You have two easy ways: The Escape Character: Use a backslash, like 'I\'m happy.' Opposite Quotes: If you need an apostrophe, wrap the whole string in double quotes: "I'm happy." 4. Booleans: True or False Boolean values represent truth. In Python, we use True and False. Fun fact: In math contexts, Python treats True as 1 and False as 0. 5. The None Literal Sometimes, you need to show that a value is missing. Python uses a special object called None. It does not mean zero it means nothing is here. Mastering these basics makes it much easier to handle data as your projects grow! #Python #CodingTips #DataTypes #Programming #LearningToCode #TechBasics
To view or add a comment, sign in
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