sop*_*ros 17 python python-3.x
我想知道为什么以下变量被视为数字?
a = 1_000_000
print (a)
Run Code Online (Sandbox Code Playgroud)
百万
不应该print(a)回来1_000_000?
sop*_*ros 30
使用Python 3.6(和PEP-515),为引入的大数字提供了一种新的便利符号,它允许您在数字文字中划分数字组,以便更容易阅读它们.
使用示例:
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)
Run Code Online (Sandbox Code Playgroud)
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'))
Run Code Online (Sandbox Code Playgroud)
百万
50159747054
174756
100000.0
A = 1__000 # SyntaxError: invalid token
Run Code Online (Sandbox Code Playgroud)
为方便起见,Python 允许您在数字中添加下划线。它们用于分隔数字组,就像非编程中的逗号一样。下划线在数字中完全被忽略,就像注释一样。所以这:
x = 1_000_000
Run Code Online (Sandbox Code Playgroud)
解释为与此相同:
x = 1000000
Run Code Online (Sandbox Code Playgroud)
但是,您不能像这样将两个下划线紧挨着放置:
x = 1__000__000 #SyntaxError
Run Code Online (Sandbox Code Playgroud)
在英语国家,逗号通常用作千位分隔符,而在许多其他国家,句点用作千位分隔符。考虑到不同的约定,以及逗号和句点在 Python 中用于其他事物的事实,决定使用下划线作为分隔符。
| 归档时间: |
|
| 查看次数: |
1680 次 |
| 最近记录: |