zoukankan      html  css  js  c++  java
  • 1.python基础—有这篇文章足够

    什么是编程语言?什么是编程?

    编程语言与人类语言类似,与中国交流用汉语,与美国人交流用英语。人类与计算机交流就需要用编程语言。

    编程 == 写代码,是一个动词,想让计算机干什么,就编写对应的代码。

     

    编程语言分类

    机械语言,直接对硬件操作,采用二进制数字。

    • 优点:最底层,速度最快

    • 缺点:复杂,开发效率低

    汇编语言,直接与硬件操作,采用英文缩写的标识符。

    • 优点:比较底层,速度快。

    • 缺点:复杂,开发效率低。

    高级语言,编写的程序不能直接被计算机识别,必须经过转换才能被执行。

    • 编译型语言执行速度快,不依赖语言环境运行,跨平台差

    • 解释性语言跨平台好,一份代码,到处使用,缺点是执行速度慢,依赖解释器运行。

     

    编程语言的流派(解释型、编译型)

    img

    • 编译类:一次性将代码编译为可以执行的文件,然后交给计算机执行。编译后的程序可以直接使用,执行效率高,依赖编译器,跨平台差。(C、C++、Delphi)

    • 解释类:类似同声翻译,程序一边执行一边翻译因此效率较低,没有生产独立的可执行文件,所以不能脱离其解释器运行(跟老外讲话翻译必须在场)。(Python、Java、PHP、Ruby)

     

    变量(储存数据的容器)

    • 使用规则:先定义后调用

    • 命名规则:

      1.字母、数字、下划线的任意组合。

      2.第一个字符不能是数字。

      3.不能使用关键字。

    变量创建的过程

    当我们定义name = 'shi'时,程序做了什么?

    1. 开辟一块内存空间

    2. 将’shi‘放进这个空间。

    3. 让name这个变量指向存放’shi‘的地址(内存地址)

      img

    • 查看内存地址(id)

    当修改变量的时候,程序做了什么?

    >>> name = "oldboy"
    >>> id(name)
    4317182304
    >>>
    >>> name = "alex"
    >>> id(name)  # 如果只是在原有地址上修改,那么修改后内存地址不应该变化呀。
    4317182360

    程序重新申请了一块内存地址,将alex放进去,变量的指向从oldboy断开,指向新的Alex的内存地址。

    img

    • 变量的指向关系

     

      >>> name1 = 'oldboy'
     >>> name2 = name1   # 把name1赋值给name2,这样name2的值也是oldboy了
     >>> print(name1,name2)
     oldboy oldboy
     >>>
     >>> name1 = 'alex'  
     >>> print(name1,name2) #改了name1后,name2为何没跟着改?
     alex oldboy

    img

    修改name1的值,相当于断开了name1到‘oldboy’的链接,重新建立name1和‘alex’之间的链接。在这个过程中,始终没有影响到name2和‘oldboy‘之间的关系,因此name2还是‘oldboy’,而name1变成了‘alex’。

    特性

    1. 有序

    2. 有索引

    3. 可以切片

    4. 不可变

    常用方法

    def capitalize(self):  
       首字母大写
    def casefold(self):  
       把字符串全变小写
       >> > c = 'Alex Li'
       >> > c.casefold()
       'alex li'
    def center(self, width, fillchar=None):  
       >> > c.center(50, "-")
       '---------------------Alex Li----------------------'
    def count(self, sub, start=None, end=None):  
       """
      S.count(sub[, start[, end]]) -> int
      >>> s = "welcome to apeland"
      >>> s.count('e')
      3
      >>> s.count('e',3)
      2
      >>> s.count('e',3,-1)
      2
    def encode(self, encoding='utf-8', errors='strict'):  
      """
       编码,日后讲
    def endswith(self, suffix, start=None, end=None):
       >> > s = "welcome to apeland"
       >> > s.endswith("land") 判断以什么结尾
       True
    def find(self, sub, start=None, end=None):  
       """
      S.find(sub[, start[, end]]) -> int
      Return the lowest index in S where substring sub is found,
      such that sub is contained within S[start:end]. Optional
      arguments start and end are interpreted as in slice notation.
      Return -1 on failure.
      """
       return 0
    def format(self, *args, **kwargs):  # known special case of str.format
       >> > s = "Welcome {0} to Apeland,you are No.{1} user."
       >> > s.format("Eva", 9999)
       'Welcome Eva to Apeland,you are No.9999 user.'
       >> > s1 = "Welcome {name} to Apeland,you are No.{user_num} user."
       >> > s1.format(name="Alex", user_num=999)
       'Welcome Alex to Apeland,you are No.999 user.'
    def format_map(self, mapping):  
       """
      S.format_map(mapping) -> str
      Return a formatted version of S, using substitutions from mapping.
      The substitutions are identified by braces ('{' and '}').
      """
       讲完dict再讲这个
    def index(self, sub, start=None, end=None):  
       """
      S.index(sub[, start[, end]]) -> int
      Return the lowest index in S where substring sub is found,
      such that sub is contained within S[start:end]. Optional
      arguments start and end are interpreted as in slice notation.
      Raises ValueError when the substring is not found.
      """
    def isdigit(self):  
       """
      S.isdigit() -> bool
      Return True if all characters in S are digits
      and there is at least one character in S, False otherwise.
      """
       return False
    def islower(self):  
       """
      S.islower() -> bool
      Return True if all cased characters in S are lowercase and there is
      at least one cased character in S, False otherwise.
      """
    def isspace(self):  
       """
      S.isspace() -> bool
      Return True if all characters in S are whitespace
      and there is at least one character in S, False otherwise.
      """
    def isupper(self):  
       """
      S.isupper() -> bool
      Return True if all cased characters in S are uppercase and there is
      at least one cased character in S, False otherwise.
      """
    def join(self, iterable):  
       """
      S.join(iterable) -> str
      Return a string which is the concatenation of the strings in the
      iterable. The separator between elements is S.
      """
       >>> n = ['alex','jack','rain']
       >>> '|'.join(n)
       'alex|jack|rain'
    def ljust(self, width, fillchar=None):  
       """
      S.ljust(width[, fillchar]) -> str
      Return S left-justified in a Unicode string of length width. Padding is
      done using the specified fill character (default is a space).
      """
       return ""
    def lower(self):  
       """
      S.lower() -> str
      Return a copy of the string S converted to lowercase.
      """
       return ""
    def lstrip(self, chars=None):  
       """
      S.lstrip([chars]) -> str
      Return a copy of the string S with leading whitespace removed.
      If chars is given and not None, remove characters in chars instead.
      """
       return ""
    def replace(self, old, new, count=None):  
       """
      S.replace(old, new[, count]) -> str
      Return a copy of S with all occurrences of substring
      old replaced by new. If the optional argument count is
      given, only the first count occurrences are replaced.
      """
       return ""
    def rjust(self, width, fillchar=None):  
       """
      S.rjust(width[, fillchar]) -> str
      Return S right-justified in a string of length width. Padding is
      done using the specified fill character (default is a space).
      """
       return ""
    def rsplit(self, sep=None, maxsplit=-1):  
       """
      S.rsplit(sep=None, maxsplit=-1) -> list of strings
      Return a list of the words in S, using sep as the
      delimiter string, starting at the end of the string and
      working to the front. If maxsplit is given, at most maxsplit
      splits are done. If sep is not specified, any whitespace string
      is a separator.
      """
       return []
    def rstrip(self, chars=None):  
       """
      S.rstrip([chars]) -> str
      Return a copy of the string S with trailing whitespace removed.
      If chars is given and not None, remove characters in chars instead.
      """
       return ""
    def split(self, sep=None, maxsplit=-1):  
       """
      S.split(sep=None, maxsplit=-1) -> list of strings
      Return a list of the words in S, using sep as the
      delimiter string. If maxsplit is given, at most maxsplit
      splits are done. If sep is not specified or is None, any
      whitespace string is a separator and empty strings are
      removed from the result.
      """
       return []
    def startswith(self, prefix, start=None, end=None):  
       """
      S.startswith(prefix[, start[, end]]) -> bool
      Return True if S starts with the specified prefix, False otherwise.
      With optional start, test S beginning at that position.
      With optional end, stop comparing S at that position.
      prefix can also be a tuple of strings to try.
      """
       return False
    def strip(self, chars=None):  
       """
      S.strip([chars]) -> str
      Return a copy of the string S with leading and trailing
      whitespace removed.
      If chars is given and not None, remove characters in chars instead.
      """
       return ""
    def swapcase(self):  
       """
      S.swapcase() -> str
      Return a copy of S with uppercase characters converted to lowercase
      and vice versa.
      """
       return ""
    def upper(self):  
       """
      S.upper() -> str
      Return a copy of S converted to uppercase.
      """
       return ""
    def zfill(self, width):  
       """
      S.zfill(width) -> str
      Pad a numeric string S with zeros on the left, to fill a field
      of the specified width. The string S is never truncated.
      """
       return ""

     

    常量:不变的量

     

    注释:

    1. 单行注释 #

    2. 多行注释 ''' ''' """ """

     

    数据类型

    什么是数据类型:计算机在底层只能认识二进制数字,所有输入的数据对于计算机没有什么不同,所以需要,事先告诉计算机输入的数据是什么?

    数字(int、float)

    • 整型(int),长整型(long),浮点型(float)

    字符串(str)

    • 在Python中加了引号的字符就是字符串。

    • 字符串拼接:

    name = 'spl' age = '25'
    name + age #相加就是进行简单的拼接
    name * 5 # 重复name五次然后拼接一起

    ** 字符串拼接的双方只能是字符串,不能和其他数据类型进行拼接。

    布尔型(bool)

    • True、False

    列表(list)

    • 列表通过下标来标记元素位置。

    元素名AlexJackRainRachelMack
    下标(索引) 0 1 2 3 4
    1. 插入(insert)

      names = ['Alex', 'Jack', 'Rain', 'Rachel', 'Mack'] 
      names.insert(3,'spl') #3代表插入的位置
      ['Alex', 'Jack', 'Rain','spl', 'Rachel', 'Mack']

      追加(append)

      names = ['Alex', 'Jack', 'Rain', 'Rachel', 'Mack'] 
      names.append('spl') ['Alex', 'Jack', 'Rain', 'Rachel', 'Mack','spl'] #追加到尾部

      合并(extend)

      names = ['Alex', 'Jack', 'Rain', 'Rachel', 'Mack'] 
      names2 = ["狗蛋","绿毛","鸡头"]
      names.extend(names2)
      ['Alex', 'Jack', 'Rain', 'Rachel', 'Mack',"狗蛋","绿毛","鸡头"]

      列表嵌套

      names2 = ["狗蛋","绿毛","鸡头"]
      name2.insert(2,['aa','bb'])
      ["狗蛋","绿毛",['aa','bb'],"鸡头"]

       

    2.改(找到下标直接赋值)

    name = ['Alex', 'Jack', 'Rain', 'Rachel', 'Mack'] 
    name[0] = 'shipinlei' 
    name = ['shipinlei','Alex', 'Jack', 'Rain', 'Rachel', 'Mack'] 
    

    3.删

    • 通过元素进行删除(remove)

    • 直接删除(del),通过索引

      • name = ['Alex', 'Jack', 'Rain', 'Rachel', 'Mack'] 
        del name[2]
        ['Alex', 'Jack', 'Rachel', 'Mack']
        
    • pop:删除并返回,默认删除最后一个,可以指定索引删除

      • names= ['Alex', 'Jack', 'Rain', 'Rachel', 'Mack'] 
        name = name.pop() #Mack
        name = name.pop(2) #Rain
        
    • 清空(clean)

      • names= ['Alex', 'Jack', 'Rain', 'Rachel', 'Mack'] 
        name.clean() #[]
        

    4.查

    • index查索引,并返回

    • count查元素个数,并返回

    5.切片

    name[start:end:步长] #步长为-1可以反转列表
    

    6.判断元素是否在列表里

    name = ['Alex', 'Jack', 'Rain', 'Rachel', 'Mack'] 
    'Alex' in name 
    

    7.排序(sort)、反转(reverse)

    元组(tuple)

    1. 与列表类似将[ ]改成()

    2. 特性

      1. 可以存放多个值

      2. 不可变

      3. 有序

    3. 元组本身不可变,如果元组中还包含其他可变元素,这些可变元素可以改变

    字典(dict)

    1. 特性

      1. key-value结构

      2. key必须是不可变类型、必须唯一

      3. 可以存放多个value,可修改,可以不唯一

      4. 无序

      5. 查询速度快,不受dict本身大小的影响。

    2. 增加

      names = {
          "alex": [23, "CEO", 66000],
          "黑姑娘": [24, "行政", 4000],
      }
      # 新增k
      names["佩奇"] = [26, "讲师", 40000]
      
    3. 删除

      names.pop("alex") # 删除指定key
      names.popitem()   # 随便删除1个key
      del names["oldboy"] # 删除指定key,同pop方法
      names.clear()     # 清空dict
      
    4. 修改

      dic['key'] = 'new_value'
      #如果key在字典中存在,'new_value'将会替代原来的value值;
      
      dic.update(dic2) 
      #将字典dic2的键值对添加到字典dic中
      

       

    5. dic['key'] #返回字典中key对应的值,若key不存在字典中,则报错;
      dic.get(key, default = None)#返回字典中key对应的值,若key不存在字典中,则返回default的值(default默认为None)
      'key' in dic #若存在则返回True,没有则返回False
      dic.keys() 返回一个包含字典所有KEY的列表;
      dic.values() 返回一个包含字典所有value的列表;
      dic.items() 返回一个包含所有(键,值)元组的列表;
      

    集合(set)

    • 特点

      1. 里面的元素不可变,不能存list、dict。

      2. 天生去重(帮列表去重)

      3. 无序

    • 增删查改(不能改)

      a = {1, 2, 3, 4, 'alex', 'rain'}
      a.add('大姑娘') #增
      a.discard('rain')#删除一个存在的值
      a.discard('rain2')   #如果这个值不存在,do nothing.
      a.pop()#随机删除并返回,少用,或特定场景用
      'alex' in a #查
      # 不能删除
      
    • 关系运算

      s_1024 = {"佩奇","老男孩","海峰","马JJ","老村长","黑姑娘","Alex"}
      s_pornhub = {"Alex","Egon","Rain","马JJ","Nick","Jack"}
      print(s_1024 & s_pornhub)  # 交集, elements in both set
      print(s_1024 | s_pornhub)  # 并集 or 合集
      print(s_1024 - s_pornhub)  # 差集 , only in 1024
      print(s_pornhub - s_1024)  # 差集,  only in pornhub
      print(s_1024 ^ s_pornhub)  # 对称差集, 把脚踩2只船的人T出去
      
      • 两个集合之间一般有三种关系,相交、包含、不相交。在Python中分别用下面的方法判断:

        print(s_1024.isdisjoint(s_pornhub))     # 判断2个集合是不是不相交,返回True or False
        print(s_1024.issubset(s_pornhub))       # 判断s_1024是不是s_pornhub的子集,返回True or False
        print(s_1024.issuperset(s_pornhub))     # 判断s_1024是不是s_pornhub的父集,返回True or False
        

         

    读取用户指令(input)

    ** input() 接收的只能是字符串,就算输入的数字,也会按字符串处理。

    **input接收的所有输入默认都是字符串格式!

     

    格式化打印

    name = input("Name:") 
    age = input("Age:") 
    job = input("Job:") 
    hobbie = input("Hobbie:") 
    info = ''' 
        ------------ info of %s ----------- 
        #这里的每个%s就是一个占位符,本行的代表 后面拓号里的 
        Name  : %s  #代表 name  
        Age  : %s  #代表 age  
        job  : %s  #代表 job  
        Hobbie: %s  #代表 hobbie  
        ------------- end ----------------- 
        ''' %(name,name,age,job,hobbie)  # 这行的 % 号就是 把前面的字符串 与拓号 后面的 变量 关联起来  print(info) 
    

    %s就是代表字符串占位符,除此之外,还有%d,是数字占位符,%f是浮点数占位符, 如果把上面的age后面的换成%d,就代表你必须只能输入数字啦

    运算符

    算数运算符

    img

    比较运算

    img

    赋值运算

    img

    逻辑运算

    img

    身份运算(is)

    • type()查看一个数据的数据类型

    • 判断一个数据类型是不是str等,可以使用身份运算is

    img

     

    流程控制

    if判断

    if 条件:   
    	满足条件后执行代码 
    elif 条件:   
    	满足条件后执行代码 。。。。。 
    else:   
    	上面条件都不满足执行代码  
    

    * **代码是从上到下依次判断,只要满足一个,就不会再往下走,这一点一定要清楚呀!*

    三元运算

    • 简单的if...else判断语句可以使用三元运算。

      name = "Eva"
      sex = None
      # 普通写法
      if name == "Eva":
          sex = "Female"
      else:
          sex = "Male"
      # 用三元运算来写
      sex = "Female" if name == "Eva" else "Male"
      

    while循环

    while 条件:
    	执行代码。。。 
    

    循环中止语句(continue、break)

    • continue:中止本次循环,继续后面的循环

    • break:中止当前循环

    while...else...

    • 当while循环正常执行完毕(没有被break),执行else后面的代码。

    什么是哈希(hash)

    就是一种算法

    哈希算法有一个很大的特点,就是你不能从结果推算出输入,所以又称为不可逆的算法

    哈希特性

    1. 不可逆

    2. 计算极快

    哈希的用途

    1. 密码

    2. 文件完整性校园

    3. 数字签名

      。。。。。

    基于hash的数据类型有哪些(dict,set)

    用python操作文件

    操作流程

    1. 找到文件双击打开

    2. 读或者修改

    3. 保存关闭

    4. f=open(filename)  # 打开文件
      f.write("我是野生程序员") # 写操作
      f.read()  #读操作
      f.close() #保存并关闭
      

    操作模式

    • r:只读模式

    • w:创建模式,若文件已经存在,则覆盖旧文件

    • a:追加模式

    创建文件

    f = open(file='D:/工作日常/staff.txt',mode='w')
    f.write("Alex  CEO  600
    ")
    f.write("黑姑娘  行政  5000
    ")
    f.close()
    

    只读模式

    f = open(file='兼职白领学生空姐模特护士联系方式.txt',mode='r')
    print(f.readline())  # 读一行
    print('------分隔符-------')
    data = f.read()  # 读所有,剩下的所有
    print(data)
    f.close()
    

    追加模式

    f = open(file='兼职白领学生空姐模特护士联系方式.txt',mode='a')
    f.write("黑姑娘 北京  168  48
    ")  # 会追加到文件尾部
    f.close()
    

    循环文件

    f = open(file='兼职白领学生空姐模特护士联系方式.txt',mode='r')
    for line in f:
        line = line.split()
        name,addr,height,weight,phone = line
        height = int(height)
        weight = int(weight)
        if height > 170 and weight <= 50:
            print(line)
    f.close()
    

    其他功能

    def mode(self) -> str:
            返回文件打开的模式
        def name(self) -> str:
            返回文件名
        def fileno(self, *args, **kwargs): # real signature unknown
            返回文件句柄在内核中的索引值,以后做IO多路复用时可以用到
        def flush(self, *args, **kwargs): # real signature unknown
            把文件从内存buffer里强制刷新到硬盘
        def readable(self, *args, **kwargs): # real signature unknown
            判断是否可读
        def readline(self, *args, **kwargs): # real signature unknown
            只读一行,遇到
     or 
    为止
        def seek(self, *args, **kwargs): # real signature unknown
            把操作文件的光标移到指定位置
            *注意seek的长度是按字节算的, 字符编码存每个字符所占的字节长度不一样。
            如“路飞学城” 用gbk存是2个字节一个字,用utf-8就是3个字节,因此以gbk打开时,seek(4) 就把光标切换到了“飞”和“学”两个字中间。
            但如果是utf8,seek(4)会导致,拿到了飞这个字的一部分字节,打印的话会报错,因为处理剩下的文本时发现用utf8处理不了了,因为编码对不上了。少了一个字节
        def seekable(self, *args, **kwargs): # real signature unknown
            判断文件是否可进行seek操作
        def tell(self, *args, **kwargs): # real signature unknown
            返回当前文件操作光标位置 
        def truncate(self, *args, **kwargs): # real signature unknown
            按指定长度截断文件
            *指定长度的话,就从文件开头开始截断指定长度,不指定长度的话,就从当前位置到文件尾部的内容全去掉。
        def writable(self, *args, **kwargs): # real signature unknown
            判断文件是否可写
    

    混合模式

    w+ 写读 , 这个功能基本没什么意义,它会创建一个新文件 ,写一段内容,可以再把写的内容读出来,没什么卵用。

    r+ 读写,能读能写,但都是写在文件最后,跟追加一样

    a+ 追加读,文件 一打开时光标会在文件尾部,写的数据全会是追加的形式

    占用硬盘的方式修改文件

    import os
    f_name = "兼职白领学生空姐模特护士联系方式.txt"
    f_new_name = "%s.new" % f_name
    old_str = "刘诺涵"
    new_str = "[黑姑娘]"
    f = open(f_name,'r')
    f_new = open(f_new_name,'w')
    for line in f:
        if old_str in line:
            new_line = line.replace(old_str,new_str)
        else:
            new_line = line
        f_new.write(new_line)
    f.close()
    f_new.close()
    os.rename(f_new_name,f_name) #把新文件名字改成原文件 的名字,就把之前的覆盖掉了,windows使用os.replace # 帮助文档说明replace会覆盖原文件
    
  • 相关阅读:
    【面试】代码默写-DCL单例
    【状态机】SCXML2
    【面试】JVM
    【面试】HashMap
    读取resource下sql脚本并执行
    Maven 二进制资源文件(excel pdf...)部署出错,乱码的解决方案
    【JVM】java内存模型
    【Spring】源码二、IOC
    mapstruct 高级用法
    warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 6.0, but the range of supported deployment target versions is 8.0 to 13.2.99.
  • 原文地址:https://www.cnblogs.com/shi-py-rengongzhineng/p/13983126.html
Copyright © 2011-2022 走看看