Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do underscores in a number mean? [duplicate]

I am wondering why the following variable is treated like a number?

a = 1_000_000 print (a) 

1000000

Shouldn't print(a) return 1_000_000?

like image 256
sophros Avatar asked Jan 02 '19 16:01

sophros


People also ask

What does an underscore number mean?

Python allows you to put underscores in numbers for convenience. They're used to separate groups of numbers, much like commas do in non-programming. Underscores are completely ignored in numbers, much like comments. So this: x = 1_000_000. is interpreted to be the same as this: x = 1000000.

What is the role of underscore when used in say to add 2 numbers?

Underscore(_) is also used to ignore the values. If you don't want to use specific values while unpacking, just assign that value to underscore(_). Ignoring means assigning the values to special variable underscore(_). We're assigning the values to underscore(_) given not using that in future code.

What is underscore before a variable mean?

An underscore in front usually indicates an instance variable as opposed to a local variable. It's merely a coding style that can be omitted in favor of "speaking" variable names and small classes that don't do too many things.

What's the meaning of single and Double underscores in Python?

Single Trailing Underscore( var_ ): Used by convention to avoid naming conflicts with Python keywords. Double Leading Underscore( __var ): Triggers name mangling when used in a class context. Enforced by the Python interpreter.


2 Answers

With Python 3.6 (and PEP-515) there is a new convenience notation for big numbers introduced which allows you to divide groups of digits in the number literal so that it is easier to read them.

Examples of use:

a = 1_00_00  # you do not need to group digits by 3! b = 0xbad_c0ffee  # you can make fun with hex digit notation c = 0b0101_01010101010_0100  # works with binary notation f = 1_000_00.0 print(a,b,c,f) 

10000

50159747054

174756

100000.0

print(int('1_000_000')) print(int('0xbad_c0ffee', 16)) print(int('0b0101_01010101010_0100',2)) print(float('1_000_00.0')) 

1000000

50159747054

174756

100000.0

A = 1__000  # SyntaxError: invalid token 
like image 77
sophros Avatar answered Sep 30 '22 21:09

sophros


Python allows you to put underscores in numbers for convenience. They're used to separate groups of numbers, much like commas do in non-programming. Underscores are completely ignored in numbers, much like comments. So this:

x = 1_000_000 

is interpreted to be the same as this:

x = 1000000 

However, you can't put two underscores right next to each other like this:

x = 1__000__000 #SyntaxError 
like image 24
Pika Supports Ukraine Avatar answered Sep 30 '22 20:09

Pika Supports Ukraine