Python 入门简明教程
1. 1. 与 Python 的第一次亲密接触-写给初学者 2. 2. Python 语法关键字 3. 3. Python 的注释和语法 4. 4. Python 基本数据类型 5. 5. Python 输入输出 6. 6. Python 运算符 7. 7. Python 变量 8. 8. Python 命名空间和变量生存范围 9. 9. Python 逻辑判断 10. 10. Python For 循环语法 11. 11. Python While 循环语法 12. 12. Python 循环语法中 break 与 continue的使用 13. 14. Python 三目运算符 14. 15. Python 循环语法中 pass 语句的使用 15. 16. Python 循环语法示例 16. 17. Python 函数 17. 18. Python main 函数 18. 19. Python print 函数 19. 20. Python print format 输出格式化 20. 21. Python print 输出到文件 21. 22. Python 输入 22. 23. Python import 导入模块 23. 25. Python 中递归的使用 24. 26. Python 匿名函数 25. 27. Python lambda 26. 28. Python PIP 包管理机制 27. 29. Python 命令行参数 28. 30. Python Numbers 包 29. 31. Python 随机数 30. 32. Python String 转 int 31. 34. Python 自定义异常 Exception 32. 35. Python 继承 33. 36. Python 父类 34. 38. Python 操作符重载 35. 39. Python __str__ and __repr__

30. Python Numbers 包

今天我们将探讨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支持四种不同的数据类型。

  1. int – signed integers. Can hold both positive and negative value
  2. long – long integers. Similar like int. But range of this data type is unlimited
  3. float– floating point real values. Holds real numbers.
  4. complex– values of the form r+ij. Holds complex numerical values.

Python数字和类型转换

我们可以将数据类型从一种类型转换为另一种类型。这通常也被称为类型铸造。这里有一些例子。

  1. int(x) – converts x to a plain integer.
  2. long(x) – converts x to a long integer.
  3. float(x) – converts x to a floating point number.
  4. complex(x) – converts x to a complex number with real part x and imaginary part zero.
  5. 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_编码*