pthon基础

python基础知识

1. 字符串

1.字符串的输出

如果打印的字符串包含的有 变量的值, 需要在字符串中使用 格式化操作符.

name = "bob"
age = 18

print("姓名是%s, 年龄是%d" % (name, age))

# f-strings
f_string1 = f"姓名是{name}, 年龄是{age}"
print(f_string1)

f_string2 = f"3 + 5 = {3 + 5}"
print(f_string2)

a = 10
b = 20
f_string3 = f"a + b 的和为:{a + b}"
print(f_string3)

'''
结果:
姓名是爽儿, 年龄是18
姓名是爽儿, 年龄是18
3 + 5 = 8
a + b 的和为:30
'''

2.字符串的索引

s = "hello python"

# 根据索引查找元素,格式为: 字符串名[索引]
# 得到索引为0的元素
e = s[0]
print(e)
print(type(e))

print(s[7])

# 得到字符串的长度:len(字符串)
# length = len(s)
# print(length)

# 最后一个元素的索引是 长度-1: length-1
# print(s[length-1])
print(s[len(s)-1])
'''
结果:
h
<class 'str'>
y
n
'''

3.字符串长度 len(str)、字符串的遍历

#for 循环
s = "hello python"
for c in s:
    print(c, end="") #末尾不加空格
    print("", end ="\n")#换行
# 得到字符串的长度:len(字符串)
# length = len(s)
# print(length)
i=0
for i in range(len(s)):
    print(s[i],end ="")
    print("", end ="\n")#换行

4. for-else语句

"""
for...else...格式:
    for 变量 in 容器:
        重复执行的代码块
    else:
         如果for循环不是通过break结束的时候,一定会执行的代码块

需求:
    判断字符串中是否包含m.
"""

s = "hello pymthon"

for c in s:
    if c == "m":
        print("字符串中包含 m")
        break
else:
    print("字符串中没有包含 m")

5.字符串切片、步长的基本使用

"""
字符串切片的基本使用
    就是截取字符串

    切片的格式:
        字符串名[开始索引: 结束索引]

        从 开始索引 对应的元素截取, 一直截取到 结束索引 对应的元素.
        包含 开始索引 对应的元素, 不包含 结束索引 对应的元素
"""
s = 'hello python'

# 从索引为1的元素 开始一直截取到索引为10的元素 顾前不顾后
print(s[1:10]) # ello pyth

#如果是截取到最后一个元素,结束的索引可以不写
print(s[6:]) #python

#如果是从第一个索引开始进行截取,则第一个索引可以不写
print(s[0:10]) #hello pyth
print(s[:10])  #hello pyth

#从头截取到末尾
print(s[:]) #hello python

#索引可以为负数 ,倒数第一个元素的索引为-1,倒数第二个元素的索引为-2
print(s[-10:-1]) #llo pytho
print(s[3:-2])  #lo pyth

"""
字符串切片步长的格式:
    字符串名[开始索引: 结束索引: 步长]

    假如步长是n.
    从开始索引对应的元素 截取,一直截取到 结束索引 对应的元素.
    先 截取出  开始索引对应的元素, 然后每次都是向后数n个元素,第n个元素是谁就把谁截出来.
    最后按照截取的先后顺序,组成一个字符串. 这个字符串 就是截取的结果.
"""
sb= "Hello World"
#步上设置为2
print(sb[2: 10: 2]) #loWr
#默认的步长是1
print(sb[2: 10: 1]) #llo Worl

# 步长可以为 负数,表示倒序截取
print(sb[9: 2: -2])  #lo l
print(sb[-3: 2: -2]) #rWo

#字符串的翻转 逆序
# s[::-1]
print(sb[:: -1]) #dlroW olleH

6.字符串常见的方法:查找、分割、统计、判断(大小写,数字字母、开头结尾)

s1 = "hello python"

#1.查找 o 在s1种 第一次 出现的位置:s1.find(str1)
print(s1.find("aa"))# -1,没有则返回-1
print(s1.find("o",6,11)) # 从下标是6的开始:10
print(s1.find("o")) # 4
print(s1.rfind("o")) #  10 找到最后一个o的下标

print(s1.index("o"))# 找到o的下标   如果找不到会抛异常ValueError: substring not found

#统计O 出现的次数
print(s1.count("o")) # 2
print(s1.count("o",6,12)) # 1

#分割的方法
s2 = 'hello python android'
# 分割出来的结果是一个列表,把分割出来的几部分作为元素放到列表中
list1 = s2.split(" ")
print(list1) #['hello', 'python', 'android']
print(type(list1))  #<class 'list'>

# 这个方法只能分割出3部分,:左边部分,自己,右边部分
list2=s2.partition(" ")
print(list2) #('hello', ' ', 'python android')
print(type(list2)) # <class 'tuple'>


#1 判断字符串是否都是由字母组成的:isalpha()
s1 = "hellopython" #True
print(s1.isalpha())

#2 判断字符串是否都是由数字组成的:
s2= "1234567"
print(s2.isdigit()) #True
print(s2.isdecimal() )#True

# 3 判断字符串是否都是大写 或者小写
s3 = "HELLO34"
S4 = "hello<>45"
print(s3.isupper()) #True
print(S4.islower()) #True

#判断字符串是否以一个字符开头或者结尾
s5 = "hellwo world andrioid"
print(s5.startswith("he"))  #True
print(s5.endswith("id")) #True

7.字符串常见的方法:替换、大小写、去空格、just、join

# 1. 替换的方法:s1.replace(oldstr,newstr)

s1 = "helloapythoan"
result = s1.replace("oa","www",1)#1表示只换一个
print(result) #hellwwwpythoan
result = s1.replace("oa","www",2)#2表示只换两个
print(result) #hellwwwpythwwwn
print(s1)#helloapythoan

#2 大小写转换的方法:
s2="hello435PYTHON"
print(s2.upper()) #HELLO435PYTHON
print(s2.lower()) #hello435python

# 3.去空格  strip():删除前后的空格
s3 =" hello python    "
print("a" +s3.strip()+"b") #ahello pythonb
print(s3.replace(" ","")) #hellopython

# 4. 对齐的方法  不够的用空格补齐
s4 = "hello"
print(s4)
print(s4.ljust(15))#hello
print(s4.rjust(15)) #          hello
print(s4.center(16))#     hello

# join
s5 = "hello"
s6 = "python"
#使用s5链接s6中的而元素 得到一个新的字符串 每个字符之间加入一个s6
result =s5.join(s6)
print(result)# phelloyhellothellohhelloohellon

2.列表(list)、元组(tuple)、字典(dict)、set

2.1 列表(list)

2.1.1.列表(list)的定义及使用
"""
列表:
    也是一个容器,可以存储多个元素,元素可以是任何类型的.

定义格式:
    # 非空
    列表名 = [元素1, 元素2, ...]
    # 空列表
    列表名 = []
"""
name_list =['boob','xiaoyun','无心']
print(name_list) #['boob', 'xiaoyun', '无心']
print(type(name_list)) #list

list1=['boob','xiaoyun','无心',3.14,2,False]
print(list1)# ['boob', 'xiaoyun', '无心', 3.14, 2, False]

#定义空列表
list2 =[]
print(list2)  #[]
2.1.2 列表(list)的增删查改操作 append、insert、extend、remove、pop、clear
name_list =['boob','xiaoyun','无心']

#1.向列表中加入一个元素
# append(数据) :在 列表的最后添加元素
name_list.append("许晴")
print(name_list) #['boob', 'xiaoyun', '无心', '许晴']

#在指定的索引处插入一个元素
name_list.insert(2,"岳绮罗") #['boob', 'xiaoyun', '岳绮罗', '无心', '许晴']
print(name_list)

#继承:把另外一个容器中的元素加入到自己的容器中
list1=[10,20]
name_list.extend(list1)
print(name_list) #['boob', 'xiaoyun', '岳绮罗', '无心', '许晴', 10, 20]

#字符串是一个一个字符添加的
name_list.extend("hello")
print(name_list) #['boob', 'xiaoyun', '岳绮罗', '无心', '许晴', 10, 20, 'h', 'e', 'l', 'l', 'o']

#修改的方法
list1 = [10,3.14,'hello',True]
print(list1[0]) #10
print(list1[2])#hello

#修改指定位置的元素:列表名[索引] = 新值
list1[1]='法师'
print(list1)#  [10, '法师', 'hello', True]

#删除元素
#删除指定的的元素
list1.remove("法师")
print(list1) #[10, 'hello', True]

# 是你出指定的索引处的元素,返回被删除的元素
result= list1.pop(1)
print(result) #hello
print(list1) #[10, True]

#pop 方法中没有写索引 默认删除最后一个元素
list1.pop()
print(list1) #[10]

#clear 把列表清空
list1=[10, 'vivi', 'hello', True]
list1.clear()
print(list1) #[]
2.1.2 列表 遍历 和 排序
list1 = ["爽儿", "千寻", "vivi", "美娜"]

# 方式一:while循环语句
# 作为元素的索引
i = 0
# while循环4次: len(列表名)
while i < len(list1):
    # 根据索引得到元素: 列表名[索引]
    print(list1[i])
    # 让索引加1
    i += 1

print("-----------------------")

# 方式二: for循环遍历
for e in list1:
    print(e)
"""
排序:
    可以按照升序/降序排序.

"""
list1 = [10, 7, 5, 12, 9]
# 按照有小到大的升序排序
# 默认按照升序排序
list1.sort()
print(list1) # [5, 7, 9, 10, 12]

# 倒序排序: 由大到小的排序,降序
list1.sort(reverse=True)
print(list1)

list2 = ["Python", "中国", "Android", "abc", "JavaEE", "C++", "Php"]
list2.sort()
print(list2)

print(ord("中"))
2.1.3 列表推导式
"""
列表推导式的格式:
   列表名 = [x for x in range()函数]
   每次循环都得到一个数字x,然后把x作为元素添加到列表中
在列表推导式中使用 if语句:
   列表名 = [ x for x in range()函数 if  条件]
"""
lis1 = [x for x in range(1,5)]
print(lis1) #[1, 2, 3, 4]

list2 = [x+2 for x in range(1,5)]
print(list2) # [3, 4, 5, 6]

list3 = [x for x in range(20) if x%2 ==0]
print(list3)#[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

a =[x for x in range(1,101)]
print(list(range(0,len(a),3))) #[0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, ...
print(range(0,len(a),3)) #range(0, 100, 3)

a[0:3]
a[3:6]

2.2.元组(tuple)的定义和使用

"""
元组:
    也是一个容器,可以存储多个元素,每个元素可以是任何类型的.
    元组是一个不可修改的列表.不能用于 增删改操作,只能用于查询.

定义格式:
    # 定义非空元组
    元组名 = (元素1, 元素2, ...)
    # 定义空元组
    元组名 = ()
    # 定义只有一个元素的元组
    元组名 = (元素1,)

 什么时候使用元组存储一组数据?
    当那一组数据不允许修改时,需要使用元组存储.
"""
tuple1 = ('bobo','小云','娜美')
print(tuple1) #('bobo', '小云', '娜美')
print(type(tuple1))#<class 'tuple'>

# 根据索引得到元组中的元素: 元组名[索引]
print(tuple1[0])
print(tuple1[1])
print(tuple1[2])

#定义只有一个元素的元组
tuple2 =(10,)
print(tuple2)
print(type(tuple2))

2.3 字典(dict)的使用

2.3.1 字典的定义
"""
字典的定义格式
    字典名={key1:value,key2:value2...}
    字典名={}
"""
dict1 = {"bob": 25,"bo1": "bobo"}
print((dict1))#{'bob': 25, 'bo1': 'bobo'}
print(type(dict1))#<class 'dict'>
2.3.2 字典的增删改查的操作
dict1= {"邓超": "孙俪","张杰": "谢娜","吴京": "谢楠"}

# 1.添加键值对的格式: 字典名[新的key]=值
dict1["李晨"] = "范冰冰"
print(dict1)  #{'邓超': '孙俪', '张杰': '谢娜', '吴京': '谢楠', '李晨': '范冰冰'}

#  修改键值对中的value :字典名[已经存在的key]=新的值   字典里只能修改value,不能修改key
dict1["张杰"] = "热巴"
print(dict1) #{'邓超': '孙俪', '张杰': '热巴', '吴京': '谢楠', '李晨': '范冰冰'}

#3.删除键值对,通过key删除键值对
dict1.pop("张杰")
print(dict1) #{'邓超': '孙俪', '吴京': '谢楠', '李晨': '范冰冰'}

# 删除最后一个键值对
dict1.popitem()
print(dict1) #{'邓超': '孙俪', '吴京': '谢楠'}

# 清空键值对
dict1.clear()
print(dict1) #{}

#4 查找value,通过key查找:字典名[key]
# 如果key不存在 就会报错
dict2 ={"阿杰": "爽儿","阿奇": "千寻"}
print(dict2["阿杰"]) #爽儿
print(dict2["阿奇"]) #千寻
#print(dict2["小王"])  #KeyError: '小王'

# 可以通过 字典名.get(key) 得到value,如果key不存在就会得到None

print(dict2.get("阿杰")) #爽儿
print(dict2.get("小王")) #None
2.3.3 字典的遍历
dict1 = {"name": "Bob","age": 20,"gender": "男","height": 180}

#方式1:
#1.先得到 所有的key组成的列表
key_list=dict1.keys()
#print(key_list) #dict_keys(['name', 'age', 'gender', 'height'])
#print(type(key_list)) # <class 'dict_keys'>
#2.遍历列表,得到key
for key in key_list:
    # 3.在循环中通过key得到value
    value=dict1.get(key)
    #print("%s=%s" % (key,value))
    print(f"{key}={value}")
print("--------------")

#方式二:
#1.先得到所有的键值对组成的列表
item_list=dict1.items()
print(item_list) #dict_items([('name', 'Bob'), ('age', 20), ('gender', '男'), ('height', 180)])
print(type(item_list))# <class 'dict_items'>

#2.遍历列表,遍历 去除键值对
for key_value in item_list:
    #key_value 是一个元组 ,比如:('name','Bob'),第一个是元素key,第二个元素是value
    #3.从键值对中取出key和value
    key=key_value[0]
    value=key_value[1]
    print(f"{key}={value}")
#直接取出key,value
for key,value in item_list:
    print(f"{key}={value}")
2.3.4 字典的应用
"""
需求:
   向系统中录入多个名片,并保存
分析步骤:
  1.定义一个card_list,用来保存所有的名片
  2.写一个无限循环
  3.在循环中 提示输入5个名片的信息
  4。在循环中使用字典把5对信息存存储,表示创建了一个名片
  5.在 循环中,把字典添加到列表中
"""
#1.定义一个列表card_list ,用来存储所有的名片
card_list=[]
while True:
    is_input = input("是否需要录入名片:")
    if is_input == "yes":
        company = input("请录入公司的名称:")
        name = input("请录入姓名")
        title = input("请录入职位")
        tel = input("请录入电话号码")
        email = input("请录入邮箱")
        address = input("请录入公司的地址")
        card ={"company": company, "name": name, "title": title, "tel": tel, "email": email, "address": address}
        card_list.append(card)
        print(card_list)
    else:
      break


#显示
for card in card_list:
    print("-" * 50)
    company = card.get("company")
    name = card.get("name")
    title = card.get("title")
    tel = card.get("tel")
    email = card.get("email")
    address = card.get("address")

    print(company)
    print()
    print(name.rjust(10) + "   " +  title)
    print()
    print("电话:" + tel)
    print("Email:" + email)
    print("公司地址:" +address)
    print("_" * 50)

2.4 set

"""
set集合
  也是一个容器,可以存储多个元素,可以是任何类型的
  没有索引:
  特点:
     set中不能存储重复的元素,自动去重复,重复的元素只留下一个
  定义格式:
     set 集合名 = { 元素1,元素2,.....}
     #定义空的set集合
    set集合名 = set()
"""
set1 = {10, "hello", True}
print(set1) #{True,10,'hello' }
print(type(set1)) #<class 'set'>

#自动去重
set2 = {10,"hello",True,10,"hello"}
print(set2)#{True, 10, 'hello'}


set2.update("hello")
print(set2) #{True, 'l', 'hello', 10, 'o', 'e', 'h'} 把hello拆分 放进去

set4 = set("hello")
print(set4)  #{'h', 'e', 'o', 'l'}

for s in set4:
    print(s)


 """
 set-list-tuple之间的转换
 数据类型转换的格式:
    目标数据类型(数据)
"""

set1 = {10, 20, 30}
list2 = list(set1)
print(list2) #[10, 20, 30]

set2 = set(list2)
print(set2) #{10, 20, 30}

3.公共方法

3.1运算符

运算符 Python 表达式 结果 描述 支持的数据类型
+ [1, 2] + [3, 4] [1, 2, 3, 4] 合并 字符串、列表、元组
* ['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] 复制 字符串、列表、元组
in 3 in (1, 2, 3) True 元素是否存在 字符串、列表、元组、字典
not in 4 not in (1, 2, 3) True 元素是否不存在 字符串、列表、元组、字典

3.2 python内置的函数

序号 方法 描述
1 cmp(item1, item2) 比较两个值
2 len(item) 计算容器中元素个数
3 max(item) 返回容器中元素最大值
4 min(item) 返回容器中元素最小值
5 del(item) 删除变量

4.函数

4.1函数定义与使用

"""
1.函数:
  具有独立功能的代码块
好处:
  1.让代码的结构变的简短,结构更加的清晰
  2.提高代码的重复使用率,避免代码重复
  3.把功能的设计和调用进行分离

2.函数的定义格式:
   def 函数名:
       函数体
   这里的函数体就是一个代码块,可以是一行或者多行代码

   函数只有被调用了,里面的代码才会被执行
3.函数的调用格式:
   函数名()

函数的5个细节(重点):
    1.保存函数的返回值
    2.直接打印函数的返回值
    3.函数的返回值作为参数传递给另一个函数
    4.函数中写多个return语句
    5.同一个文件中函数不能重名
"""


def print_hello_python():
    i = 1
    while i < 10:
        print("hello python")
        i += 1


print_hello_python()


def sum1(a, b):
    s = a + b
    print(s)


sum1(8, 6)
sum1(8, 20)

4.2全局变量和局部变量

"""
全局变量:
    在函数外面定义的变量
特点:
   可以全局使用,函数内想要修改必须用global
局部变量:
    在函数中定义的变量.包括形参.
特点:
    只能在函数内部使用,不能在函数外面使用.

"""

a = 20 #全局变量
b = 20#全局变量
def func1(num1, num2):
    print(num1 + num2)
    # a就是局部变量
    a = 10
    global  b
    global  c #函数内部定义全局共享变量
    b=30
    c=60
    print(a)


func1(100, 200)
print(a)#20
print(b) #30
print(c) #60

4.3函数可以返回多个返回值

"""
函数返回值可以返回多个,元组

"""

def func1(num1, num2):
     s = num1 * num2
     v = num1 + num2
     m = max(num1,num2)
     return  s,v,m

result =func1(3,9)
print(result) #(27, 12, 9)
print(type(result)) #<class 'tuple'>

4.4 匿名函数 lambda

# lambda 形参1,形参2.....: 单行表达式 或者 调用其他函数的代码
my_add = lambda a, b: a + b
sum1 = my_add(10, 20)
print(sum1)  # 30


def my_function(func):
    a = 100
    b = 200
    # 把func 当作函数来调用
    result = func(a, b)
    print('result:', result)


my_function(lambda a, b: a + b) #30
my_function(lambda a, b: a - b) #-100
my_function(lambda a, b: a * b)# 20000

4.5 递归函数

"""
递归求1-5的和
"""
def sum1(number):
    if number == 1:
        return 1
    else:
        return number + sum1(number-1)



print(sum1(5)) : 15

练习题:输入一段字符串,统计大写字母 小写字母 数字的个数

str1 = input("请录入一个字符串:")
upper_count = 0
lower_count = 0
num_count = 0
other_count= 0

for c in str1:
    if c.isupper():
        upper_count += 1
    elif c.islower():
        lower_count += 1
    elif c.isdigit():
        num_count += 1
    else:
        other_count += 1

print(upper_count, lower_count, num_count, other_count)

5 参数

5.1 默认参数

"""
默认参数:
  在定义函数时,给形参指定了默认的值,这个参数叫做默认参数(缺省参数)
特点:
   在调用函数时,可以给它传值也可以不给它传值
   如果传了,在执行函数时就会使用传递过去的值,如果没传就是使用默认的值
"""


def sum1(a, b, c=60):
    print(a + b + c)


sum1(10, 20, 50)  #80

# 由于给形参c 指定了默认的值,调用可以不给它传值
sum1(10, 20) #90

5.2 关键字参数

"""
关键字参数:
   在调用函数时,根据形参的名称传递的参数叫做关键字参数
特点:
  时根据形参的名称给形参传值的
关键字参数只能写在实参列表的最后
"""

def sum2(a, b, c):
    print(a)
    print(b)
    print(c)
    print(a+b+c)

# 这里的 b=20, a=10,c =30 都是关键字参数
sum2(b=20, a=10, c=30)
sum(0,c=10,b=30)
sum2(0,b=30,c=20)

5.3 可变参数

"""
可变参数:
    在形参前面加了一个 *,这个参数就叫做可变参数(不定长参数)
    表示0个或者任意多个形参
特点:
  1. 前面 由一个 *
  2. 表示 0个或者任意多个形参
好处:
  1.可以扩展函数的功能,更加的通用
"""

# 如果函数的形参时一个可变的参数 ,当调用函数的时候,python解释器会自动把传递的实参打包成一个元组,然后把元组传递个可变参数
def print_params(* args):
    print(* args) #10 20
    print(args) #(10,20)
    print(type(args))#<class 'tuple'>
    for e in args:
        print(e)

print_params(10,20)

"""
关键字参数的 可变参数
  在参数前面加 **,这个参数叫做 关键字参数的 可变参数

"""
# python 解释器会自动把 关键字参数打包成一个 字典,然后把字典传递给带**的参数
def print_ars(a, ** kargs):
    print(f"arg-{kargs}") #arg-{'m': 10, 'n': 20}
    print(type(kargs)) #<class 'dict'>
print_ars(10,m=10,n=20)

#参数的混合使用
def sum_nums_3(a, *args, b=22, c=33, **kwargs):
    print(a)
    print(b)
    print(c)
    print(args)
    print(kwargs)


sum_nums_3(100, 200, 300, 400, 500, 600, 700, b=1, c=2, mm=800,

5.3 自动组包和解包

#自动组包
tuple1 = 10,20
print(tuple1)  #(10, 20)
print(type(tuple1)) #<class 'tuple'>

#自动解包
#要求左边的变量的个数与元组中的元素的个数相同
a,b = (10,20)
print(a) #10
print(b)#20

#对列表的的自动解包
c,d = [10,20]
print(c)#10
print(d)#20

#利用自动解包交换两个数的值
a,b = b,a
print(a)#20
print(b )#10

5.4 小数字和短字符串的加载存储

"""
小数字:
   -5-256
短字符串:
   长度不超过20的字符串
在python解释器一启动的 时候,就会把小数字和短字符串放到缓冲区(小数字对象池和短字符串对象池)
"""
a = 10
b = 10

#获得数的地址: 调用id(数据)
print(id(10)) #140709290104768
print(id(a)) #140709290104768
print(id(b)) #140709290104768

#大数字时在第一次使用的时候才被缓存的,以后在用到这个数字时就是用刚才缓存的那个数字
c = 10000
d = 10000
print(id(10000))
print(id(c))
print(id(d))

print("- " * 50)

#短字符串对象池
s = "hello"
s2 = "hello"
print(id("hello")) #2379121813168
print(id(s)) #2379121813168
print(id(s2)) #2379121813168

s3="hellohellohellohellohellohellohellohellohellohello";
s4="hellohellohellohellohellohellohellohellohellohello";
print(id("hellohellohellohellohellohellohellohellohellohello"))
print(id(s3))
print(id(s4))

5.5 不可变和可变数据类型

"""
不可变类型:
   如果改变了该数据的值,地址也发生了变化,这中类型的数据时不可变类型的数据  
   常见的不可变数据类型
     int str  tuple  float bool
可变类型:
   如果改变了该数据的值,地址不改变,那么这就是可变数据类型
   常见的可变数据类型:
     list  dict set
"""
a =10
print(id(a)) #140709290104768
a= 20
print(id(a)) #140709290105088



str1 = "hello"
print(id(str1)) #2562099570352
str1 = "python"
print(id(str1)) #2562099900912


print(" -"* 50)
lsit1 = [10,20]
print(id(lsit1)) #2427067235200
lsit1.append(50)
print(id(lsit1))#2427067235200


print(" -"* 50)
dict1 = {20: 20,30: 30}
print(id(dict1)) #2427068481408
dict1["bob"] = "boy"
print(dict1) # {20: 20, 30: 30, 'bob': 'boy'}
print(id(dict1))#2427068481408

5.6 += 和=+的区别

"""
a += 1
a = a+1

这两种写法对应不可变的数据时 时没有区别的
"""
a = 10
print(id(a))#140709290104768
a += 1
print(a) #11
print(id(a))#140709290104800


print("- "*50)

list1 = [10,20]
print(id(list1)) #1714902399872

# += 只是把第二个列表中的元素放到第一个列表,第一个列表的地址不变
list1 += [30,40]
print(list1)#[10, 20, 30, 40]
print(id(list1))#1714902399872

#= + 是把两个列表中的元素放到第三个列表,产生了 第三个列表 list1的地址这个时候变了

list1 =list1 +[30,40]
print(list1)#[10, 20, 30, 40, 30, 40]
print(id(list1))#1714904036800

6. 文件操作

6.1 文件操作模式

访问模式 说明
mode='r' 以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。
mode='w' 打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
mode='a' 打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
mode='rb' 以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。这是默认模式。
mode='wb' 以二进制格式打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
mode='ab' 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
mode='r+' 打开一个文件用于读写。文件指针将会放在文件的开头。
mode='w+' 打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
mode='a+' 打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。
mode='rb+' 以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。
mode='wb+' 以二进制格式打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
mode='ab+' 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。
posted @ 2022-02-07 16:30  bobpeng  阅读(66)  评论(0)    收藏  举报