Python变量类型——Number

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_42398077/article/details/98525865

1. 简介

Python 数据类型用于存储数值,数据类型是不允许改变的。


2. 数据类型


由于Python3 中已取消长整型,因此这里不再讨论长整型。

类型 说明 举例
整型(int) 包括正整数、负整数和零,均不带小数点 a = 10
浮点型(float) 由整数位和小数位组成,带小数点, 可用科学计数法表示 b = 10.0; c = 2.5e2
复数(complex) 由实数部分和虚数部分组成,可用a + bj 或者comlex(a, b)表示, 其中a和b都是浮点型 d = 10 + 0j; e = comlex(10, 0)

可以使用 type 函数查看变量的类型, 如上面的例子:

In [50]: a                                                                      
Out[50]: 10

In [51]: type(a)                                                                
Out[51]: int

In [52]: b                                                                      
Out[52]: 10.0

In [53]: type(b)                                                                
Out[53]: float

In [54]: c = 2.5e2                                                              

In [55]: type(c)                                                                
Out[55]: float

In [56]: d = 10 + 0j                                                            

In [57]: type(d)                                                                
Out[57]: complex

In [58]: e = complex(10, 0)                                                     

In [59]: type(e)                                                                
Out[59]: complex

3. 类型转换


方法 功能
int(x [,base ]) 将x转换为一个整数
long(x [,base ]) 将x转换为一个长整数
float(x ) 将x转换到一个浮点数
complex(real [,imag ]) 创建一个复数
str(x ) 将对象 x 转换为字符串
repr(x ) 将对象 x 转换为表达式字符串
eval(str ) 用来计算在字符串中的有效Python表达式,并返回一个对象
tuple(s ) 将序列 s 转换为一个元组
list(s ) 将序列 s 转换为一个列表
chr(x ) 将一个整数转换为一个字符
unichr(x ) 将一个整数转换为Unicode字符
ord(x ) 将一个字符转换为它的整数值
hex(x ) 将一个整数转换为一个十六进制字符串
oct(x ) 将一个整数转换为一个八进制字符串

对于具体的函数,在ipython中可使用help函数来查看其文档, 比如:

In [60]: help(int) 

Help on class int in module builtins:
class int(object)
 |  int(x=0) -> integer
 |  int(x, base=10) -> integer
 |  
 |  Convert a number or string to an integer, or return 0 if no arguments
 |  are given.  If x is a number, return x.__int__().  For floating point
 |  numbers, this truncates towards zero.
 |  
 |  If x is not a number or if base is given, then x must be a string,
 |  bytes, or bytearray instance representing an integer literal in the
 |  given base.  The literal can be preceded by '+' or '-' and be surrounded
 |  by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
 |  Base 0 means to interpret the base from the string as an integer literal.
 |  >>> int('0b100', base=0)
 |  4
 |  
 |  Methods defined here:
 |  
 |  __abs__(self, /)
 |      abs(self)
 |  
 |  __add__(self, value, /)

猜你喜欢

转载自blog.csdn.net/weixin_42398077/article/details/98525865
今日推荐