python基础

**python基础 **

目录

1. python的分类


2. 运行第一个python文件:

python3x :python 文件路径 回车
python2x :python2 文件路径 回车
python2 python3区别:
python2默认ASCII码,中文显示乱码,解决方法:(#_*_encoding:utf-8_*_)

python3默认编码utf-8

3. 变量

  • 变量:就是将一些运算的中间结果暂存到内存中,以便后续代码调用。
  • 变量由数字、字母、下划线任意组合,不能以数字开头。
  • 不能是python中的关键字。
    ['and', 'as', 'assert', 'break', 'class', 'continue','def', 'del', 'elif', 'else', 'except', 'exec','finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']
  • 变量具有可描述性。
  • 不能是中文。
age1 = 12
age2 = age1
age3 = age2
age2 = 100
print(age1, age2, age3) # 12,100,12 

4. 常量

一直不变的量,如圆周率Π

5.注释

  • 方便自己方便他人理解代码。
    • 单行注释:#
    • 多行注释:'''被注释的内容'''  """被注释的内容"""

6.基础数据类型初始

数字:int  (+、-、*、\、%取余) (不可变数据类型)

  • ps:type() print(100,type(100))

  • 字符串转化成数字:int(str)。条件:str必须是数字组成的。

  • 数字转换成字符串:str(int)

  • i = 1
    print(i.bit_length()) #转换成二进制最少的位数
    
    type:判断数据的类型
    print(100,type(100)) # 100 <class 'int'>
    

字符串:str(不可变数据类型)

  • python中用引号引起来的都是字符串。尽量用双引号。

  • 字符串拼接,+

  • 字符串打印多次 *
    print('坚强'*8) # 坚强坚强坚强坚强坚强坚强坚强坚强

  • 索引与切片(下标从0开始,顾头不顾尾)

  •    s = 'AbgjHYUIO90ER'
       print(s[0]) # A
       print(s[0:5]) # AbgjH
       print(s[0:]) # AbgjHYUIO90ER
       print(s[-1:]) # R
       print(s[-2:]) # ER
       print(s[4::-1]) # HjgbA
       print(s[4:0:-1]) # Hjgb
       print(s[-1::-1]) # RE09OIUYHjgbA
       print(s[::-1]) # RE09OIUYHjgbA
       #常用方法
       print(s.startswith('A')) # 判断是否以A开头,存在返回True,不存在返回False
       print(s.startswith('A',2,5)) # 可切片存在返回True,不存在返回False
       print(s.endswith('R')) # 判断是否以R结尾,存在返回True,不存在返回False
       print(s.endswith('R',3,4)) # 可切片,存在返回True,不存在返回False
       print(s.find('A')) 
       print(s.find('A',1,8)) #存在返回索引值 不存在返回-1,可切片查找
       print(s.index('b'))
       print(s.index('b',1,7)) #存在返回索引值 不存在报错,可切片查找
       print(s.strip()) #去除字符前后的空格
       print(s.lstrip()) #去除字符左边的空格
       print(s.rstrip()) # 去除字符右边的空格
       print(s.count('bx')) # 统计字符的分数,可切片统计
       print(s.split()) #1、若sep未指定或无,则有空白字符串是分隔符,空字符串是从结果中移除。2、返回值为列表
       print(s.upper()) #全大写 lower()小写
       print(s.swapcase()) # 大小写翻转 aBGJhyuio90er
       print(s.title()) # 每个隔开的单词(数字也是特殊字符)首字母大写
       print(s.center(50,'^')) # 字符串居中
    

布尔值: bool (True or False)(不可变数据类型)

列表: list (可变数据类型)

  • 列表中可以存储任何数据类型
  • 索引下标从0开始,可切片(与字符串切片方法一致)
  •   li = ['jim',[3,2,1],'bob','tom','egon']
          print(li[0:4])
            
        #增加
        li.append('小强') # append() 增到到列表的end
        print(li) #['jim', [3, 2, 1], 'bob', 'tom', 'egon', '小强']
        
        li.insert(1,'阿花') #可指定位置增加
        print(li) #['jim', '阿花', [3, 2, 1], 'bob', 'tom', 'egon', '小强']   
        li.extend([1,2,'5']) #迭代添加
        print(li) #['jim', [3, 2, 1], 'bob', 'tom', 'egon', 1, 2, '5']
              
        #删除
        res = li.pop() #删除并返回索引处的值(最后一个默认值)
        print(res) #egon
        
        li.remove('jim') #删除指定的元素。如果元素不存在,则引发ValueError
        li.clear() #清空
        del li #删除所有的元素
        del li[0:3] #可切片删除 
        print(li) #['jim', [3, 2, 1], 'egon']
        
        #改
        li[0] = '花花'
        li[0:3] = '花花草草不要踩踏' #迭代添加到列表中
        #查
        print(li[0:])
        
        for i in li:
        print(i)
        
        #公共方法
        l = len(li) #计算列表的元素长度
        l = li.count('bob') #计算元素出现的次数
        l= li.index('jim')
        l= li.index('jim',0,7)#返回匹配的第一个值索引。如果值不存在,则引发ValueError。
        li.sort() #排序
        li.sort(reverse=False) # 逆序
        li.reverse() #将元素反向存放
            
        #列表的嵌套
        li1 = ['ajian', '武藤兰', '海强', ['jim', 'Tom', 'bob', 89], 23]
        print(li[1][1])
        li1[0] = li1[0].capitalize()
        li1[2] = li1[2].replace('强', '日天')
        li1[3][0] = li1[3][0].upper()
        print(li1)
        
        #列表也可相加 
        print(li + li1) #['egon', 'tom', 'bob', [3, 2, 1], 'jim', 'ajian', '武藤兰', '海强', ['jim', 'Tom', 'bob', 89], 23]
        
        #列表相乘
        print(li * 3) # ['egon', 'tom', 'bob', [3, 2, 1], 'jim', 'egon', 'tom', 'bob', [3, 2, 1], 'jim', 'egon', 'tom', 'bob', [3, 2, 1], 'jim']
      
      l = ['ajian', '武藤兰', '海强', ['jim', 'alix', 'bob', 89], 23]
      # 根据值取
      for i in l:
           if type(i) == list:
                 for k in i:
                       print(k)
                else:
                    print(i)
      #根据索引取
      for i in range(0,len(l)):
           if type(l[i]) == list:
               for k in l[i]:
                  print(k)
            else:
                 print(l[i])
                    
      #join 拼接 返回字符串   字符串转换成列表split
        s = ['ajian', 'haiqiang']
        s1 = '>'.join(s)
        print(s1) # list>str
        #range 生成一个列表
        for i in range(0,200):
             if i == 99:
                 print('>'.join(s))
        else:
            print(i,end='')
        
        for i in range(10,-1,-2):
            print(i)
        # 倒着取,必须指定
        for i in range(10,-2):
            print(i)
    

字典 dict (可变数据类型)

  • key 必须是不可变数据类型

  • value 任意数据类型

  • 无序的,3.6之后按照第一次存储的数据排序

  •  dic = {
        'name': ['ajian', 'jim', 'bob'],
        'wyx': [{'num': 2000, 'avg_age': 18}],
        True: 1,
        (1, 2, 3): 'yoyo',
        'bike': 'jieant',
        1: [1, 2, 3, 66]
    }
    print(dic)
    
    #增加 如果存在,则覆盖,不存在,则添加
    dic = {'name':'ajian','age':28,'sex':'male'}
    dic['age'] = 22
    dic['weight']=99
    print(dic) #{'name': 'ajian', 'age': 22, 'sex': 'male', 'weight': 99}
    #存在不覆盖,没有添加
    dic.setdefault('k1','kk')
    dic.setdefault('name','二狗')
    print(dic) #{'name': 'ajian', 'age': 28, 'sex': 'male', 'k1': 'kk'}
    
    #删除
    dic.pop('name') 
    dic.pop('name',None) # 返回value,可设置返回值。如果‘name’不存在,返回None
    
    dic.popitem() #随机删除,返回值为删除的键值对
    
    del dic['name']
    del dic
    dic.clear()
    
    #修改
    dic['name'] = '葫芦娃'
    
    dic1 = {'name':'ajian','age':28,'sex':'male'}
    dic2 = {'name':'haiqiang','age':99,'weight':'120'}
    dic2.update(dic1) #相同的键不覆盖,没有则添加
    print(dic2) #{'name': 'ajian', 'age': 28, 'weight': '120', 'sex': 'male'}
    
    #查
    print(dic1.keys(),type(dic1.keys())) #按照键查询
    print(dic1.values()) #按照值查询
    print(dic1.items(),type(dic1.items())) #dict_items([('name', 'ajian'), ('age', 28), ('sex', 'male')])
    print(dic1.get('name1','没有这个键')) #存在返回key,不存在返回None。可定义返回值。
    for i in dic1: #默认打印 key
        print(i)
        
    for i in dic1.values(): #打印value
        print(i)
        
    for i in dic1.items(): #打印键值对元组 ('name', 'ajian')
        print(i)
        
    for k, v in dic1.items(): #以name : ajian样式打印
        print(k, ':', v)
    
        
    a,b = 1,2
    print(a,b) # a = 1,b = 2
    
    #将a b 值互换
    a = 1
    b = 2
    a, b = b, a
    print(a,b)
    

元组 tuple(可变数据类型)

  • 只读列表,可循环查询,可切片

  • 儿子不能改,孙子可能可以更改

  • tu = (1, 2, 3, 4, 'bob', [2, 3, 4, 'haiqiang'], 'jim')
    print(tu[3]) #4
    print(tu[0:3]) #(1, 2, 3, 4)
    for i  in tu:
        print(i)
    tu[5][3] = tu[5][3].capitalize()
    print(tu) #(1, 2, 3, 4, 'bob', [2, 3, 4, 'Haiqiang'], 'jim')
    tu[5].append('sb')
    print(tu) #(1, 2, 3, 4, 'bob', [2, 3, 4, 'Haiqiang', 'sb'], 'jim')
    
    tu.index('bob') #找到第一个元素出现的索引值,不存在报错
    tu.count('bob') #获取元素出现的次数
    len(tu) #元组的长度
    

集合 set (可变数据类型)

  • 元素必须是不可变的数据类型,集合无序,不重复
  • set1 = set({1, 2, 'barry'})
    set2 = {1, 2, 'barry'}
    set3 = set({1, 2, 4, 'bool', '999', (1, 'hah')})
    print(set1, set2, set3)
    
    # 增 add update
    set3.add('难受')
    set3.update('难受1') #迭代添加
    print(set3)
    
    # 删 pop 随机删除
    set3.pop()
    print(set3.pop())
    print(set3)
    
    # 按照元素删除
    set3.remove('bool')
    print(set3)
    
    set3.clear()
    print(set3) #set()
    
    del set3
    print(set3)
    
    # 查
    for i in set3:
         print(i)
    
    # 求交集
    set1 = {1, 2, 3, 4, 5}
    set2 = {4, 5, 6, 7, 9}
    set4 = set1 & set2
    print(set4)
    print(set1.intersection(set2))
    
    # 求并集
    set1 = {1, 2, 3, 4, 5}
    set2 = {4, 5, 6, 7, 9}
    print(set1|set2)
    print(set2.union(set1))
    
    #反交集
    set1 = {1, 2, 3, 4, 5}
    set2 = {4, 5, 6, 7, 9}
    print(set1^set2) #{1, 2, 3, 6, 7, 9}
    print(set1.symmetric_difference(set2))
    
    #差集
    set1 = {1, 2, 3, 4, 5}
    set2 = {4, 5, 6, 7, 9}
    print(set1-set2) #set1独有的
    print(set1.difference(set2))
    
    #去重
    l = [1,2,3,4,4,66,7,7,9,9]
    set9 = set(l)
    l = list(set9)
    print(l)
    

7.用户输入 input

1、等待输入
2、将你输入的内容赋给了前面的变量
3、input出来的数据类型为str

name = input('请输入你的名字:')
age = input('请输入你的年龄:')
print(name, age, type(name))
print('我的名字是' + name, '年龄' + age + '岁')

8.流程控制之_if

第一种

if 条件:结果

if True:
    print(666)
print(777)

第二种

if 4 > 5:
    print('123')
else:
    print('456')

第三种

num = int(input('请输入你的数字:'))
if num == 1:
    print('我我请你吃鸡')
elif num == 2:
    print('一起大排档')
else:
    print('新开了一家,走看看去')

第四种 嵌套

name = input('请输入名字:')
age = input('请输入年龄:')
if name == '小儿狗':
    if age == '19':
        print('999')
    else:
        print('333')
else:
    print('输入错误')

9.循环控制_while

print('111')
while True:
    print('在人间')
    print('痒')
    print('下山')
print(222)

10.格式化输出

%s 顺序
name = input('请输入姓名:')
age = input('请输入年龄:')
height = input('请输入身高:')
msg = '我叫%s,今年%s,身高%s,学习进度3%%' % (name, age, height)
print(msg)

.format
name = input('请输入姓名:')
age = input('请输入年龄:')
height = input('请输入身高:')
msg = '我叫{},今年{},身高{},学习进度3%'.format(name,age,height)
print(msg)

11.初始编码

ASCII码最左边的那一位是0, 8bit 位== 1byte 字节 1024byte == 1kb
unicode 一个中文>4byte 32bit
utf-8 一个中文>3byte 24bit
gbk 一个中文>2byte 16bit'''

12. 运算符

算数运算符
比较运算符
赋值运算符
逻辑运算符 优先级 () not and or

ps:int >  bool 非零转换成bool True  0转换成bool False

x or y,x为真(非零),返回x
print(1 or 2)
print(2 or 1)
x and y,x为真(非零),返回y
print(1 and 0)
print(0 and 1)
print(2 or 1 < 3 and 2)

13.文件操作

  • 1、文件路径

  • 2、编码方式(以什么编码方式存储文件就以什么编码打开进行操作)

  • 3、操作方式:只读 只写 追加 读写 写读........

    只读r rb

    打开文件,得到文件句柄并赋值给变量

    f = open('log','r',encoding='utf-8') #默认打开模式为r
    data = f.read() #通过句柄对文件进行操作
    print(data)
    f.close() #关闭文件

    f = open('log','rb')
    data.read()
    print(data)
    f.close()

    read()读取的时候指定读取到什么位置,按照字符读取

    f = open('log','r',encoding='utf-8')
    data = f.read(3)
    print(data)
    f.close()

    readline()读取每次只读取一行,注意点:readline()读取出来的数据在后面都有一个\n

    f = open('log','r',encoding='utf-8')
    data = f.readline()
    print(data)
    f.close()

    readlines() 返回一个列表,列表里的元素是原文件的每一行

    for 循环 每行遍历

    f = open('log','r',encoding='utf-8')
    for line in f:
    print(line)

    写 w wb

    w没有此文件,创建文件

    f = open('log','w',encoding='utf-8')
    f.write('一根藤上七朵花')
    f.close()

    先将源文件的内容全部清除,再写

    f = open('log','w',encoding='utf-8')
    f.write('葫芦娃呼噜娃')
    f.close()

    wb

    f = open('log','wb')
    f.write('小河弯弯向东流'.encode('utf-8'))
    f.close()

    a 打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。

    f = open('log','a',encoding='utf-8')
    f.write('葫芦娃呼噜娃')
    f.close()

    读写r+

    f = open('log','r+',encoding='utf-8')
    f.read()
    f.write('!!!!!!!!!!!!!')
    f.close()

    w+

    f = open('log','w+',encoding='utf-8')
    f.write('ajian')
    f.seek(0)#调光标
    print(f.read())
    f.close()

    a+

    f = open('log','a+',encoding='utf-8')
    f.write('1111高清无码111111111')
    f.seek(0)
    print(f.read())
    f.close()

    seek()

    seek(n)光标移动到n位置,注意: 移动单位是byte,所有如果是utf-8的中文部分要是3的倍数

    通常我们使用seek都是移动到开头或者结尾

    移动到开头:seek(0)

    移动到结尾:seek(0,2) seek的第二个参数表示的是从哪个位置进行偏移,默认是0,表示开头,1表示当前位置,2表示结尾

    f = open("log", mode="r+", encoding="utf-8")
    f.seek(0) # 光标移动到开头
    content = f.read() # 读取内容, 此时光标移动到结尾
    print(content)
    f.seek(0) # 再次将光标移动到开头
    f.seek(0, 2) # 将光标移动到结尾
    content2 = f.read() # 读取内容. 什么都没有
    print(content2)
    f.seek(0) # 移动到开头
    f.write("小花猫") # 写入信息. 此时光标在9 中⽂文3 * 3个 = 9
    print(f.tell()) # 光标位置9
    f.flush()
    f.close()

    
    - 注意
    
    - ```python
    #1. 打开文件的模式有(默认为文本模式):
    r ,只读模式【默认模式,文件必须存在,不存在则抛出异常】
    w,只写模式【不可读;不存在则创建;存在则清空内容】
    a, 只追加写模式【不可读;不存在则创建;存在则只追加内容】
    
    #2. 对于非文本文件,我们只能使用b模式,"b"表示以字节的方式操作(而所有文件也都是以字节的形式存储的,使用这种模式无需考虑文本文件的字符编码、图片文件的jgp格式、视频文件的avi格式)
    rb 
    wb
    ab
    注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,不能指定编码
    
    #3,‘+’模式(就是增加了一个功能)
    r+, 读写【可读,可写】
    w+,写读【可写,可读】
    a+, 写读【可写,可读】
    
    #4,以bytes类型操作的读写,写读,写读模式
    r+b, 读写【可读,可写】
    w+b,写读【可写,可读】
    a+b, 写读【可写,可读】
    
    • #打开一个文件包含两部分资源:操作系统级打开的文件+应用程序的变量。在操作完毕一个文件时,必须把与该文件的这两部分资源一个不落地回收,回收方法为:
      f.close() #回收操作系统级打开的文件
      del f #回收应用程序级的变量
      
      #其中del f一定要发生在f.close()之后,否则就会导致操作系统打开的文件还没有关闭,白白占用资源,而python自动的垃圾回收机制决定了我们无需考虑del f,这就要求我们,在操作完毕文件后,一定要记住f.close()
      # 使用with关键字来帮我们管理上下文
      with open('log.txt','w') as f:
          pass
      
      with open('log.txt','r') as read_f,open('log.txt','w') as write_f:
          data=read_f.read()
          write_f.write(data)
      
  • 编码方式

    • # 各个编码之间的二进制,是不能相互识别的,会产生乱码
      # 文件的存储,传输,不能是Unicode(只能是utf-8 utf-16 gbk,gb2312 ascii码)
      
      # python3
      #         str在内存中是用Unicode编码.
      #           bytes类型 编码以utf-8 gbk gb2312
      #           对于英文,
      #               str: 表现形式:s='jim'  编码方式>unicode
      #               bytes:       s=b'jim' 编码方式>utf-8 gbk gb2312
      #               对于中文,
      #               str: 表现形式:s='中国'  编码方式>unicode
      #               bytes:       s=b'\xe4\xb8\xad\xe5\x9b\xbd' (16进制)编码方式>utf-8 gbk gb2312
      s = 'jim'
      s2 = '中国'
      # print(s, type(s))
      
      #encode 编码,如何将str>bytes Unicode>gbk  utf-8
      s1 = s.encode('utf-8')
      s22 = s2.encode('utf-8')
      print(s22)
      
      
    • 文件的数据是存放于硬盘上的,因而只存在覆盖、不存在修改这么一说,我们平时看到的修改文件,都是模拟出来的效果,具体的说有两种实现方式:

      方式一:将硬盘存放的该文件的内容全部加载到内存,在内存中是可以修改的,修改完毕后,再由内存覆盖到硬盘(word,vim,nodpad++等编辑器)

    • import os  # 调用系统模块
      
      with open('a.txt') as f,open('a1','w') as f1:
          data=f.read() #全部读入内存,如果文件很大,会很卡
          data=data.replace('ajian','SB') #在内存中完成修改
      
          f1.write(data) #一次性写入新文件
      
      os.remove('a.txt')  #删除原文件
      os.rename('.a.txt.swap','a.txt')   #将新建的文件重命名为原文件
      
      
    • 方式二:将硬盘存放的该文件的内容一行一行地读入内存,修改完毕就写入新文件,最后用新文件覆盖源文件

    • import os
      
      with open('log.txt') as f1,open('log1.txt','w') as f2:
          for line in f1:
              line=line.replace('ajian','SB')
              f2.write(line)
      
      os.remove('log.txt')
      os.rename('log1.txt','log.txt') 
      
posted @ 2020-05-08 00:20  十块钱买包鸟崽烟  阅读(65)  评论(0)    收藏  举报