Modules should have short, all-lowercase names.
模组名全小写
Class names should normally use the CapWords (CamelCase) convention.
类名用驼峰命名法
Function and variables names should be lowercase, with words separated by underscores as necessary to improve readability.
函数与变量名全小写,可用下划线增加可读性
Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include MAX_OVERFLOW and TOTAL.
常熟全大写,可用下划线增加可读性
Common name conventions:
_single_leading_underscore: weak “internal use” indicator. E.g. from M import * does not import objects whose names start with an underscore.
single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g. : tkinter.Toplevel(master, class_='ClassName')
__double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo).
__double_leading_and_trailing_underscore__: “magic” objects or attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Never invent such names; only use them as documented.
注释
Python中单行注释以 # 开头,实例如下:
#!/usr/bin/env python3
# 第一个注释
print ("Hello, Python!") # 第二个注释
复制代码
执行以上代码,输出结果为:
Hello, Python!
复制代码
多行注释可以用多个 # 号,还有 ''' 和 """:
#!/usr/bin/env python3
# 第一个注释
# 第二个注释
''' 第三注释
第四注释
'''
"""
第五注释
第六注释
"""
print ("Hello, Python!")
复制代码
执行以上代码,输出结果为:
Hello, Python!
复制代码
行与缩进
python最具特色的就是使用缩进来表示代码块,不需要使用大括号 {} 。 PEP 8: Indentation 与 PEP 8: Tabs or Spaces? 对Python缩进提出额外的要求,包括尽量使用四个空格作为缩进、尽量使用tabs而不是空格。
缩进的空格数是可变的,但是同一个代码块的语句必须包含相同的缩进空格数。实例如下:
if True:
print ("True")
else:
print ("False")
复制代码
以下代码最后一行语句缩进数的空格数不一致,会导致运行错误:
if True:
print("Answer")
print("True")
else:
print("Answer")
print("False") # 缩进不一致,会导致运行错误
复制代码
以上程序由于缩进不一致,执行后会出现类似以下错误:
SyntaxError: unindent does not match any outer indentation level
On BSD’ish Unix systems, Python scripts can be made directly executable, like shell scripts, by putting the line
#!/usr/bin/env python3.5
复制代码
(assuming that the interpreter is on the user’s PATH) at the beginning of the script and giving the file an executable mode. The #! must be the first two characters of the file. On some platforms, this first line must end with a Unix-style line ending ('\n'), not a Windows ('\r\n') line ending. Note that the hash, or pound, character, '#', is used to start a comment in Python.
The script can be given an executable mode, or permission, using the chmod command.
chmod +x myscript.py
复制代码
On Windows systems, there is no notion of an “executable mode”. The Python installer automatically associates .py files with python.exe so that a double-click on a Python file will run it as a script. The extension can also be .pyw, in that case, the console window that normally appears is suppressed.