专注分享与IT相关知识,关注我,一起升职加薪!
在Python编程语言中,一切都是对象。因此,数据类型被视为类,而变量是这些类的实例或对象。Python中有各种数据类型来表示值的类型。在本文中,我们将了解不同的Python数据类型,以及它们是如何按以下顺序赋给变量的:让我们开始吧。
![](https://img.haomeiwen.com/i26322751/cf1c53a5e5b4c8c8.png)
Python数据
类型变量用于保存不同数据类型的值。因为Python是一种动态类型的语言,所以在定义变量时不需要定义它的类型。解释器将值与其类型隐式绑定。Python使我们能够检查程序中使用的变量类型。在type()函数的帮助下,您可以找出传递的变量的类型。
x = 24
y = 14.7
z = "Welcome to Python"
print(type(x));
print(type(y));
print(type(z));
<type 'int'>
<type 'float'>
<type 'str'>
Python中的标准数据类型
变量用于保存不同类型的值。例如,人名必须存储为字符串,而员工ID必须存储为整数。
-
数字
-
字符串
-
列表
-
元组
-
词典 Python提供了各种标准数据类型,这些数据类型定义了每种类型的存储方法。Python中的标准数据类型包括:既然您已经了解了标准Python数据类型,让我们继续并详细了解每种数据类型。
号码
-
INT-用于12、2、7等有符号整数。
-
LONG-此整数用于更高范围的值,如908090800L、-0x1929292L等。
-
Float-用于存储浮点数,如1.5、701.89、15.2等。
- 复数-用于2.14j、2.0+2.3j等复数。
Number用于存储数值。当将数字分配给avariable时,Python会创建Number对象。有4种类型的数字数据:在Python中,您可以使用带有长整数的小写L。不过,使用大写字母L会更方便。
- 复数-用于2.14j、2.0+2.3j等复数。
a = 12
print(a, "is of type", type(a))
b = 5.05
print(b, "is of type", type(b))
c = 1+2j
print(c, "is complex number?", isinstance(1+2j,complex))
12 is of type <class 'int'>
5.05 is of type <class 'float'>
(1+2j) is complex number? True
String
字符串定义为用引号表示的字符序列。在python中,您可以使用单引号、双引号或三引号来定义字符串。
Python中的字符串处理可以使用各种内置函数和运算符来完成。在字符串处理的情况下,运算符+用于连接两个字符串。
str1 = 'Welcome to Python' #string str1
str2 = 'Python Programming' #string str2
print (str1[0:3])
print (str1[4])
print (str1 + str2)
Wel
c
Welcome to Python Python Programming
列表
列表类似于C中的数组,但在Python中可以包含不同类型的数据。该列表中存储的项目用逗号(,)分隔,并用方括号[]括起来。
您可以使用list[:]运算符来访问列表的数据。连接运算符(+)类似于字符串中的运算符。
list = [20, "welcome", "Python", 40]
print (list[3:]);
print (list);
print (list + list);
[40]
[20, 'welcome', 'Python', 40]
[20, 'welcome', 'Python', 40, 20, 'welcome', 'Python', 40]
元组
元组在许多方面类似于列表。与列表一样,元组也包含不同数据类型的项的集合。元组中的项目用双引号(,)分隔,并用括号()括起来。
元组是只读数据结构,您不能修改元组项目的大小和值。
tuple = ("welcome", "Python", 40)
print (tuple[1:]);
print (tuple);
print (tuple + tuple);
('Python', 40)
('welcome', 'Python', 40)
('welcome', 'Python', 40, 'welcome', 'Python', 40)
字典
字典是项的键-值对的有序集合。它类似于关联数组或哈希表,其中每个键存储一个特定值。键可以保存任何原始数据类型,而值是任意的Python对象。
词典中的条目用逗号分隔,并用大括号{}括起来。
dict = {1:'John', 2:'Rachel', 3:'Nancy', 4:'Daniel'};
print("1st name is "+dict[1]);
print (dict.keys());
print (dict.values());
1st name is John
[1, 2, 3, 4]
['John', 'Rachel', 'Nancy', 'Daniel']
说到这里,我们就到了文章的末尾。
![](https://img.haomeiwen.com/i26322751/3978256ada016fdb.jpg)
网友评论