Python Division Gotchas: Floor Division and Negative Numbers

𝗔 𝗣𝘆𝘁𝗵𝗼𝗻 𝗴𝗼𝘁𝗰𝗵𝗮 𝘁𝗵𝗮𝘁 𝗯𝗶𝘁𝗲𝘀 𝗲𝘃𝗲𝗿𝘆 𝗯𝗲𝗴𝗶𝗻𝗻𝗲𝗿 𝗲𝘅𝗮𝗰𝘁𝗹𝘆 𝗼𝗻𝗰𝗲. >>> 10 / 2 5.0 Wait... 5.0? Not 5? Python's division operator 𝘢𝘭𝘸𝘢𝘺𝘴 returns a float. Even when the result is a whole number. This seems like a minor detail until you try to use that result as a list index: → my_list[10 / 2] # TypeError! The fix is floor division: → 10 // 2 returns 5 (an integer) But here's another trap: floor division rounds toward 𝘯𝘦𝘨𝘢𝘵𝘪𝘷𝘦 𝘪𝘯𝘧𝘪𝘯𝘪𝘵𝘺, not toward zero. → -7 // 2 returns -4, not -3 Small details. Big consequences. The developers who know these quirks aren't necessarily smarter—they've just been burned by them before and learned. Now you know without the burn. I'm writing "Zero to AI Engineer: Python Foundations" in public. Follow along on Substack for behind-the-scenes updates and excerpts (link in comments). What Python gotcha caught you by surprise? #Python #Programming #SoftwareEngineering #TechCareers #LearnToCode

To view or add a comment, sign in

Explore content categories