p2s学习笔记第四录

发布时间 2023-12-02 19:27:26作者: LPF0502

datawhale p2s 学习chapter_5与chapter_6

chapter_5:循环

for循环

for循环和循环范围

  1. 特点

    基于提供的范围,重复执行特定次数的操作

  2. range默认参数

    range(a,b,c)

    • a为起始值,b为终值+1,c为步长
    • a如果不写,默认为0
    • c不写默认为1

for循环嵌套

a = 5
b = 5
for i in range(a):
    for j in range(b):
        print(a,b)

while循环

  1. 特点

    未知执行次数,依靠条件判断是否继续执行

  2. 在范围已知与未知时都可用while循环

break 与 continue 语句

假死循环

  1. 特点

    与环境交互后,在特定条件下终止的循环

  2. 简单示例

    def readUntilDone():
    linesEntered = 0
    while True:
        response = input("输入一个字符串(输入 done 则退出): ")
        if response == "done":
            break
        print("你输入了: ", response)
        linesEntered += 1
    print("Bye!")
    return linesEntered
    

chapter_6:字符串

字符串文字

  1. 引号

    • 单引号
    • 双引号
    • 三引号
    " "
    ' '
    ''' '''
    """ """
    
  2. 转义序列

    • \n 换行符
    • \t 制表符
    • " 双引号
    • \\ 反斜线
  3. 在多行文本中可用\来排除换行

    print("""你可以在字符串后面使用 反斜杠 `\`  来排除后面的换行。\
    比如这里是第二行文字,但是你会看到它会紧跟在上一行句号后面。\
    这种做法在 CIL 里面经常使用(多个 Flag 并排保持美观),\
    但是在编程中的应用比较少。\
    """)
    
  4. 多行字符串作为注释

    """
    Python 本身是没有多行注释的,
    但是你可以用多行字符串实现同样的操作,
    还记得我们之前学过的“表达式“吗?
    它的原理就是 Python 会运行它,
    但是马上扔掉!(垃圾回收机制)
    """
    
  5. repr()函数

    转义字符显示

    str = data\nwhale
    print(repr(str))
    '''
    有repr()显示
    data\nwhale
    #无repr()显示
    data
    whale
    '''
    

字符串常量

  1. 字母

    import string
    print(string.ascii_letters)
    #abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
    
  2. 小写字母

    print(string.ascii_lowercase)
    #abcdefghijklmnopqrstuvwxyz
    
  3. 大写字母

    print(string.ascii_uppercase) 
    #ABCDEFGHIJKLMNOPQRSTUVWXYZ
    
  4. 数字

    print(string.digits)
    #0123456789
    
  5. 特殊字符

    print(string.punctuation)
    #!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
    
  6. 可打印字符

    print(string.printable)
    #0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
    #!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ 
    
  7. 空白字符

    print(string.whitespace)
    
  8. 空白字符不转义

    print(repr(string.whitespace))
    #\t\n\r\x0b\x0c
    

字符串运算

  1. 简单运算

    print("abc" + "def")
    print("abc" * 3)
    #abcdef
    #abcabcabc
    
  2. in运算

    print("ring" in "strings") # True
    print("wow" in "amazing!") # False
    print("Yes" in "yes!") # False
    print("" in "No way!") # True
    print("聪明" in "聪明办法学 Python") # True
    
  3. 字符串索引和切片

    字符串可作为迭代对象

字符串循环

  1. in循环

    for c in s:
    print(c)
    
  2. enumerate函数

    for idx, c in enumerate(s):
    print(idx, c)
    '''
    0 D
    1 a
    2 t
    3 a
    4 w
    5 h
    6 a
    7 l
    8 e
    '''
    
  3. zip函数

    zip(a,b)可以在一次循环中,分别从 a 和 b 里同时取出一个元素

    for a, b in zip(s, reverseString(s)):
    print(a, b)
    '''
    D e
    a l
    t a
    a h
    w w
    h a
    a t
    l a
    e D
    '''
    
  4. split函数来循环

    # class_name.split() 本身会产生一个新的叫做“列表”的东西,但是它不存储任何内容
    
    class_name = "learn python the smart way 2nd edition"
    for word in class_name.split():
        print(word)
    '''
    learn
    python
    the
    smart
    way
    2nd
    edition
    '''
    
  5. splitlines函数来循环

    # class_info.splitlines() 也会产生一个列表,但不存储任何内容
    
    class_info = """\
    聪明办法学 Python 第二版是 Datawhale 基于第一版教程的一次大幅更新。
    
    我们的课程简称为 P2S,有两个含义:
    Learn Python The Smart Way V2.
    Prepare To Be Smart. 我们希望同学们学习这个教程后能学习到聪明的办法,从容的迈入人工智能的后续学习。
    """
    
    for line in class_info.splitlines():
        if (line.startswith("Prepare To Be Smart")):
            print(line)
    
    '''
    Prepare To Be Smart, 我们希望同学们学习这个教程后能学习到聪明的办法,从容的迈入人工智能的后续学习。
    '''
    

字符串内置函数与方法

字符串函数

  1. str() 和 len()

    str 函数将其他类型转化为字符串

    len 函数获得迭代对象长度

  2. chr() 和 ord()

    chr 函数将ascii码转化为对应字符

    ord 函数将字符转化为对应ascii码

  3. ast.literal_eval()

    安全地执行字符串中的Python表达式,而不会执行任何可能存在的恶意代码。

字符串方法

  1. isalnum()

  2. isalpha()

  3. isdigit()

  4. islower()

  5. isspace()

  6. isupper()

  7. strip()

    可以将字符串首尾的空格删除

  8. count()

  9. startwith()

    print("Dogs and cats!".startswith("Do"))
    print("Dogs and cats!".startswith("Don't"))
    #True False
    
  10. endwith()

    print("Dogs and cats!".endswith("!"))
    print("Dogs and cats!".endswith("rats!"))
    #True False
    
  11. find()

    print("Dogs and cats!".endswith("!"))
    print("Dogs and cats!".endswith("rats!"))
    # 5 -1
    
  12. index()

    print("Dogs and cats!".index("and"))
    print("Dogs and cats!".index("or"))
    # 5
    
  13. with语句