Writing big numbers cleanly
What's easier to read — 1000000 or 1_000_000?
Python lets you write large numbers with underscores as separators. The underscores are ignored when the code runs — they're just there for you.
The problem
Big numbers are hard to read at a glance:
Python
How many zeros is that? You have to count. That's a bug waiting to happen.
The fix
Python
Python strips the underscores completely — the values are identical to the versions without them.
It works on floats too
Python
The underscores can go anywhere
Python doesn't enforce where the underscores go — but grouping by thousands is the convention that makes the most sense to most readers:
Python
Stick to groups of three unless you have a good reason not to.
Key takeaways
- Use
_to separate digits in large numbers — Python ignores them completely - Works on both integers and floats
- Group by thousands (
1_000_000) — it's the convention everyone expects
No comments yet. Add the first comment to start the discussion.