• python 基础语法及保留字


    编码

    默认情况下,Python 3 源码文件以 UTF-8 编码,所有字符串都是 unicode 字符串。 当然你也可以为源码文件指定不同的编码:

    # -*- coding: cp-1252 -*-
    
    • 1

    上述定义允许在源文件中使用 Windows-1252 字符集中的字符编码,对应适合语言为保加利亚语、白俄罗斯语、马其顿语、俄语、塞尔维亚语。

    标识符

    • 第一个字符必须是字母表中字母或下划线 _ 。
    • 标识符的其他的部分由字母、数字和下划线组成。
    • 标识符对大小写敏感。

    在 Python 3 中,可以用中文作为变量名,非 ASCII 标识符也是允许的了。

    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']
    
    • 1
    • 2
    • 3

    行与缩进

    python最具特色(sb)的就是使用缩进来表示代码块,不需要使用大括号 {} 。

    缩进的空格数是可变的,但是同一个代码块的语句必须包含相同的缩进空格数。实例如下:

    if True:
        print ("True")
    else:
        print ("False")
    
    • 1
    • 2
    • 3
    • 4

    以下代码最后一行语句缩进数的空格数不一致,会导致运行错误:

    if True:
        print ("Answer")
        print ("True")
    else:
        print ("Answer")
      print ("False")    # 缩进不一致,会导致运行错误
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    以上程序由于缩进不一致,执行后会出现类似以下错误:

     File "test.py", line 6
        print ("False")    # 缩进不一致,会导致运行错误
                                          ^
    IndentationError: unindent does not match any outer indentation level
    
    • 1
    • 2
    • 3
    • 4

    多行语句

    Python 通常是一行写完一条语句,但如果语句很长,我们可以使用反斜杠 \ 来实现多行语句,
    (我还以为python作者认为代码就应该一行写完所以让缩进作为块语句呢)
    例如:

    total = item_one + \
            item_two + \
            item_three
    
    • 1
    • 2
    • 3

    在 [], {}, 或 () 中的多行语句,不需要使用反斜杠 \,例如:

    total = ['item_one', 'item_two', 'item_three',
            'item_four', 'item_five']
    
    • 1
    • 2
  • 相关阅读:
    ElementUI之CUD+表单验证
    国债1万亿,你该学点什么
    前端、后端面试集锦
    无线投屏冷知识
    centos上安装rabbitmq
    kubesphere安装
    8月份补丁更新:微软修补了121个安全漏洞
    Flink Interval Join,Temporal Join,Lookup Join区别
    对标 VSCode?JetBrains 下一代编辑器 Fleet
    Mybatis Plus分页实现逻辑整理(结合芋道整合进行解析)
  • 原文地址:https://blog.csdn.net/weixin_44368963/article/details/136252697