IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Python知识库 -> python期末复习 -> 正文阅读

[Python知识库]python期末复习

Python期末复习

第二章 基本程序设计

eval('3')               # 3 
eval('3') + eval('4')   # 7
eval('abc')             #报错,abc没有定义
x , y = y ,x            #x,y互换
eval('34') == eval('3' + '4')
integer = eval(input('Enter an integer:'))
q = integer // 1000 
b = integer // 100 % 10
g = integer % 1000 % 100 // 10
s = integer % 1000 % 100 %10
print(s,g,b,q)

在这里插入图片描述

第三章 数字函数,字符串和对象

  1. 符串和字符
    ord('a') #返回字符的ascii码          97
    chr(98)  #返回ascii码的code字符      'b'
    
  2. 对象和方法
    n = 3        
    id(n)    #2426581877040
    type(n)  #int
    
    s1 = 'HELLO'
    s1 = s1.lower()    # 'hello'
    s1
    
    s2 = 'hello'
    s2 = s1.upper()    #'HELLO'
    s2
    
  3. strip():删除字符串两端的空格
    s = '\t Welcome \n'
    s1 = s.strip()      #'Welcome'
    s1
    
    s = '\t \n\t123e\t12\nsa  \t\n\t'
    s.strip()        #'123e\t12\nsa'
    
    '''\t,\f,\r,\n都属于空格'''
    
  4. object.find(str(被查找字符),beg = 0(开始索引),end(结束索引)).如果找到则返回object中第一次出现str的索引值,否则返回-1 。
  5. format() 函数 ‘.2f’ 四舍五入后保留小数点后2位小数
    round(0.1532,2)                  # 0.15
    format(0.125,'.2f')              #'0.12'
    
    #数值类型默认右对齐,小数点也占一位
    format(57.467657,'10.2f')        #'     57.47'
    format(12345678.923,'10.2f')     #'12345678.92'
    format(57.4,'10.2f')             #'     57.40'
    format(57,'10.2f')               #'     57.00'
    format(57,'.2f')                 #'57.00'
    
    #字符串默认左对齐
    format('hello! Amber','20s')     #'hello! Amber        '
    format('hello! Amber','<20s')    #'hello! Amber        '
    format('hello! Amber','>20s')    #'        hello! Amber'
    format('hello! Amber!hello! Amber!','>20s')
                                     #'hello! Amber!hello! Amber!'
        
    #  %也占一位
    format(0.456789101112,'9.3%')    #'  45.679%'
    format(0.456789101112,'<9.3%')   #'45.679%  '
    
  6. object.split (str=’’,num = string.count(str))
    str = 'Line1-abcdef \nLine2-abcdef \nLine3-abcdef'
    str.split()     
    #['Line1-abcdef', 'Line2-abcdef', 'Line3-abcdef']
    
    str.split(' ',1)
    #['Line1-abcdef', '\nLine2-abcdef \nLine3-abcdef']
    
    s = 'apple,peach,banana,pear'
    s.split(',',2)
    #['apple', 'peach', 'banana,pear']
    
    s = 'asda\t as\nsada  saa\nasda'
    s.split('s')
    #['a', 'da\t a', '\n', 'ada  ', 'aa\na', 'da']
    s.split('\n')
    #['asda\t as', 'sada  saa', 'asda']
    

第四章 选择

  1. 布尔类型、值和表达式
    • python用1代表True ;用0代表False
    • True是python关键字;一个布尔字面量(对);等同于1(错)
    • Python将任何非零非空值视为True,如果一个对象为0或者为空,那么被视为Flase
  2. 生成随机数
    • random.randint(a,b) 从范围[a,b]中返回一个随机整数,包括a和b
    • random.random() 从范围(0,1)中返回一个随机**浮点数****
    • randrange(a,b) 从范围[a,b)中返回一个随机整数,包括a但不包括b,与 random.randint(a,b - 1 )相同
    • random.sample(object(eg.string,list),number) 多用于截取列表的指定长度的随机数,但不改变列表本身的顺序
    random.randint(0,10)           #8
    random.random()                #0.1632552069197507
    random.randrange(0,10)         #9
    random.sample(range(1,100),3)  #[25, 5, 82]
    random.sample(range(1,100),4)  #[4, 53, 28, 79]
    
  3. if i > 0 :
       x = 1
       y = 1
    

    可以使用任何宽度的空格,但一定要对齐

  4. 条件表达式
    if x > 0:
    	y = 1
    else:
    	y = -1
    
    y = 1 if x > 0 else -1
    
    if number % 2 == 0:
    	print(number,'is even.')
    else:
    	print(number,'is odd.')
    	
    print(number,'is even.' if number % 2 == 0 else 'is odd.')
    

第五章 循环

0 % 2 = 0 1 % 2 = 0

  1. 举例

    1. 乘法口诀表

      #乘法口诀表
      print('           Multiplication Table')
      print(' '* 2 ,end = ' ')
      for i in range(1,10):
          print(format(i,'4d'),end = ' ')
      print()
      print('-' * 4 * 12)
      for i in range(1,10):
          print(i,end = '| ')
          for j in range(1,10):
              print(format(i * j,'4d'),end = ' ')
          print()
      

在这里插入图片描述

  1. 嵌套循环

    for i in range(1,5):
        j = 0
        while j < i:
            print(j,end = ' ')
            j += 1
            
    # 0 0 1 0 1 2 0 1 2 3 
    
    i = 5
    while i >= 1:
        num = 1
        for j in range(1,i + 1):
            print(num,end = 'xxx')
            num *= 2
        print()
        i -= 1
        
    1xxx2xxx4xxx8xxx16xxx
    1xxx2xxx4xxx8xxx
    1xxx2xxx4xxx
    1xxx2xxx
    1xxx
    
    for i in range(1,9):
        print(' ' * 4 * (8 - i),end = ' ')
        for j in range(0,i):
            print(format(2 ** j ,'3d'),end = ' ')
        for j in range(0,i - 1):
            print(format(2 ** (i - j - 1),'3d'),end = ' ')
        print()
    
  2. 找出最大公约数

    #找出最大公约数
    n1 = eval(input('Enter first integer:'))
    n2 = eval(input('Enter second integer:'))
    gcd = 1
    k = 2
    while k < min(n1,n2):
        if n1 % k == 0 and n2 % k == 0:
            gck = k
        k += 1
    print(n1,'和',n2,'的最大公约数是',gck)
    
    #或者
    n1,n2 = eval(input('Please enter two integer:'))
    for i in range(1,min(n1 + 1, n2 + 1)):
        if n1 % i == 0 and n2 % i == 0:
            a = i
    print(n1,'和',n2,'的最大公约数是',a)
    
  3. break 和 continue

    1. break帮助退出整个循环

    2. continue帮助退出或跳过当前的迭代

      sum = 0
      number = 0
      while number < 20:
          number += 1
          sum += number
          if sum >= 100:
              break
          
      print('The number is ',number,'\nThe sum is ',sum)
      
      #The number is 14
      #The sum is 105
      
      sum = 0
      number = 0
      while number < 20:
          number += 1
          if number == 10 or number == 11:
              continue
          sum += number
      print('The sum is ',sum)
      
      # 10 与 11并没有加入
      #The sum is 189
      
      #break and continue
      b = 1000
      while 1:
          if b < 9:
              break
          b = b - 9
      print('b is ',b)
      #b is 1
      
      b = 1000
      while 1:
          if b < 9:
              continue
          b = b - 9
      print('b is ',b)
      #陷入死循环
      
      #break and continue
      for i in range(1,4):
          for j in range(1,4):
              if i * j > 2:
                  break
              print( i * j)
          print(i)
       
      1
      2
      1
      2
      2
      3
      
      for i in range(1,4):
          for j in range(1,4):
              if i * j > 2:
                  continue
              print( i * j)
          print(i)
      
      1
      2
      1
      2
      2
      3
      
      #写一个程序,给出前50个素数,每行包含10个素数
      print('The first 50 prime numbers are')
      print()
      count = 0
      n = 2
      
      while count < 50:
          for i in range(2,(n // 2 + 1)):
              if n % i == 0:
                  break
          else:
              count += 1
              print(format(n,'>5d'),end = ' ')
              if count % 10 == 0:
                  print()
          n += 1
      

在这里插入图片描述

第六章 对象和类

  1. 一切事物都是对象,如类,函数等,因此对象并不只是一个类的实例

  2. init(self,…) self初始化:创建数据域

  3. self可以用其他变量代替,只是习惯上self

  4. 不可变对象和可变对象

  5. 举例

    1. class Count:
          def __init__(self,count = 0):
              self.count = count
      def main():
          c = Count()
          times = 0
          for i in range(100):
              increment(c,times)
          print('count is ',c.count)
          print('times is ',times)
      def increment(c,times):
          c = Count(times)
          times += 1
      main()
      
      #count is 0
      #times is 0
      
  6. 隐藏数据域

    1. 缺陷:数据肯能会被篡改; 不利于维护
    2. 定义:__radius 通过2个下划线来定义私有数据域
    3. 私有数据域和方法仅能在类内部被访问,类外部不能被访问,除非提供一个方法返回它的值
    4. 类如果只是在程序内使用,而不是被其他程序使用,那么没有必要定义私有数据域

第七章 字符串、列表、集合和字典

  1. 创建字符串
    s = ''
    s1 = 'amber'
    s = str()
    s1 = str('amber')
    
  2. 字符串的相关函数
    len('\t')      #1
    len('\t 12')   #
    
  3. 索引操作符[]

    index:[0,len(s) - 1]

    s[-1] = s[-1 + len(s)]

  4. 切片操作符
    • s[start:end]:返回指定索引值从start到end -1的字符切片

      s = 'welcome'
      s[1:4]              #'elc'
      
    • 默认情况:start = 0,end 为最后一个

      s[ :6]              #'welcom'
      s[4: ]              #'ome'
      
    • 如果 s[i:j]中的索引值i或j为负数,将它替换为len(s)+i或j
      如果j > len(s),j默认为len(s)
      如果i >= j,那么切片值为空字符

      s[1:-1]             #'elcom'
      s[2:-3]             #'lc'
      
  5. in 和 not in操作符

    测试一个字符是否在另一个字符串中 返回布尔值

  6. 迭代字符串

    s = 'welcome'
    for ch in s :
        print(ch,end = " ")
    #w e l c o m e
    
    #将一个多位数反转
    number = 123456
    s = str(number)
    for i in range(len(s)):
        print(s[len(s) - i -1],end = ' ')
    # 6 5 4 3 2 1 
    # %%
    num = ''
    for i in range(len(s)):
        num = num + s[len(s)- i - 1]
    int(num)
    #654321
    
  7. 列表方法

     list1 = [2,3,4,2,6,5,3,56]
     list1.append(19)
     #[2, 3, 4, 2, 6, 5, 3, 56, 19]
    
    list1.count(3)
    #2
    
    list2 = [99,54]
    list1.extend(list2)
    list1
    #[2, 3, 4, 2, 6, 5, 3, 56, 19, 99, 54]
    
    list1.insert(3,77)   #index = 3,return None
    #[2, 3, 4, 77, 2, 6, 5, 3, 56, 19, 99, 54]
    
    list1.pop(3)         #index = 3,return None
    #[2, 3, 4, 2, 6, 5, 3, 56, 19, 99, 54]
    
    list1.pop()          #弹出最后一个字符,return最后一个字符
    #54
    [2, 3, 4, 2, 6, 5, 3, 56, 19, 99]
    
    list1.remove(56)      #移除56,return None
    #[2, 3, 4, 2, 6, 5, 3, 19, 99]
    
    list1.reverse()       #翻转列表
    #[99, 19, 3, 5, 6, 2, 4, 3, 2]
    
    list1.sort()          #排序
    #[2, 2, 3, 3, 4, 5, 6, 19, 99]
    
    a,b = [1,2,3],[99,100]
    a.append(b)
    #[1, 2, 3, [99, 100]]
    
    a.append('a')
    a.append(['b'])
    #[1, 2, 3, [99, 100], 'a', ['b']]
    
    x的范围是1~10,将x中的每个元素值扩大3倍,并存入一个列表中
    法1list = [ i * 3 for i in range(1,11)]
    list
    #[3, 6, 9, 12, 15, 18, 21, 24, 27, 30]2:
    list2 = []
    for i in range(1,11):
        list2.append(i * 3)
    list2
    #[3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
    
  8. 列表解析

    a = [x + y for x in 'ab' for y in '123']
    a
    #['a1', 'a2', 'a3', 'b1', 'b2', 'b3']
    
  9. 复制列表 list2 = list1

    • 这条语句不是将list1中的内容赋给list2,而是将参考对象赋给list2,即他们指向同一个对象

    • a = [1,2,3,4]
      b = a
      b                    
      #[1, 2, 3, 4]
      
      a[0] = -1
      b
      #[-1, 2, 3, 4]
      
      b = a + []        #新建一个列表   等同于 b = a[:]
      a[0] = -2
      a                 #[-2, 2, 3, 4]
      b                 #[-1, 2, 3, 4]
      
  10. 举例

    ? 易混淆

    def main():
        list1 = add(1)
        print(list1)
        list2 = add(2)
        print(list2)
        list3 = add(3,[11,12,13,14])
        print(list3)
        list4 = add(4)
        print(list4)
    main()
    
    [1]
    [1, 2]
    [11, 12, 13, 14, 3]
    [1, 2, 4]
    
    def add(x,lst = None):
        if lst == None:
            lst = []
        if x not in lst:
            lst.append(x)
        return lst
    
    def main():
        list1 = add(1)
        print(list1)
        list2 = add(2)
        print(list2)
        list3 = add(3,[11,12,13,14])
        print(list3)
        list4 = add(4)
        print(list4)
    main()
    
    [1]
    [2]
    [11, 12, 13, 14, 3]
    [4]
    

    查找列表

    #线性查找   --不需要排序
    def linearSearch(lst,key):
        for i in range(len(lst)):
            if key == lst[i]:
                return i
        return -1
    
    lst = [1,2,3,4,5,1,2,3,5]
    print(linearSearch(lst,5))       #4
    print(linearSearch(lst,9))       #-1
    #二分查找   --需要排序
    def binarySearch(lst,key):
        low = 0
        high = len(lst) - 1
        while high >= low:
            mid = (high + low) // 2
            if key <lst[mid]:
                high = mid - 1
            elif key > lst[mid]:
                low = mid + 1
            else:
                return mid
        return - low - 1
    
    lst = [1,2,3,4,5,1,2,3,5]
    print(binarySearch(lst,5))       #4
    print(binarySearch(lst,9))       #-10
    

第八章 多维列表集合和字典numpy

  1. 打印列表

    matrix = [[1,2,3],[4,5,6],[7,8,9]]1for row in range(len(matrix)):
        for colum in range(len(matrix[row])):
            print(matrix[row][colum],end = ' ')
        print()2for row in matrix:
        for value in row:
            print(value,end = ' ')
        print()
    1 2 3
    4 5 6 
    7 8 9 
    
  2. 随机打乱顺序,random.shuffle(list)函数只能处理一维列表,不能处理多维列表

    import random
    
    matrix = [[1,2,3],[4,5,6],[7,8,9]]
    for row in range(len(matrix)):
        for column in range(len(matrix[row])):
            i = random.randint(0,len(matrix) - 1)
            j = random.randint(0,len(matrix[row]) - 1)
    
            matrix[row][column],matrix[i][j] = matrix[i][j], matrix[row][column]
    print(matrix)
    #[[2, 1, 4], [3, 9, 6], [5, 7, 8]]
    #[[3, 1, 4], [8, 2, 9], [5, 7, 6]]
    
  3. 排序 --sort()

    points = [[4,2],[1,4],[2,5],[6,7],[1,2],[4,1]]
    points.sort()
    print(points)
    #[[1, 2], [1, 4], [2, 5], [4, 1], [4, 2], [6, 7]]
    
  4. 易混淆

    matrix = []
    matrix.append(3 * [1])
    matrix.append(3 * [1])
    matrix.append(3 * [1])
    print(matrix)
    matrix[0][0] = 2
    print(matrix)
    [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
    [[2, 1, 1], [1, 1, 1], [1, 1, 1]]
    
    matrix = []
    matrix.append([3 * [1]])
    matrix.append([3 * [1]])
    matrix.append([3 * [1]])
    print(matrix)
    matrix[0] = 3
    print(matrix)
    [[[1, 1, 1]], [[1, 1, 1]], [[1, 1, 1]]]
    [3, [[1, 1, 1]], [[1, 1, 1]]]
    
  5. 初始化列表 and 求和

    #初始化列表
    import random
    matrix = []
    
    row = eval(input('Enter the row:'))
    column = eval(input('Enter the column:'))
    for i in range(row):
        matrix.append([])
        for j in range(column):
            value = random.randint(0,99)
            matrix[i].append(value)
    print(matrix)
    #求和
    def isSum(matrix):
        sum = 0
        if matrix != None:
            for row in matrix:
                for value in row:
                    sum = sum + value
                '''
                for value in row:
                    sum = sum + value
                    也可替换为:
                    sum = sum + sum(row)
                    sum()求列表的和
                '''
            return sum
        else:
            return False
    matrix =  [[2, 1, 1], [1, 1, 1], [1, 1, 1]]
    print(isSum(matrix))
    
  6. 元组 和列表一样,但元素不可变,且元组的效率更高

    元组一旦创建,就不能增删,替换元素,也不能改变顺序

    注意 tuple([1,2,3]) == (1,2,3);

    tuple(list1.sort())会报错

    t1 = ()                                 #()
    t2 = (1,2,3)                            #(1,2,3)
    t3 = tuple([2 * x for x in range(3)])   #(0,2,4)
    t4 = tuple('abac')                      #('a', 'b', 'a', 'c')
    
    tuple1 = ('a','b','c')
    ###注意 tuple([1,2,3]) == (1,2,3)
    tuple2 = tuple([1,2,3])
    tuple3 = tuple1 + tuple2
    tuple3
    ('a','b','c',1,2,3)
    
    tuple1 = tuple([7,8,5,6,1,2,3,4])
    list1 = list(tuple1)            #[7, 8, 5, 6, 1, 2, 3, 4]
    list1.sort()                    #[1, 2, 3, 4, 5, 6, 7, 8]
    #tuple(list1.sort())会报错
    
  7. 集合

    集合中没有重复的元素,也没有顺序,如果不考虑顺序的话,用集合比用列表的效率要高

    集合无序,没有index方法

    初始化
    s1 = set()                        #set()
    s2 = {1,2,3}                      #{1, 2, 3}
    s3 = set([1,2,3])                 #{1, 2, 3}
    s4 = set([x for x in range(5)])   #{0, 1, 2, 3, 4}
    s5 = set('abad')                  #{'a', 'b' , 'd'}
    
    相关操作
    s1 = {1,2,3} 
    s1.add(5)
    len(s1)                           #4
    max(s1)                           #5
    sum(s1)                           #11
    3 in s1                           #True
    s1.remove(2)                      #{1,3,5}
    
    子集与超集
    如果s1中所有元素都在s2中,那么s1是s2的子集 s1.issubset(s2)
    如果s2中所有元素都在s1中,那么s1是s2的超集 s1.issuperset(s2)
    
    s1 = {1,2,4}
    s2 = {1,4,5,2,6}
    s1.issubset(s2)           #True
    s2.issuperset(s1)         #True         
    
    集合操作符
    并集
    s1 = {1,2,4}
    s2 = {1,3,5}
    s1.union(s2)                 #或s1 | s2
    {12345}
    
    交集
    s1.intersection(s2)          #或s1 & s2
    {1}
    
    差集
    s1.difference(s2)            #或s1 - s2
    {2,4}
    
    对称差(异或)
    s1.symmetric_difference(s2)  #s1 ^ s2
    {2, 3, 4, 5}
    
  8. 字典

    存储键值对集合的容器对象。通过关键字实现快速获取、删除和更新值

    字典中的关键字有点像列表中的索引,每个索引对应一个值,关键字不能相同,但其对应值可以相同 key:value

    key只能是不可变对象,所以列表不能用来做key

    a = {'1':'a','2':'b'}
    a = {}
    
    添加、修改、获取值
    students = {'201931990201':'a','201931990202':'b','201931990203':'3'}      
    #{'201931990201': 'a', '201931990202': 'b', '201931990203': '3'}
    
    students['201931990209'] = 'amber'
    #{'201931990201': 'a', '201931990202': 'b', '201931990203': '3', '201931990209': 'amber'}
    
    students['201931990201'] = 'wenzhou'
    #{'201931990201': 'wenzhou', '201931990202': 'b', '201931990203': '3', '201931990209': 'amber'}
    
    print(students['201931990209'])
    #amber
    
    vegetables = [('celery',1.58),('brocoli',1.29),('lettuce',2.19)]
    dict = dict(vegetables)
    print(dict)
    {'celery': 1.58, 'brocoli': 1.29, 'lettuce': 2.19}
    
    删除与循环条目
    a = {'abc':123,'cde':456}           #{'abc': 123, 'cde': 456}
    del a ['cde']
    print(a)                            #{'abc': 123}
    
    a = {'abc':123,'cde':456}
    for key in a:
        print(a[key])
    123
    456
    
    字典方法
    keys()返回关键字序列 tuple
    students = {'001':'amber1','002':'amber2','003':'amber3'}
    tuple(students.keys())
    ('001', '002', '003')
    
    values()返回值序列 tuple
    tuple(students.values())
    ('amber1', 'amber2', 'amber3')
    
    tuple(students.items())
    (('001', 'amber1'), ('002', 'amber2'), ('003', 'amber3'))
    
    get(key)
    print(students.get('001'))
    amber1
    
    pop(key)返回值,并删除
    print(students.pop('001'))
    amber1
    
    删除所有条目
    students.clear()
    {}
    
    

numpy常用生成数组的函数 -->多维数组

  1. np.zero() np.empty() np.ones()

    import numpy as np
    x= np.zeros(6)
    x
    array([0., 0., 0., 0., 0., 0.]) 
    
    
    x = np.zeros((2,3))
    array([[0., 0., 0.],[0., 0., 0.]])
        
    np.empty((2,3))  
    array([[0., 0., 0.],[0., 0., 0.]])
     
    np.ones((2,3))
    array([[1., 1., 1.],[1., 1., 1.]])
        
    np.ones([2,3])  
    array([[1., 1., 1.], [1., 1., 1.]])
    
  2. 利用arange(a,b,step)函数创建[a,b)之间以step为步长的一维数组

    • 默认以0开始步长为1的整数序列
    • arrange的参数可以是浮点数

    array.shape 返回数组的维数

    array.size 返回数组的元素个数

    a = np.arange(6)
    array([0, 1, 2, 3, 4, 5])
     
    a.shape 
    (6,)
        
    a.size
    6    
    
    np.arange(1,10,2)
    array([1, 3, 5, 7, 9])
    
    np.arange(1,2,0.2)
    array([1. , 1.2, 1.4, 1.6, 1.8])
    
    np.arange(1.2,3.1,0.3)
    array([1.2, 1.5, 1.8, 2.1, 2.4, 2.7, 3. ])
    
  3. array.reshape(n,m,k)将数组array转换为n* m* k维矩阵

    a = np.arange(12)
    a
    array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
    
    b = a.reshape(2,3,2)
    b
    array([[[ 0,  1],
            [ 2,  3],
            [ 4,  5]],
    
           [[ 6,  7],
            [ 8,  9],
            [10, 11]]])
        
    b = a.reshape(2,3,-1)
    b
    array([[[ 0,  1],
            [ 2,  3],
            [ 4,  5]],
    
           [[ 6,  7],
            [ 8,  9],
            [10, 11]]])
    

第九章 文件操作

  1. 文件分为二进制文件和文本文件

  2. 打开文件

    fileopen = open(filename,mode)
    'r' 为读取打开一个文件
    'w' 为写入打开一个文件,如果文件已存在,则销毁
    'a' 打开一个文件从文件尾部追加数据
    'rb'为读取二进制数据而打开文件
    'wb'为写入二进制数据打开文件
    #打开当前目录
    fl = open('score.txt','r') 
    #打开绝对目录下
    f2 = open(r'C:\Users\LiuYixiu\Desktop\score.txtt','r')
    f2 = open('C:\\Users\\LiuYixiu\\Desktop\\score.txt','r')
    
  3. 当我们对该目录下已存在的文件进行写操作时,已有的文件数据将会被新的文本覆盖或销毁
    测试文件是否存在:

    import os.path

    os.path.isfile(‘score.txt’)

    存在返回True ,否则False

  4. 读写文件 !!!读取完要关闭

    outfile = open('score.txt','w')
    outfile.write('Bill Clintor\n')
    outfile.write('George Bush\n')
    outfile.write('Barack Obama')
    outfile.close()
    
  5. 从文件中读取所有数据:

    1. read():读取剩下所有的数据,以字符串的形式返回

    2. readlines():读取剩下所有的数据,以字符串列表的形式返回,这里的字符串是原始数据

    3. 注意:数据量太大以致于存储器无法存下,read(),readlines()方法都不可行,可以循环利用readline()解决

      while line! = ‘’:

      line = inflie.readline()

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

    def main():
        inflie = open('score.txt','r')
        print('(1) Using read ():')
        print(inflie.read())
        inflie.close()
    
        inflie = open('score.txt','r')
        print('\n(2) Using read (number):')
        s1 = inflie.read(4)
        print(s1)
        s2 = inflie.read(4)
        #repr()返回原始字符串
        print(repr(s2))
        inflie.close()
    
        inflie = open('score.txt','r')
        print('\n(3) Using readline ():')
        line1 = inflie.readline()
        line2 = inflie.readline()
        line3 = inflie.readline()
        line4 = inflie.readline()
        print(repr(line1))
        print(repr(line2))
        print(repr(line3))
        print(repr(line4))
        inflie.close()
    
        inflie = open('score.txt','r')
        print('\n(4) Using readlines ():')
        print(inflie.readlines())
        inflie.close()
    main()
    '''
    (1) Using read ():
    Bill Clintor
    George Bush
    Barack Obama
    
    (2) Using read (number):
    Bill
    ' Cli'
    
    (3) Using readline ():
    'Bill Clintor\n'
    'George Bush\n'
    'Barack Obama'
    ''
    
    (4) Using readlines ():
    ['Bill Clintor\n', 'George Bush\n', 'Barack Obama']
    '''
    
    #将一个源文件的数据复制到目标文件,并统计文件的行数和字符数
    from os import path
    import os.path
    import sys
    def main():
        f1 = input('Enter a source file:').strip()
        f2 = input('Enter a target file:').strip()
        if os.path.isfile(f2):
            print(f2 + 'already exists')
            sys.exit()
        infile = open(f1,'r')
        outfile = open(f2,'w')
        countLines = countChars = 0
        for line in infile:
            countLines += 1
            countChars += len(line)
            outfile.write(line)
        print(countLines,'lines and',countChars,'chars copied')
        infile.close()
        outfile.close()
    main()
    
    #在已存在的数据末尾添加数据
    def main():
        outfile = open('score.txt','a')
        outfile.write('\nhello amber\n')
        outfile.close()
    main()
    
    #读取数值数字,必须转换成字符类型
    from  random import randint 
    
    def main():
        outfile = open('score.txt','w')
        for i in range(10):
            outfile.write(str(randint(0,9))+' ')
        outfile.close()
        inflie = open('score.txt','r')
        s = inflie.read()
        numbers = [eval(x) for x in s.split()]
        for number in numbers:
            print(number,end = ' ')
        inflie.close()
    main()
    #8 1 1 9 3 6 2 6 4 5
    
    #统计文件中每个字符出现的次数,不区分大小写
    def main():
        filename = input('Enter a filename:')
        infile = open(filename,'r')
        counts = [0] * 26
        for line in infile:
            countLetters(line.lower(),counts)
        for i in range(len(counts)):
            if counts[i] != 0:
                print(chr(ord('a') + i) + '  appears  ' + str(counts[i]) + ('  time  ' if counts[i] == 1 else '   times'))
                infile.close()
    def countLetters(line,counts):
        for ch in line:
            if ch.isalpha():
                counts[ord(ch) - ord('a')] += 1
    main()
    '''
    Enter a filename:score.txt
    a  appears  6   times
    b  appears  5   times
    c  appears  12   times
    d  appears  15   times
    f  appears  11   times
    v  appears  14   times
    '''
    
  6. 从网站上获取数据

    打开URL:使用函数urlopen(‘http://hao123.com’)

    import urllib.request
    infile = urllib.request.urlopen('http://www.hao123.com')
    #read()读取字节数据类型的原始数据
    #decode()将原始数据转换为字符串
    print(infile.read().decode())
    
    import urllib.request
    def main():
        url = input('Enter a URL for a file:')
        infile = urllib.request.urlopen(url)
        s = infile.read().decode()
        counts = countLetters(s.lower())
        for i in range(len(counts)):
            if counts[i] != 0:
                print(chr(ord('a') + i) + ' appears ' + str(counts[i]) + (' time' if counts[i] == 1 else ' times'))
    
    def countLetters(s):
        counts = 26 * []
        for ch in s:
            if ch.isalpha():#判断ch是否由英文字母组成
                counts[ord(ch) - ord('a')] += 1
        return counts
    
    main()
    

第十章 异常处理

def main():
    try :
        n1 ,n2 = eval(input('Enter two numbers,separated by a comma:'))
        result = n1 / n2
        print('Result is',result)
    except ZeroDivisionError:
        print('Division by zero!')
    except SyntaxError:
        print('A comma may be missing in the input')
    except:
        print('Something wrong in the input')
    else:
        print('No exceptions')
    finally:
        print('The finally clause is executed')
main()
'''
Enter two numbers,separated by a comma:3,4
Result is 0.75
No exceptions
The finally clause is executed

Enter two numbers,separated by a comma:2,0
Division by zero!
The finally clause is executed

Enter two numbers,separated by a comma:2 3
A comma may be missing in the input
The finally clause is executed

Enter two numbers,separated by a comma:a,v
Something wrong in the input
The finally clause is executed
'''
try :
    statement1
    statement2
except Exception1:
except Exception2:
except Exception3:
finally:
    statement4
statement5
'''
若异常未被捕获,那么statement5不会执行,但会执行finally(statement4)
若异常类型是Exception3,那么statement4会执行,statement5也会执行
'''
try:
    lst = [0] * 10
    x = lst[9]
    print('Done')
except IndexError:
    print('Index out of bound')
else:
    print('Nothing is wrong')
finally:
    print('Finally we are here')
print('Coutinue')
'''
Done
Nothing is wrong
Finally we are here
Coutinue
'''
#抛出异常
def annonnegative():
    a = eval(input('asdsa:'))
    if a < 0:
        raise RuntimeError('Negative radius')
    else:
        return a
try:
    a1 = annonnegative()
    print(a1)
except RuntimeError:
    print('Invalid enter value.')
    
'''
asdsa:-1
Invalid enter value.

asdsa:2
2
'''

实验课

在这里插入图片描述

def isMinPrime(n):
    i = 2
    while True:
        if n % i == 0:
            print(i,end = ',')
            n = n // i
        else:
            i = i + 1 
        if n == i:
            print(i)
            break
isMinPrime(120)
22235

在这里插入图片描述

n = eval(input('Enter 1 ~ 15 :'))
for i in range(1,n + 1):
   print(' ' * 4 * (n - i ),end = ' ')
   for j in range(1 , i + 1):
       print(format(i - j + 1,'3d'),end = ' ')
   for j in range(1 , i):
       print(format(j+1,'3d'),end = ' ')
   print()

在这里插入图片描述

    
for j in range(10000,100001,10000):
    e = 1
    item = 1
    for i in range(1 , j + 1):
        item *= i
        e += 1/item
    print("i = %d 时,  e = %.19f"%(j,e))

在这里插入图片描述
在这里插入图片描述

sum = 0
for i in range(1,50):
    sum =  ( 2 * i - 1)/(2 * i + 1) + sum
print(sum)

在这里插入图片描述

#判断一个数是否是素数
def isPrime(num):
    tag = True
    for i in range(2,(num // 2 + 1)):
        if num % i != 0:
            i = i + 1
        else:
            tag = False
    return tag
#判断一个数是否是回文数
def isPalindrome(num):
    tag = True
    s = str(num)
    if s[::-1 ] == s[::]:
        return True
    else:
        return False
#输出前100个回文素数
def print1():
    count = 0
    k = 2
    while count < 100:
        if isPalindrome(k) and isPrime(k):
            count = count + 1
            print(format(k,'6d'),end = ' ')
            if count % 10 == 0:
                print()
        k = k + 1
                
print1()

在这里插入图片描述
在这里插入图片描述

def finder(str1,str2):
    if str2 in str1:
        return True
    else:
        return False
print(finder('abc','a'))

输入1到100之间的整数,统计出现的次数

a = input('Enter integers between 1 and 100:').split()
counts = []
b = list(set( eval(x) for x in a))
b.sort()
for i in range(len(b)):
    item = a.count(str(b[i]))
    print(b[i],'occurs ', item ,' time' if item == 1 else 'times')

在这里插入图片描述

matrix = []
def sumMajorDiagonal(matrix):
    sum = 0
    for i in range(len(matrix)):
        sum = sum + float(matrix[i][i])
    print('Sum of the elements in the major diagonal is',sum)

for i in range(4):
    a = input('Enter a 4-by-4 matrix row for row '+str(i)+':').split()
    matrix.append(a)
    
sumMajorDiagonal(matrix)

在这里插入图片描述

def main():
    matrix1 = []
    matrix2 = []
    
    s = input("Enter a 3-by-3 matrix1: ") 
    items = s.split() # Extracts items from the string
    for i in range(3):
        list = [eval(items[j]) for j in range(3 * i, 3 * i + 3)] # Convert items to numbers   
        matrix1.append(list)

    s = input("Enter a 3-by-3 matrix2: ") 
    items = s.split() # Extracts items from the string
    for i in range(3):
        list = [eval(items[j]) for j in range(3 * i, 3 * i + 3)] # Convert items to numbers   
        matrix2.append(list)
        
    matrix3 = multiplyMatrix(matrix1, matrix2)
    printResult(matrix1, matrix2, matrix3, "*")
    
def multiplyMatrix(m1, m2):
    list = len(m2[0]) * [0]
    result = []  
    for i in range(len(m1)):
        result.append([x for x in list])
    
    for i in range(len(result)):
        for j in range(len(result[0])):
            for k in range(len(m2)):
                result[i][j] += m1[i][k] * m2[k][j]
        
    return result
          
# Print result 
def printResult(m1, m2, m3, op):
    for i in range(len(m1)):
        for j in range(len(m1[0])):
            print(" " + str(m1[i][j]), end = "")

        if i == len(m1) // 2:
            print( "  " + op + "  ", end = "")
        else:
            print( "     ", end = "")

        for j in range(len(m2[0])):
            print(" " + str(m2[i][j]), end = "")

        if i == len(m1) // 2:
            print("  =  ", end = "")
        else:
            print("     ", end = "")

        for j in range(len(m3[0])):
            print(" " + str(m3[i][j]), end = "")

        print()
        
main()
'''
Enter a 3-by-3 matrix1: 1 2 3 4 5 6 7 8 9
Enter a 3-by-3 matrix2: 0 2 4 1 4.5 2.2 1.1 4.3 5.2
 1 2 3      0 2 4      5.300000000000001 23.9 24.0
 4 5 6  *   1 4.5 2.2  =   11.600000000000001 56.3 58.2
 7 8 9      1.1 4.3 5.2      17.9 88.69999999999999 92.4
'''

在这里插入图片描述

#13.1
filename = input('Enter a filename:')
content = input('Enter the string to be removed:')
infile = open(filename,'r')
for line in infile:
    line = line.replace(content,'')
    print(line)
infile.close()
'''
Enter a filename:score.txt
Enter the string to be removed:okk
Amber!

good moring!

haha!1

abchsfndvjmfkvmfjvfvjfjivjvjnj!
'''
'''
Enter a filename:score.txt
Enter the string to be removed:1
Amber!

good moring!

haha!okkokk

abchsfndvjmfkvmokkfjvfvjokkfjivjvjnjokk!
'''

#13.2
def main():
    f1 = input("Enter a filename: ").strip()
    infile = open(f1, "r") 
    s = infile.read() 
    print(str(len(s)) + " characters") 
    print(str(len(s.split())) + " words") 
    print(str(len(s.split('\n'))) + " lines") 
    infile.close()
main()
'''
Enter a filename: score.txt
69 characters
6 words
7 lines
'''
  Python知识库 最新文章
Python中String模块
【Python】 14-CVS文件操作
python的panda库读写文件
使用Nordic的nrf52840实现蓝牙DFU过程
【Python学习记录】numpy数组用法整理
Python学习笔记
python字符串和列表
python如何从txt文件中解析出有效的数据
Python编程从入门到实践自学/3.1-3.2
python变量
上一篇文章      下一篇文章      查看所有文章
加:2022-01-17 11:28:10  更:2022-01-17 11:30:18 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/16 1:27:57-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码