[Python learning] 词法结构

主要学习Python词法结构

#字符集

通常,Python的源代码必须完全由ASCII码组成。若想在程序中的注释和字符串常量中使用非ASCII字符,需在源代码的第一行添加注释 # -*- coding: <encoding-name> -*-

#标识符

通常Python的风格是类名称以大写字母开始,其他的标识符都是小写字母。以单个下划线开始的标识符是私有的,以两个下划线开始的标识符是非常强的私有标识符;如果标识符还以两个下划线结尾,则表示该标志符是Python语言定义的特殊名称。

#关键字(3.7.1版本)

1
2
3
4
5
6
7
False      await      else       import     pass
None       break      except     in         raise
True       class      finally    is         return
and        continue   for        lambda     try
as         def        from       nonlocal   while
assert     del        global     not        with
async      elif       if         or         yield

#逻辑行与物理行

逻辑行由一个或多个物理行组成。

  • 当某一物理行以backslash(\)结束,并且后面没有注释,就会连接到下一个物理行作为一个逻辑行。

    1
    2
    3
    4
    
    if 1900 < year < 2100 and 1 <= month <= 12 \
            and 1 <= day <= 31 and 0 <= hour < 24 \
            and 0 <= minute < 60 and 0 <= second < 60:  # Looks like a valid date
        print("It's a valid date.")
    
  • 如果一个左边的圆括号、方括号、花括号还没有对应的右括号,则Python会自动把多个物理行连接成一个逻辑行。

    1
    2
    3
    4
    
    month_names = ['January', 'February', 'March',      # These are the
                'April',   'May',      'June',       # Dutch names
                'July',    'August', 'September',  # for the months
                'October', 'November', 'December']   # of the year
    
updatedupdated2022-05-032022-05-03