Underscores inside numeric literals improve readability by grouping digits. They do not change the numeric value.
Understanding the Concept
Large values such as 1000000 can be hard to scan. Python allows underscores between digits in many numeric literal forms, such as 1_000_000 or 0b1111_0000. The underscore is not included in the resulting number. It is a source-code readability feature, not a thousands separator that appears automatically in output. Placement rules apply; arbitrary leading, trailing, or repeated underscores are invalid.
When and Why You Would Use This
Group a large count and a bit pattern to make their scale and structure clearer. Keep grouping consistent so other developers can recognize the representation quickly.
Practical Example
annual_visits = 1_250_000
permission_bits = 0b1111_0000
print(annual_visits)
print(permission_bits)
Understanding the Example
The output is 1250000 and 240. Neither displayed value contains the source underscores because both names refer to ordinary int objects.
Example Output
1250000
240
Try It Yourself
Rewrite three large numeric literals using groups of three digits and verify they calculate the same totals.
Common Beginner Mistakes
- Expecting underscores to appear in default numeric output.
- Placing underscores where Python does not allow them, such as at the end of a literal.
- Confusing underscore grouping in source code with formatting a number for a user.
Key Takeaways
- Underscores in numeric literals improve source readability.
- They do not affect the stored numeric value.
- Output formatting is a separate operation.