cpsc 103 python基本前提

发布时间 2023-10-10 17:58:59作者: zzhou75

python基本知识

基本运算符

1.(**)是次方

ex:2 ** 3 evaluates to (2 to the power of 3)8

2.(%)是求余数

ex:15 % 4 evaluates to because the remainder when dividing 15 by 4 is 33

基本运算规则

1.str 乘以数字

ex:'hello'*2 evalutes to 'hellohello'

2.[a?️c] a:起点 b:终点(不包含) c:步子大小(非必须)

ex:
'hello world'[10:0:-1]evaluates to 'dlrow olle'
'hello world'[::-1] evaluates to 'dlrow olleh'
'hello world'[10:0:-2]evaluates to 'drwol'
'hello'[0:2] evaluates to 'he'
'hello'[1:4] evaluates to 'ell'
'hello world'[0:10:2] evaluates to 'hlowr'
'hello world'[1:8:3]evaluates to 'eoo'

python内置函数【primitive functions】

  1. len()读取字符串长度
  2. max()&min()返回最大值/最小值
  3. list.append 在原list之后添加新的字符串

课程书写要求HtDF

Notation and Naming Conventions for Functions

1.the @typecheck annotation must be present in all functions

2.All function names should be lowercase with each new word separated by an underscore “_”

3.All function parameter names should be lowercase. A meaningful parameter name will suggest what that parameter represents.

4.Below the def line, there must be a concise purpose statement enclosed by triple quotations:

5.All local variables names should be lowercase

Examples should be written below the function inside of a code block that begins with start_testing() and ends with summary()

@typecheck#1
     #2                   #3
def booster_needed(msld: MonthsSinceLastDose) -> bool:
    """
#4  returns True if 6 or more months have elapsed since the last dose, 
    or if the vaccination status is unknown. Otherwise, returns False.
    """
    if msld is None:
        return True
    else:
        return msld >= 6
start_testing()#6

expect(booster_needed(None), True)
expect(booster_needed(0), False)
expect(booster_needed(5), False)
expect(booster_needed(6), True)
expect(booster_needed(999), True)

summary()

课程书写要求HtDD

Notation and Naming Conventions for Data Definitions

1.All data type names should be written in UpperCamelCase (no underscores), where the first letter of each new word is in uppercase.

2.All examples should be written in UPPERCASE (often using an abbreviation of the data type's capital letters)

3.The template function name begins with fn_for_[data type name] all lowercase, with underscores separating new words

4.The parameter name in the template function is written in lowercase and is usually an abbreviate of the data type's capital letters.

#1
AccountValue = float#simple automic data

#interpr. the value held by a bank account
#examples

AV0 = 0
AV_POS = 1500.55
AV_NEG = -300.10#2

@typecheck       
#template based on simple automic data
     #3              #4
def fn_for_accountvalue(a:AccountValue)->...:
    return...(x)