美文网首页
Python 3 笔记 - 第1章 基本语法

Python 3 笔记 - 第1章 基本语法

作者: 小叶与小茶 | 来源:发表于2018-06-22 11:48 被阅读16次

    Python 3 相对于 Python 2 是一个较大的升级,在设计的时候并没有考虑向下兼容,不少语法都有差异。而我是 Python 的新手,因此也直接从新一代的 Python 3 版本学起。这套学习笔记,如果没有特殊说明,提到 Python 就是指 Python 3 版本。

    关于 Python 的安装和环境变量的配置方法,无论是在 Windows ,还是 MacOS 或 Linux 都比较简单,网上也有很多教程,我就不再赘述了。

    几个不错的 Python 3 基础知识学习网站:

    另外,我的入门参考书是 Eric Matthes 的《Python编程从入门到实践》,这是一本明星图书。作者是一个数学老师,兼职教授 Python。我喜欢 Eric 轻松、实用、简单的文字风格。书中项目实践例子是“外星人入侵”和“数据可视化”,后者是 Python 的一个重要应用场景,而我则希望能够借助前者,用寓教于乐的方式来让儿子接触和喜欢上编程。不多说了,给这本书作个小小的广告。

    Python编程从入门到实践

    在进入正题之前,让我们看看 Tim Perters 写的那段著名的 “Python 之禅”

    import this

    The Zen of Python, by Tim Peters

    eautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    That way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than right now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!

    Python 之禅 by Tim Perters

    优美胜于丑陋
    明了胜于晦涩
    简洁胜于复杂
    复杂胜于凌乱
    扁平胜于嵌套
    间隔胜于紧凑
    可读性很重要
    即便假借特例的实用性之名,也不可违背这些规则
    不要包容所有错误,除非你确定需要这样做
    当存在多种可能,不要尝试去猜测
    而是尽量找一种,最好是唯一一种明显的解决方案
    虽然这并不容易,因为你不是 Python 之父(这里的 Dutch 是指 Guido)
    做也许好过不做,但不假思索就动手还不如不做
    如果你无法向人描述你的方案,那肯定不是一个好方案
    命名空间是一种绝妙的理念,我们应当多加利用

    开启 Python 之旅


    1. Python 保留字

    Python 标准库提供了一个 keyword 模块,可以输出当前版本的所有关键字:

    >>> import keyword
    >>> keyword.kwlist

    ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']


    2. 缩进

    使用缩进来代表代码块,而不是用 “{}” 是 Python 最大的特色。用编译层级的手段来强制你写出规范,层次清晰的代码。

    不过,缩进的空格数并未强制要求是4个,但是,同一逻辑层级的,也就是同一代码块的语句缩进必须完全一致。我们来体会一下这种“变态”。

    # 1. 同一逻辑层级,缩进空格数相同,没有问题
    if True :
            print("You are right")  # 我是7个空格
            print("You are right")  # 我是7个空格
         
    # 2. 同一逻辑层级,缩进空格数不同,编译错误
    if True :
            print("You are right")   # 我是7个空格
             print("You are right")  # 我是8个空格
     
    >>> IndentationError: unexpected indent
    
    # 3. 缩进空格数和任何一个代码块都不能匹配,编译错误
    if True :
        print("You are right")
    else :
        print("You are wrong")
      
      print("Am I right")   # 我跟哪段逻辑都不搭界
      
    >>> IndentationError: unindent does not match any outer indentation level  
    

    4. 基础数据类型

    Python 有6种基础数据类型

    • Number,数值类型
    • String,字符串类型
    • List,列表类型
    • Tuple,元组类型
    • Dictionary,字典类型
    • Set,集合类型

    其中

    • 不可变的有四种:Number,String,Tuple,Set
    • 可变的有两种:List,Dictionary

    其中 Number 和 String 不过多写了,就挤在本章中,剩下的4种集合类型,单独章节记笔记。


    4. 数值类型

    Python 有4种基本的数值类型:

    • int,整型,Python 3 中不区分整型和长整型,统一都为长整型
    • bool,布尔型,True 和 False
    • float,浮点型,如1.23,2E-2
    • complex,复数型,如 1+2j,1.1+2.2j

    Python 不需要对变量进行声明,但在使用变量之前,必须对其进行赋值。

    • 数值的除法包含两个运算符:/ 返回一个浮点型,// 返回一个整型
    • 在混合计算时,Python 会把整型转换成为浮点型
    >>> 1 + 2.0    # 混合计算时自动转换为浮点型
    3.0
    >>> 4 / 2      # “/” 代表直接相除,结果为浮点型
    2.0
    >>> 3 // 2     # “//” 代表取整,结果为整型
    1
    >>> 15 % 4     #取模
    3
    >>> 2 ** 5     # 乘方
    32
    

    Python 提供了 type() 函数,可以查询变量的类型

    # 使用 type() 函数查询变量类型
    a = 1
    b = 1.0
    c = True
    d = 1 + 2j
    
    print(type(a), type(b), type(c), type(d), type(e))
    

    执行结果为:

    <class 'int'> <class 'float'> <class 'bool'> <class 'complex'>
    

    5. 字符串

    说到字符串,各家编程语言都喜欢做做文章。Python 也不例外,其字符串截取(或者叫作“字符串片段”)语法挺有特色,体现了 Python 的极简设计思路。

    • 表示字符串时,不必刻意区分单引号和双引号。
    • 没有字符类型,1个字符就是长度为1的字符串。
    • 使用 “+” 连接多个字符串,使用 “*” 重复字符串。
    • 字符串有两种索引方式,从左往右以 0 开始,从右往左以 -1 开始。
    • 字符串截取的语法格式为:变量[头下标:尾下标],下标为正数代表从左数,下标为负数代表从右数。截取的字符串包含左下标代表的字符,不含右下标代表的字符。
    # 字符串截取
    str="Andy Zhang"
    
    print(str)                 # 输出字符串
    print(str[0:])             # 输出第一个到后面所有字符
    print(str[0:-1])           # 输出第一个到倒数第二个的所有字符
    print(str[0:-2])           # 输出第一个到倒数第三个的所有字符
    print(str[0])              # 输出第一个字符
    print(str[0:6])            # 输出第一个开始到第六个的字符
    print(str[2:])             # 输出第三个到后面所有字符
    

    执行结果为:

    Andy Zhang
    Andy Zhang
    Andy Zhan
    Andy Zha
    A
    Andy Z
    dy Zhang
    

    需要注意的是,字符串是常量,不能改变其中的字符

    str = "Hello"
    print(str)
    
    str[1] = 'a'
    print(str)
    

    执行结果为:

    str[1] = 'a'
    TypeError: 'str' object does not support item assignment
    

    相关文章

      网友评论

          本文标题:Python 3 笔记 - 第1章 基本语法

          本文链接:https://www.haomeiwen.com/subject/sahkyftx.html