Posts pyhon--基础
Post
Cancel

pyhon--基础

变量与字符串

  1. 字符串可以为单引号,也可以为双引号
    1
    2
    
     message = "hello word "
     message = 'hello word "python"'
    
  2. 修改字符串的大小写
    1
    2
    3
    
     name.title() 首字母大写 
     name.upprt()   全体大写
     name.lower()   全体小写
    
  3. 合并字符串
    1
    2
    3
    4
    
     message_1 = "hello word "
     message_2 = "python"
     print(message_1 + message_2)
     用 + 号来进行拼接
    
  4. 字符串换行与添加空白 print("\t python ") \t 对齐 \n 换行

  5. 字符串删除空白 ``` name.rstrip() 删除两端空白 name.lstrip() 删除开头空白

列表简介

列表是一类特定顺序排列的元素组成,可以将任何元素加入列表中,元素之间可以没有很合关系。用([])表示。 索引从零号位置开始,-2位置表示倒数第二位。 furits = ['apple','banana','orange'] furits = ('apple','banana','orange')

  1. 访问列表元素与使用列表元素 略
  2. 修改列表元素
    • 修改表中元素
      1
      2
      3
      
        furits = ('apple','banana','orange')
        fruits[0] = 'strawterry'
        print(fruits) #此时fruits列表已改变
      
    • 在表中添加元素
      • 在表末尾增加元素 name.append('apple')
      • 在列表中插入一个元素 name.insert(0,'apple')
    • 从列表中删除元素
      • del语句删除元素 del name[0] #删除某个元素
      • pop的用法 被弹出的元素不再存在与原来的列表之中 name_1 = name.pop() #弹出最后一个元素 name_1 = name.pop(0) #弹出指定位置的元素
      • remove的用法
        1
        2
        3
        
          furits = ('apple','banana','orange')
          furits.remove('apple') #根据值来删除元素,
          #若有多个相同的值,用while循环删除
        
  3. 组织列表
    • 使用sort()进行永久排序
      1
      2
      
        name.sort() #字母正向排序
        name.sort(reverse=True)#字母逆向排序
      
    • 使用sorted()对列表进行临时排序 ` sorted(name) #表中顺序并没有被改变 `
    • 使用reverse ()使列表永久倒叙排列 ` name.reverse()`
    • 确定表的长度 ` len(name) `

列表操作

  1. 遍历整个列表,有关for循环的用法
    1
    2
    3
    
      furits = ('apple','banana','orange')
      for fruit in furits :
         print (fruit) # 注意缩进与冒号的用法
    
  2. 创建数字列表
    • 有关range()函数的使用
      1
      2
      
        for value in range(1,5): #并不输出数字5
        print (value)
      
    • 使用list()函数创建数字列表 ``` number = lisr(range(1,5)) #创建一个1-4的数字列表 number = lisr(range(1,5,2))#创建一个以2为间隔的数字列表
    • 创建数字列表
      1
      2
      3
      4
      
        squraes  = []
        for value in range(1,5):
            square = value ** 2
            squares.append(square) #创建以数字平方的列表
      
    • 数字列表的简单统计
      1
      2
      3
      4
      
        digit = [1,2,3,4]
        sum(digit)
        max(digit)
        min(digit)
      
    • 列表解析 squares = [value**2 for value in range (1,11)]
  3. 使用列表的一部分
    • 切片
      1
      2
      3
      4
      
       print(name[1:4]) # 输出2-4个元素
       print(name[:4])  # 从头索引
       print(name[2:])  # 从第三个索引到最后一个
       print(name[-3:]) # 输出最后三个
      
    • 遍历切片 ` for name in names[:4]: `
    • 复制列表 ⭐⭐ ``` 试比较下列两种不同的代码复制表述 my_foods = [‘apple’,’oranges’,’banana’] friend_foods = my_foods my_foods.append (‘subbary’) friend_foods.append(‘subbary_1’) print(my_foods) print(friend_foods)

    name = input(“请输入你的名字”) print (name)

    age = input (“请出入你的年龄”) age = int(age) # 用int()将字符串类型转为数值 ```

  4. while循环
    • 基础循环
      1
      2
      3
      4
      
       a = 10
       while a > 1:
        print (a)
        a=a-1 
      
    • 让用户选择何时退出循环
      1
      2
      3
      4
      5
      
       message = ""
       while message != 'quit':
        message=input('请输入文本')
        if message != 'quit': #使用if语句,避免出现输出quit。
            print (message)
      
    • 设置标志位
      1
      2
      3
      4
      5
      6
      7
      
       active = True
       while active:
        message=input('请输入文本')
        if message == 'quit':
            active = False
        else:
            print(message)
      
    • break 与 continue 语句 略 p109
  5. 用while循环处理列表与字典
    • 列表之间移动元素
      1
      2
      3
      4
      5
      6
      7
      
        un_user = ['1','2','3','4']
        user = []
        while un_user:
            temp = un_user.pop()
            user.append(temp)
        print(un_user)
        print(user)       
      
  6. 删除多个相同值的列表元素
    1
    2
    3
    4
    
         un_user = ['1','2','2','3','4']
         while '2' in un_user :
             un_user.remove('2')
         print (un_user)
    
  7. 使用户的输入来进行字典填充 略 P112

函数

1
2
3
4
5
6
7
8
9
10
```
一个简单的函数实例
def greet(name):
    print("hello "+name.title()+"!")
greet('xyx')
``` 1. 有关函数默认值
`def greet(name_1,name_2 = 'xyx'):`

`greet(name_1):  或者 greet(name_1,name_2):`
第二个参数为默认值,调用实例如下,显示的给出参数,python将默忽略这个默认值。
  1. 返回值
    1
    2
    3
    4
    5
    6
    
     def full_name (first_name,last_name):
         f_name = first_name + last_name
         return f_name.title()
    
     name = full_name('zhou','jielun')
     print (name)
    
  2. 让实参变成可选的
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
     def full_name (first_name,last_name,mid_name=''):
         if mid_name:
             f_name = first_name + mid_name + last_name
         else:
             f_name = first_name + last_name
         return f_name
    
     name = full_name('jay','chou')
     name_1 = full_name('jay','chou','love')
     print(name,name_1)
     第三位可选,可不选,mid_name=''表示。
    
  3. 返回字典类型 P124 略

  4. 传递列表
    1
    2
    3
    4
    5
    6
    
     def greet (names):
         for name in names:
             msg = 'hello' + name.title
             print(msg)
     d_name = ['jay','chou']
     greet (d_name)
    
  5. 在函数中修改列表
    • 将列表传递给函数后,函数就可以对其进行修改,函数对列表的修改都是永久性的。
  6. 禁止函数修改列表
    • 复制列表副本
  7. 传递任意数量的实参
    1
    2
    3
    4
    5
    6
    7
    
     //列表类型的多个参数
     def f_fruits (*fruits):
         for fruit in fruits:
             print(fruit)
    
     f_fruits('apple','banana','orange') #多个参数传递
     f_fruits('apple') #单个参数传递
    

    ``` //字典类型的多个参数传递 双-表示 ⭐⭐ def name_1 (f_name,l_name,else_inf): name = {} name[‘first_name’] = f_name name[‘last_name’] = l_name for key,value in else_inf.items(): name[key] = value print (name)

    name_1(‘jay’,’chou’,loc=’wuhan’,tel=’132’)

  8. 函数的模块化思想
    • 导入函数 import + 文件名
      • 导入特定函数 ` from + 文件名 + import + 函数名`
    • as 给函数起别名 ` from + 文件名 + import + 函数名 + as 别名`
    • as 给模块其别名 import + 文件名 + as 别名 +导入模块中的所有函数 from + 文件名 + import + *

  1. 创建类
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    
     class Dog ():
         def __init__(self,name,age):
             """初始化属性name和age"""
             self.name = name
             self.age = age
    
         def sit(self):
             """模拟小狗下蹲"""
             print(self.name.title()+"is now sitting")
    
         def roll(self):
             """模拟小狗打滚"""
             print(self.name.title()+"rolled over")
    
  2. 类的调用方法
    1
    2
    3
    4
    
     class Dog()
     my_dog = Dog ('jack',6)
     my_dog.name   #访问属性
     my_dog.sit()    #调用sit()
    
  3. 使用类和实例
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    
     class Car ():
         def __init__(self,make,modle,year):
             self.make = make
             self.modle = modle
             self.year = year
             self.mile = 0  #可以添加默认属性
         def get_des(self):
             long_name = str(self.year) + self.make + self.modle
             return long_name
         def get_mile(self):
             print(self.mile)
                
     my_new_car = Car ('audi','a4',2016)
     print(my_new_car.get_des())
     my_new_car.get_mile()  #打印里程数
    
  4. 修改属性值
    • 直接修改
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      
        class Car ():
            def __init__(self,make,modle,year):
                self.make = make
                self.modle = modle
                self.year = year
                self.mile = 0  #可以添加默认属性
            def get_des(self):
                long_name = str(self.year) + self.make + self.modle
                return long_name
            def change_mile(self,mile_1):
                self.mile = mile_1
            def get_mile(self):
                print(self.mile)
                      
        my_new_car = Car ('audi','a4',2016)
        print(my_new_car.get_des())
        my_new_car.change_mile(23)  #更改公里数
        my_new_car.get_mile()  #打印里程数
      

      可对里程增加函数进行扩展,使用if判断语句块使里程只能前进不能够后退调整。

      1
      2
      3
      4
      5
      
        def change_mile(self,mile_1):
        if mile_1 > self.mile:
            self.mile = mile_1
        else:
            print("你输入的里程有误")
      

      将里程表读数增加指定量

      1
      2
      
        def increa (self,mile_1):
        self.mile = self.mile+mile_1
      
  5. 继承 子类继承其父类所有的属性,同时还可以定义自己的属性和方法
    • 继承 ``` #继承父类的属性 class Car (): –>–

    class Electri_car (Car): def init(self,make,modle,year): #调用Electri_car的父类 super().init(make,modle,year) #super()函数继承 my_tesla = Electri_car(‘telsa’,’-4’,6) print(my_tesla.get_des())

    1
    
     + 给子类定义属性和方法
    

    #继承父类的属性 class Electri_car (Car): def init(self,make,modle,year): #调用Electri_car的父类 super().init(make,modle,year) self.bettery = 70 def des_bettery (self): #增加属性 print(self.bettery)

    my_tesla = Electri_car(‘telsa’,’telsa_4’,2016) my_tesla.des_bettery()

    1
    
     + 重写父类的方法
    

    class Electri_car (Car): –> def fill_gas(self): “"”电动汽车没有油箱””” print(“电动汽车没有油箱”) ``` 有关解释,如果有人对电动汽车这一类调用了fill_gas函数,python将自动忽略父类(CAR)中的fill_gas函数,在使用继承使,让子类可以保留父类中的精华,而去其糟怕。⭐⭐

  6. 将实例用作属性 ⭐⭐

  7. 导入类
    • 导入单个类
      1
      2
      3
      
       from car import Car
       my_newcar = Car('audi','a4',2016)
       print(my_newcar.get_des())
      
    • 从一个模块中导入多个类 from car import Car,ElectricCar
    • 导入整个模块
      1
      2
      
       import car
       my_car = car.Car('','','') #用句点表示访问需要的类
      
    • 在一个模块中导入另一个模块 有时候模块太大,你会发现一个模块中的类依赖于另一个模块中的类,这种情况下,前一个模块必须导入必要的类。 ``` from car import Car

    class ElextricCar() class BatteryCar() #最后两类需要访问其父类Car,所以要将car导入其中。

#文件

  1. 读取整个文件
    1
    2
    3
    
     with open('pi.txt') as pi:
         contents = pi.read()
         print(contents.rstrip())
    

    利用文件路径打开文件

    1
    2
    3
    4
    5
    
     file_path = 'D://安装//vscode安装//python//pi.txt'
     """ 注意 文件路径用双反斜杠,否则会报错"""
     with open(file_path) as pi:
         contents = pi.read()
         print(contents.rstrip())
    

    逐行读取

    1
    2
    3
    4
    
     file_path = 'D://安装//vscode安装//python//pi.txt'
     with open(file_path) as pi:
         for line in pi:
             print(line.strip())
    
  2. 利用列表存储文件内容
    • open返回的文件,只能在with代码块内使用。要想在with代码块外使用,必须存储在一个列表之中。
      1
      2
      3
      4
      5
      
       file_path = 'D://安装//vscode安装//python//pi.txt'
       with open(file_path) as pi:
        lines = pi.readlines()
       for line in lines:
        print(line.strip())
      

      readlines()从文件中读取每一行,并将其存储到一个列表中。

  3. 使用文件内容
    1
    2
    3
    4
    5
    6
    7
    8
    
     file_path = 'D://安装//vscode安装//python//pi.txt'
     with open(file_path) as pi:
         lines = pi.readlines()
     f_pi = ''
     for line in lines:
         f_pi += line.strip()
     print(f_pi)
     print(len(f_pi))
    
  4. 写入文件 1.写入空文件夹,如果文件夹没有建立,python将自动建立文件夹。
    1
    2
    3
    
     file_path = 'love.txt'
     with open(file_path,'w') as pi:
         pi.write("i love you")
    

    with open(file_path,’w’) as pi: ‘w’ 为写入模式,’r’为只读模式,’r+’为读取写入模式,’a’为附加模式。

  5. 多行写入
    1
    2
    3
    4
    
     file_path = 'love.txt'
     with open(file_path,'w') as pi:
         pi.write("i love you\n")
         pi.write("i love you too\n")
    
  6. 附加到文件 不会覆盖原有内容,在末尾新增内容,’a’。
    1
    2
    3
    4
    
     file_path = 'love.txt'
     with open(file_path,'a') as pi:
         pi.write("i love you\n")
         pi.write("i love you too\n")
    
  7. 分析文本 利用split()创建一个单词列表
    1
    2
    3
    
     title = "how old are you"
     print(title.split())
     --> ['how', 'old', 'are', 'you']
    

    如何读取一本书里有多少单词

    1
    2
    3
    4
    5
    
     flie_name = 'love.txt'
     with open(flie_name) as j:
         contents = j.readline()
     number = contents.split()
     print(len(number))
    
  8. 利用json存储数据
    • 利用json.dump 存储 ``` import json number = [2,3,4,5,6]

    file_name = ‘number.json’ with open(file_name,’w’) as j: json.dump(number,j)

    1
    
     + 利用json.load 来读取数据
    

    import json file_name = ‘number.json’ with open(file_name) as j: load_number = json.load(j) print(load_number) ```

异常

  1. try except 语句
    1
    2
    3
    4
    5
    
     try:
         print(5/0)
     except:
         print("输入的参数有误")
    
    
  2. try - except - else 语句
    1
    2
    3
    4
    5
    6
    
     try:
         answer = 5/1
     except:
         print("输入的参数有误")
     else:
         print(answer)
    

    else 将执行 try 后的语句。

  3. try-except语句来处理找不到文件异常
    1
    2
    3
    4
    5
    
     try:
         file_path = 'D://安装//vscode安装//python//pi.txt'
         with open(file_path) as pi:
     else:
         print("文件异常,找不到文件。")
    
This post is licensed under CC BY 4.0 by the author.

Contents

Trending Tags