Python - 数字文字表达式 [英] Python - Numeric Literal expressions

查看:40
本文介绍了Python - 数字文字表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮我理解为什么 Python 会执行以下操作吗?

<预><代码>>>>1,024语法错误:无效的令牌>>>1,024.46(1, 24.46)

第一个数字字面量 1,024 返回 SyntaxError,因为在 Python 中的数字字面量中从未使用逗号.

然而,第二个数字文字将数字 1,024.46 作为两个不同的数字返回,即使它是一个数字并且不会引发错误.

我想了解 Python 认为第二个数字是什么以及它与第一个数字有何不同?

解决方案

Python 将这样的两个逗号分隔值视为一个元组(因此使用括号).第一个是语法错误而第二个不是的原因是对于浮点数,允许以 0 开头,而对于整数则不允许.所以 (1, 024) 是一个语法错误,(1, 024.46) 不是,因为 024 不是一个有效的整数而是 024.46 是一个有效的浮点数.

Can somebody help me understand why Python does the following?

>>> 1,024
SyntaxError: invalid token

>>> 1,024.46
(1, 24.46)

The 1st numeric literal 1,024 returns a SyntaxError as commas are never used in numeric literals in Python.

However, the 2nd numeric literal returns the number 1,024.46 as two different numbers, even though it is one number and it does not throw an Error.

I am trying to understand what Python perceives the 2nd number to be and how is it different from the 1st one?

解决方案

Python considers two comma-separated values like that to be a tuple (hence the parentheses). The reason the first one is a syntax error and the second isn't is that for a float, starting with a 0 is permitted, while for an integer it isn't. So (1, 024) is a syntax error, (1, 024.46) isn't, because 024 is not a valid integer but 024.46 is a valid float.

这篇关于Python - 数字文字表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆