Python基础之八大基本数据类型

【一】数据类型引入

【1】为什么要学习变量和基本数据类型

  • 变量能帮助我们在程序中可以根据自己的意愿去修改数据,去展现不一样的效果
  • 基本数据类型是让我们更好的理解不同类型的数据在电脑中是怎么处理的

【2】基本数据类型介绍

  • 数字类型(整数和浮点数)
  • 字符串类型
  • 列表类型
  • 字典类型
  • 布尔类型
  • 元祖类型
  • 集合类型
#定义一个变量名为name 变量值为scott
name = "scott"
print(name,type(name))

#定义一个变量名为age 变量值为20
age = "20"
print(age,type(age))

#定义一个变量名为height 变量值为180cm
height = "180cm"
print(height,type(height))

#定义一个变量名为weight 变量值为70kg
weight = "70kg"
print(weight,type(weight))

【二】数字类型

【1】整数类型

  • 整数类型(int)表示整数
  • 整数类型可以参与各种数学运算
#类似年龄,一个个数字等
age = 18
num1 = 1
num2 = 2
num3 = 3
#查看变量值
print(age,num1,num2,num3)  #18 1 2 3
#查看数据类型
print(type(age),type(num1),type(num2),type(num3)) #<class 'int'> <class 'int'> <class 'int'> <class 'int'>

【2】浮点数类型

  • 浮点数类型(float)表示带小数点的数字
  • 浮点数类型和整数类型一样也可以参与各种数学运算,并且还可以跟整数类型混合运算
#浮点数类型
float1 = 3.14
float2 = 2.0
float3 = 4.2
#整数与浮点数实现数学运算
a = 3
b = 2.5
print(a+b)  #5.5
print(a-b)  #0.5
print(a*b)  #7.5
print(a/b)  #1.2
#也可实现大小的比较
print(a>b) #运行返回值为True

【三】字符串

【1】定义

  • 字符串类型(str)用于表示文本信息

  • 字符串可以使用单引号、双引号或三引号进行定义

    name1 = 'scott'
    name2 = "scott"
    name3 = '''scott'''
    name4 = """scott"""
    
    #引号嵌套配对问题
    # 正确示范一:双引号内部,可以使用单引号,并且可以使用多个单引号
    msg_1 = "My name is Dream , I'm 18 years old!,hope your life : 'wonderful!'"
    
    # 正确示范二:单引号内部,可以使用双引号,但是只支持双引号,不支持单个的单引号
    msg_2 = 'My name is Dream , I am 18 years old!,hope your life : "wonderful!"'
    
    # 错误示范: 单引号内部,嵌套了单引号,会导致语法错误 ---- End of statement expected
    msg_3 = 'My name is Dream , I'm 18 years old!,hope your life : "wonderful!"'
    
    #多行字符串,通过三引号来定义
    msg_1 = '''         
    	 
    '''
    msg_2 = """
    	
    """
    

【2】字符串的使用

#字符串的"相加"和"相乘"运算
#相加
a = "hello"
b = "world"
c = a + "," + b + "!"
print(c) #输出 hello,world!
#相乘
a = '@' * 10
print(a) #输出 @@@@@@@@@@

#索引取值(从0开始计数)
msg = 'Hello World'
print(len(msg))  # 11
# 取索引为 0 的位置的元素
print(msg[0])  # H
# 取索引位置为 10 的元素 
#取索引值为负数
# 取索引为 -1 的位置的元素
print(msg[-1])  # d
# 取索引位置为 -11 的元素 
print(msg[-11])  # H

【3】格式化输出

[1] % 输出

# 格式化输出语法一 : %
name = "scott"
age = 18
height = 180

# 使用 %s 占位符,输出字符串
print("My name is %s." % name)  
# My name is scott.

# 使用 %d 占位符,输出整数
print("My age is %d." % age)  
# My age is 18.

# 使用 %f 占位符,输出浮点数,默认保留六位小数
print("My height is %f." % height)  
# My height is 180.000000.

# 使用 %.2f 占位符,保留两位小数
print("My height is %.2f." % height)  
# My height is 180.00.

# 使用 %x 占位符,输出十六进制整数
number = 255
print("Number in hex: %x." % number)  
# Number in hex: ff.

# 两个以上的占位符格式化输出
print("My name is %s; My age is %d" % (name, age)) 
# My name is scott; My age is 18
  • 在上例中,%s%d 是占位符,分别表示字符串和整数,而 (name, age) 是传入这两个占位符的实际值。
  • 占位符类型
    • %s:字符串
    • %d:整数
    • %f:浮点数
    • %x:十六进制整数

[2] formate 输出

  • 使用 format 方法进行格式化输出,通过花括号 {} 表示占位符,然后调用 format 方法传入实际值
name = "scott"
age = 18
# 格式化输出语法三 : format
print("My name is {}; My age is {}".format(name, age))
# My name is scott; My age is 18
  • 在这个例子中,{} 是占位符,它会按顺序依次填充传入 format 方法的值

[3] f + {} 输出

  • 使用 f-string(f + {})进行格式化输出,通过在字符串前加上 fF 前缀,然后在字符串中使用 {} 表示占位符,并在 {} 中直接引用变量。
name = "scott"
age = 18
# 格式化输出语法二 : f + {}
print(f"My name is {name}; My age is {age}")
# My name is scott; My age is 18

(4)字符串的转义

转义字符 说明
\n 换行符,将光标位置移到下一行开头。
\r 回车符,将光标位置移到本行开头。
\t 水平制表符,也即 Tab 键,一般相当于四个空格。
\a 蜂鸣器响铃。注意不是喇叭发声,现在的计算机很多都不带蜂鸣器了,所以响铃不一定有效。
\b 退格(Backspace),将光标位置移到前一列。
\ 反斜线
' 单引号
" 双引号
\ 在字符串行尾的续行符,即一行未完,转到下一行继续写。
# 换行符
print("Hello\nWorld")
# Hello
# World

# 制表符
print("Name\tAge")
# Name    Age

# 反斜线
print("This is a backslash: \\")
# This is a backslash: \

# 单引号
print("I'm a programmer.")
# I'm a programmer.

# 双引号
print("He said, \"Hello.\"")
# He said, "Hello."

# 回车符与退格符
print("One\rTwo\bThree")
# Two Three

【四】列表

【1】定义

  • 列表类型(list)用来存取多个相同属性的值,帮助我们取得多个同属性值中的某个我们想要的值,用于记录多个同属性的元素,可以存放任意数据类型的元素,元素可以替换

    # 字符串类型
    stu_name=’张三 李四 王五’
    # 列表类型
    name_list = ['张三', '李四', '王五']
    

【2】列表的使用

#索引取值
student1 = name_list[2]
student2 = name_list[0]
print(student1)  #输出 王五
print(student2)  #输出 张三

#列表嵌套
name_list1 = ['张三', '李四', '王五']
name_list2 = ['大王', '小王', 'Q']
list = [name_list1,name_list2]

#嵌套取值
student1 = list[1][0]
student2 = list[0][-1]
print(student1)  #输出 大王
print(student2)  #输出 王五

【五】字典

【1】定义

  • 字典类型(dict)需要用一个变量记录多个值,但多个值是不同属性的

  • 大括号括起来,内部可以存放多个元素,元素与元素之间使用逗号隔开,以key:value的形式存储

    person_info = {'name': 'scott', 'age': 20, 'height': 180, 'hobby': ["音乐", "游戏"]}
    print(person_info)  #{'name': 'scott', 'age': 20, 'height': 180, 'hobby': ['音乐', '游戏']}
    print(type(person_info))  #<class 'dict'>
    

【2】字典的使用

person_info = {'name': 'scott', 'age': 20, 'height': 180, 'hobby': ["音乐", "游戏"]}

# 字典取值
name = person_info['name']
height = person_info['height'][1]
print(name)  # 输出结果:scott
print(height)  # 输出结果:180

student1 = {'name': '大王', 'age': 20}
student2 = {'name': '小王', 'age': 21}
dict = {'student1': student1, 'student2': student2}
# 取值
student1_name = dict['student1']['name']
student2_age = dict['student2']['age']
print(student1_name)  # 输出结果:大王
print(student2_age)  # 输出结果:21
info = {
    'name': 'Dream',
    'addr': {
        '国家': '中国',
        'info': [666, 999, {'编号': 466722, 'hobby': ['read', 'study', 'music']}]
    }
}

# 1. music在大字典里的位置
d1 = info['addr']  
print(d1)
# {'国家': '中国', 'info': [666, 999, {'编号': 466722, 'hobby': ['read', 'study', 'music']}]}

# 2. music在小字典里的位置
d2 = d1['info']  
print(d2)
# [666, 999, {'编号': 466722, 'hobby': ['read', 'study', 'music']}]

# 3. music在列表里的位置
d3 = d2[2]  
print(d3)
# {'编号': 466722, 'hobby': ['read', 'study', 'music']}

# 4. music在小字典里的位置
d4 = d3['hobby']  
print(d4)
# ['read', 'study', 'music']

# 5. music在列表里的位置
d5 = d4[2]  
print(d5)
# music

# 整合
d6 = info['addr']['info'][2]['hobby'][2]
print(d6)
# music

【六】布尔

【1】定义

  • 布尔类型(bool)只有True和False两个取值,将常用于条件判断,条件循环等

  • 布尔的命名都是以is开头

    # 定义布尔类型
    is_student = True
    is_teacher = False
    

【2】布尔的使用

#布尔进行条件判断
is_student = True
if is_student:
    print("I am a student")
else:
    print("I am not a student") #返回值为 I am a student
    
#用布尔类型比较大小
a = 3
b = 6
is_greater = a > b
print(is_greater)  # 返回值为 False

【补充】Python中的真与假

  • 在 Python 中,布尔类型的 True 表示真,False 表示假。
  • 在条件判断和逻辑运算中,通常会使用布尔值来确定程序的执行流程。

(1)假的情况(False)

  • 布尔值为 False: 显而易见,False 本身就表示假。
is_false = False
if is_false:
    print("This won't be executed.")
else:
    print("This will be executed.")
  • 数字零: 数字类型中,整数或浮点数中的零被视为假。
zero_integer = 0
zero_float = 0.0

if zero_integer or zero_float:
    print("This won't be executed.")
else:
    print("This will be executed.")
  • 空字符串: 空字符串 '' 被视为假。
empty_string = ''

if empty_string:
    print("This won't be executed.")
else:
    print("This will be executed.")
  • 空列表、空字典、空集合等: 对于容器类型,如果它们为空,被视为假。
empty_list = []
empty_dict = {}
empty_set = set()

if empty_list or empty_dict or empty_set:
    print("This won't be executed.")
else:
    print("This will be executed.")

(2)真的情况(True)

  • 布尔值为 True: True 本身表示真。
is_true = True
if is_true:
    print("This will be executed.")
else:
    print("This won't be executed.")
  • 非零数字: 除了零之外的任何整数或浮点数都被视为真。
non_zero_integer = 42
non_zero_float = 3.14

if non_zero_integer and non_zero_float:
    print("This will be executed.")
else:
    print("This won't be executed.")
  • 非空字符串: 非空字符串被视为真。
non_empty_string = 'Hello, World!'

if non_empty_string:
    print("This will be executed.")
else:
    print("This won't be executed.")
  • 非空列表、非空字典、非空集合等: 如果容器类型中包含元素,被视为真。
non_empty_list = [1, 2, 3]
non_empty_dict = {'key': 'value'}
non_empty_set = {1, 2, 3}

if non_empty_list and non_empty_dict and non_empty_set:
    print("This will be executed.")
else:
    print("This won't be executed.")

【七】元祖

【1】定义

  • 元组(tuple)是元素不能改变的的基本数据类型,与列表的区别在于元组的元素不能被修改、删除或添加
  • 通常以小括号 ( ) 定义,可以用索引拿取元祖里的元素
#元祖的定义
tuple = (1,2,'scott',5,True)
a= tuple[1]
b= tuple[-1]
print(a,b) #2 True
#元祖的语法细节
#字符串后面加逗号会变成原组,以及元组里面放一个字符串不加逗号会变成字符串
tuple = ('sdds',) 
print(tuple)  #输出 ('sdds',)
tuple = ('sdds') 
print(tuple)  #输出 sdds

【2】元祖的使用

#元祖的切片和拼接
tuple1 = tuple[2:4]
tuple2 = tuple + (999,'good')
print(tuple1)   #('scott', 5)
print(tuple2)   #(1, 2, 'scott', 5, True, 999, 'good')

#元组解包
a,b,c,d,e = tuple
print(a)  #1
print(b)  #2
print(c)  #scott
print(d)  #5
print(e)  #True

#元祖的不可变性
# 尝试修改元组的元素(会报错)
tuple[0] = 20  # TypeError: 'tuple' object does not support item assignment
# 尝试删除元组的元素(会报错)
del tuple[1]  # TypeError: 'tuple' object doesn't support item deletion
# 尝试添加元素到元组(会报错)
tuple.append('new_element')  # AttributeError: 'tuple' object has no attribute 'append'

【八】集合

  • 集合(set)是一种无序、不重复的数据类型,用于存储多个独立的元素
  • 通常以 { } 定义,可通过set()构建函数
#用大括号定义
a = {1,2,3,4,5}
#用set函数定义
b= set([6,7,8,9,10])
# 添加元素
a.add(6)
print(a)  #{1, 2, 3, 4, 5, 6}
# 删除元素
a.remove(3)
print(a)  #{1, 2, 4, 5, 6}
# 成员测试
is_member = 2 in b
print(is_member)  #返回值为False
#也实现数学中集合的交集并集
a1 = a.union(b)
print(a1)  #{1, 2, 4, 5, 6, 7, 8, 9, 10}
#集合具有不重复性,会自动去除重复的元素
c = {1,3,3,4,4,4,55,561,664}
print(c)  #{1, 561, 3, 4, 55, 664}
#集合不只有一种数据类型时,每一次运行的元素顺序都不同
d = {1,3,3,4,4,4,55,561,664,'abc'}
print(d)
#{1, 561, 3, 4, 55, 664, 'abc'}
#{1, 561, 3, 4, 55, 'abc', 664}
#{1, 'abc', 3, 4, 561, 55, 664}
posted @   Ligo6  阅读(393)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示