Python在添加两个变量时选择的默认值是什么?

2024-05-26 17:43:08 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我们有以下上下文:

x = 3  
y = 4  
z = x + y

zint还是float等等?我很清楚,浮点数确实以.something结尾,但是我不清楚Python是否会支持浮点类型而不是整数类型,因为用户是否要将此变量更改为其他类型是不可预测的。你知道吗


Tags: 用户类型结尾整数floatsomethingint浮点
3条回答

这很容易测试。默认情况下,如果对两个整数执行算术运算,Python将结果存储为整数。你可以在这里看到。你知道吗

>>> x = 1
>>> y = 2
>>> z = x + y
>>> type(z)
<class 'int'>

type函数将告诉您Python中对象的“type”是什么。在这里我们可以看到z变量的类型是int,它代表整数。你知道吗

如果我们对两种不同的类型执行算术,比如整数和浮点,结果是十进制,那么结果将存储为浮点。你知道吗

>>> x = 2.55
>>> y = 3
>>> z = x / 3
>>> type(z)
<class 'float'>

现在,如果对一个整数和一个浮点数执行算术,结果显示为非十进制,Python仍然会将其存储为一个浮点数。你可以在这里看到。你知道吗

>>> x = 2.5
>>> y = 1.25
>>> z = x / y
>>> type(z)
<class 'float'>
>>> print(z)
2.0

总之,当您进行算术运算时,只有当所涉及的两个数字也是整数时,Python才会将结果存储为整数。如果一个是float,那么新变量也将是float类型(或类)。你知道吗

希望这有帮助:)

当混合类型时,总是会得到'wider'类型,其中复数比float宽,而float又比整数宽。当两个值都是同一类型(所以不是混合类型)时,只会得到一个类型作为结果。你知道吗

Numeric Types documentation

Python fully supports mixed arithmetic: when a binary arithmetic operator has operands of different numeric types, the operand with the “narrower” type is widened to that of the other, where plain integer is narrower than long integer is narrower than floating point is narrower than complex. Comparisons between numbers of mixed type use the same rule.

因此,当对不同类型的数字求和时,Python会将较窄的类型加宽,使其与较宽的类型相同。对于带有整数和浮点数的操作,您将得到一个float,因为float更宽。你知道吗

但是,如果两个操作数都是同一类型,则更改类型没有意义。在那种情况下改变类型将是非常令人惊讶的。你知道吗

例如:

>>> type(3 + 4)
<class 'int'>
>>> type(3.0 + 4)
<class 'float'>
>>> type(3.0 + 4.0)
<class 'float'>

如果浮点数或整数之间的差异对应用程序很重要,请显式地将用户输入转换为浮点数,以便您知道每次处理的是什么。你知道吗

user_input = float(input())

相关问题 更多 >

    热门问题