今天我们将探讨Python数。之前我们学习了Python包。如果你想你可以找到它在这里.
Python数字
存储数值的数据类型称为数字。如果更改数字数据类型的值,则会生成新分配的对象。所以你可以调用不可变的号码。
我们可以简单地通过给变量赋值来创建一个number对象。我们也可以操作它们,如下面的例子所示。
#create two number objects
var1=2
var2=3
# to print them
print(var1)
print(var2)
#to delete one of them
del var1
不同的数值类型
Python支持四种不同的数据类型。
int– signed integers. Can hold both positive and negative valuelong– long integers. Similar like int. But range of this data type is unlimitedfloat– floating point real values. Holds real numbers.complex– values of the form r+ij. Holds complex numerical values.
Python数字和类型转换
我们可以将数据类型从一种类型转换为另一种类型。这通常也被称为类型铸造。这里有一些例子。
int(x)– converts x to a plain integer.long(x)– converts x to a long integer.float(x)– converts x to a floating point number.complex(x)– converts x to a complex number with real part x and imaginary part zero.complex(x,y)– converts x to a complex number with real part x and imaginary part y.
下面是一些类型转换的例子。
确定类型
我们还可以确定一个变量所包含的数值类型。
a = 25
# Output:
print(type(a))
# Output:
b=25.0
print(type(b))
# Output: True
print(isinstance(b, float))
上面的代码,如果我们运行它将产生以下输出。
带前缀的Python数字
我们以10为基数处理我们的生活。但在计算机程序中,我们可能还需要处理其他基数的数字,如二进制数(以2为基数)、十六进制数(以16为底)、八进制数(以8为底)等。我们可以在这些数字前面加上前缀,如下所示-
# Output: 10
print(0b1010)
# Output: 15
print(0xF)
# Output: 13
print(0o15)
此代码将生成如下输出。
关于复数的更多信息
python内置了一些函数来支持一些复杂的访问器。为了更好地理解下面的代码。
# different complex numbers and their real and imaginary part
complex1 = (1,2)
print(complex1)
complex2=(2,-3)
print(complex2)
complex3= 3+4j
print(complex3)
complex4=2+3j
print(complex4)
#some built-in accessors
print(complex4.real) # gives the real part of a complex number
print(complex4.imag) #gives the imaginary part of a imaginary number
print(complex4.conjugate()) # gives the complex conjugate of a complex number
#some built-in functions for complex numbers
print(abs(complex3)) #gives the magnitude of a complex number
print(pow(complex3,2)) #raise a complex number to a power
上面的输出将生成以下代码-
因此,这是对python数字的快速汇总。确保你自己运行每一段代码。此外,探索事物和跳出框框思考是更好的做法。如果你有任何疑问,请随时留言。#happy_编码*