p2s学习笔记第三录

发布时间 2023-11-28 18:39:05作者: LPF0502

datawhale p2s 学习chapter_4与选学01

chapter_4:条件

if语句

  1. if语句

    if x == 0:
        print(a)
    
  2. if-else 语句

    if x == 0: 
        print("B", end="")
    else:
        print("D", end="")
    

    abs转换示例

    def abs(n):
        if n >= 0:
            sign = +1
        else:
            sign = -1
        return sign * n
    
  3. if-elif-else 语句

    print("A", end="")
    if x == 0:
        print("B", end="")
    elif x == 1:
        print("D", end="")
    else:
        print("E", end="")
    
  4. 一元二次方程示例

    求一元二次方程实数根数

    def numberOfRoots(a, b, c):
    # 返回 y 的实数根(零点)数量: y = a*x**2 + b*x + c
    d = b**2 - 4*a*c
    if d > 0:
        return 2
    elif d == 0:
        return 1
    else:
        return 0
    
  5. if-else 推导式

    print(n if (n >= 0) else -n)
    

match-case语句

Http响应状态码

  1. Http响应码示例

    match 后的对象会依次与 case 后的内容进行匹配,如果匹配成功,则执行匹配到的表达式,否则直接跳过,_ 可以匹配一切。

    def http_error(status):
        match status:
            case 400:
                return "Bad request"
            case 404:
                return "Not found"
            case 418:
                return "I'm a teapot"
            case _:
                return "Something's wrong with the internet"
    
    mystatus=400
    print(http_error(mystatus))
    #输出 Bad request
    
  2. 一个 case 也可以设置多个匹配条件,条件使用 | 隔开

    ...
    case 401|403|404:
        return "Not allowed"
    

选学01:代码style

代码风格

修饰的前提时能跑通

代码布局

  1. 缩进

    • 如果开局有定界符,其余缩进需与开始定界符(例如括号)对齐
    a = function(accd,
                 eeef)
    
    • 需要一个4个空格(长度等于1个制表符),以区分传入参数和其他内容
    def function(
            accd,eeef,
            hijk)
        print(accd)
    
    
    if (function(accd,eeef,hijk)
            and a==0):
        print(accd)
    
    • 空格一般用于添加以上缩进,tab键一般保持行与行间的一致。
    • 多行if语句衔接,需要一个额外的缩进区分。
  2. 换行

    • 所有行限制最多79个字
    • 一般语句接受"隐式"显示,with语句不支持,需要用 \ 来衔接
    with open(                          ) as file_1, \
    open(                          ) as file_2: 
        file_2.write(file_1.read())
    
    • 如果一项参数需要单独成行时,符号跟在参数前
    income = (gross_wages
              + taxable_interest
              +(dividends - qualified_dividends)
              - ira_deduction
              - student_loan_interest)
    

导入规范

  1. 导入本地同目录下封装好的模块或者文件,直接导入即可

  2. 导入子目录下封装好的模块或者文件,需声明子目录名

    form branch import m3
    

空格

  1. 紧接在括号内,不需要多余空格
  2. 在逗号,分号或冒号之前,尾随逗号之后均不需要多余空格
  3. 在切片中,两个冒号必须应用相同的间距
  4. 紧接在开始函数调用的参数列表在左括号之前,不需要多余空格
  5. 赋值或其他运算符周围需要多个空格以使其与另一个运算符对齐,在同时拥有不同级别运算符时,在优先级较低的符号加空格

注释

  1. 在有处理逻辑代码中,源程序有效注释量必须在20%以上。
  2. 写注释文档时用```

命名规范

  1. 不要将关键字和函数名用作变量名。
  2. 变量名和函数名应既简短又具有描述性
  3. 分号可以做隔断,换行自动添加分号