Python数据类型用于定义变量的类型。之前我们学习了Python中的语句和注释。如果你想的话,你可以从Python注释和语句.
目录
Python数据类型
有不同类型的python数据类型。一些内置的python数据类型包括:
Python数据类型和数字
Python numeric数据类型用于保存以下数值:;
- int–;包含长度不限的有符号整数。
- long-保存长整数(存在于python2.x中,在python3.x中不推荐使用)。
- float-保存浮动精度数字,精度高达小数点后15位。
- 复数-保存复数。
在Python中,我们不需要声明数据类型,而声明一个变量,比如C或C++。我们可以简单地在变量中赋值。但是如果我们想知道它现在持有什么类型的数值,我们可以使用类型(),如下所示:
#create a variable with integer value.
a=100
print("The type of variable having value", a, " is ", type(a))
#create a variable with float value.
b=10.2345
print("The type of variable having value", b, " is ", type(b))
#create a variable with complex value.
c=100+3j
print("The type of variable having value", c, " is ", type(c))
如果您运行上面的代码,您将看到如下图所示的输出。
Python数据类型和字符串
字符串是一个字符序列。Python支持Unicode字符。通常,字符串由单引号或双引号表示。
a = "string in a double quote"
b= "string in a single quote"
print(a)
print(b)
# using "," to concatenate the two or several strings
print(a,"concatenated with",b)
#using "+" to concate the two or several strings
print(a+" concated with "+b)
上面的代码产生的输出如下图所示-
Python数据类型和列表
list是Python中唯一的通用数据类型。从某种意义上讲,它与C/C++中的数组是一样的。但是Python中列表的有趣之处在于它可以同时保存不同类型的数据。正式列表是用方括号([])和逗号(,)写入的一些数据的有序序列。
#list of having only integers
a= [1,2,3,4,5,6]
print(a)
#list of having only strings
b=["hello","john","reese"]
print(b)
#list of having both integers and strings
c= ["hey","you",1,2,3,"go"]
print(c)
#index are 0 based. this will print a single character
print(c[1]) #this will print "you" in list c
上面的代码将产生如下输出-
Python数据类型和元组
元组是另一种数据类型,它是类似于list的数据序列。但它是不变的。这意味着元组中的数据是写保护的。元组中的数据是用括号和逗号写的。
#tuple having only integer type of data.
a=(1,2,3,4)
print(a) #prints the whole tuple
#tuple having multiple type of data.
b=("hello", 1,2,3,"go")
print(b) #prints the whole tuple
#index of tuples are also 0 based.
print(b[4]) #this prints a single element in a tuple, in this case "go"
上面这个python数据类型元组示例代码的输出如下所示。
字典
Python字典是键-值对形式的无序数据序列。它类似于哈希表类型。字典是用大括号写成的key:value
. It is very useful to retrieve data in an optimized way among a large amount of data.
#a sample dictionary variable
a = {1:"first name",2:"last name", "age":33}
#print value having key=1
print(a[1])
#print value having key=2
print(a[2])
#print value having key="age"
print(a["age"])
如果运行这个python字典数据类型示例代码,输出将如下图所示。
因此,这就是今天关于python数据类型的全部内容。别忘了在自己的机器上运行每一段代码。也不要粘贴。试着自己写几行代码。#happy_编码*
参考文献:数据类型的Python文档