Recently, I learnt a simple way of representing large numbers in python. Say, I had a large number like 8736570164
I had to manually (and erratically) point my finger at the monitor on that number - look for tens, thousands, millions, etc., draw imaginary commas and come to a conclusion, as taught in school. If we cleverly had to include the commas in the number itself, python treats them as items of a tuple, separated by those commas.
num = 8,736,570,164 # -> num = (8, 736, 570, 164)
# Print an awesome loop from 0 to 12345
for i in range(12,346):
print(i) # -> Oops! It prints from 12 to 345
So, what is the way then? Turns out, python (since version 3.6) provides the underscore character for digit separation, making it easier for human reading.
1_234_567_890 == 1234567890 # -> True
# Both are the number 1,234,567,890
So now, we can print our loop correctly, like:
# So now, I can print it better
for i in range(12_346):
print(i) # -> Voila! It prints from 0 to 12345
Now let us see some basic rules for this digit separator in numeric literals.
- A number cannot start or end with an underscore.
num = _314 # -> Error! Well, it creates a variable identifier, not a numeric literal
num = 314_ # -> Error!
- There cannot be multiple underscore separators next to each other.
12__345 # -> Error!
- Underscore separators can also be used for floats. But, there cannot be an underscore separator right next to the decimal point.
num = 3_.141592 # -> Error
num = 3._141592 # -> Also an error
num = 3.141_592 # -> Correct!
One last point: let us learn how to output an underscore separated number, given a normal one. We just have to convert it to a formatted string. Python adds in the separators based on the 'International Number System' (thousands, million, billion, etc.,).
num = 1234567890
print(f'{num:_}') # -> 1_234_567_890
When you ask AI to write your code, it typically always writes plain numeric literals like 1234567890.
If you want the AI to write how we humans want to read easily, specify in the prompt to "Format large numbers with underscore digit separators."
Code is read far more often than it is written, so save yourself (and your teammates) the headache of counting digits. Happy coding!
Top comments (0)