VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • 初步了解Python

编程规范:PEP 8

在没有额外编程规范的前提下,建议翻阅并遵守PEP 8 - Style Guide for Python Code

编码

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

# -*- coding: cp-1252 -*-

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


标识符

标识符(变量名)命名规则:

  • 第一个字符必须是字母表中字母或下划线 _

  • 其他的字符由字母、数字和下划线组成。

  • 大小写敏感

  • 不能用Python内置的关键字(keywork)

关键字即保留字,它们不能用作标识符名称。Python 的标准库提供了一个 keyword 模块,可以输出当前版本的所有关键字:

>>>import keyword
>>>print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', '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']
  • Python naming convention (命名惯例):

    • 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

多行语句

Python 通常是一行写完一条语句,但如果语句很长,我们可以使用反斜杠 \ 来实现多行语句,例如:

# 仅作展示使用,不符合PEP 8规范
total = item_one + \
        item_two + \
        item_three

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

total = ['item_one', 'item_two', 'item_three',
        'item_four', 'item_five']

total = (item_one
         + item_two
         + item_three)

PEP 8: Maximum Line Length 和 PEP 8: Line Break Before or After Operator? 包含了对于多行语句的编程规范。

空行

函数之间或类的方法之间用空行分隔,表示一段新的代码的开始。类和函数入口之间也用一行空行分隔,以突出函数入口的开始。详见PEP 8: Blank Lines

空行也是程序代码的一部分。


同一行显示多条语句

Python 可以在同一行中使用多条语句,语句之间使用分号 ; 分割,以下是一个简单的实例:

#!/usr/bin/env python3

x = 'abcd'; print(x)

使用脚本执行以上代码,输出结果为:

abcd

多个语句构成代码组

缩进相同的一组语句构成一个代码块,称之代码组。

像if、while、def和class这样的复合语句,首行以关键字开始,以冒号( : )结束,该行之后的一行或多行代码构成代码组。

首行及后面的代码组被称为一个子句(clause)。

如下实例:

if expression : 
   suite
elif expression : 
   suite 
else : 
   suite

print 默认输出是换行的,如果要实现不换行需要在变量末尾加上 end=""

#!/usr/bin/env python3  

x="a" 
y="b" 
# 换行输出 
print( x ) 
print( y )  

print('---------') 
# 不换行输出 
print( x, end="" ) 
print( y, end="" ) 
print()

以上实例执行结果为:

a
b
---------
ab 

善用 help() 方法

通过命令 help("print") 我们知道这个方法里第三个为缺省参数 sep=' '

这里表示我们使用分隔符为一个空格。

>>> help("print")
Help on built-in function print in module builtins:

print(*args, sep=' ', end='\n', file=None, flush=False)
    Prints the values to a stream, or to sys.stdout by default.
    
    sep
      string inserted between values, default a space.
    end
      string appended after the last value, default a newline.
    file
      a file-like object (stream); defaults to the current sys.stdout.
    flush
      whether to forcibly flush the stream.

所以在打印 dict 类的使用, 可以这样写:

>>> def getPairs(dict):
...     for k,v in dict.items() :
...             print(k,v,sep=':')
...

测试代码:

>>> getPairs({ x : x ** 3 for x in range(1,5)})
1:1
2:8
3:27
4:64

import 与 from...import

在 python 用 import 或者 from...import 来导入相应的模块。

将整个模块(somemodule)导入,格式为: import somemodule

从某个模块中导入某个函数,格式为: from somemodule import somefunction

从某个模块中导入多个函数,格式为: from somemodule import firstfunc, secondfunc, thirdfunc

将某个模块中的全部函数导入,格式为:from somemodule import *

以 time 模块举例:

  1. 将整个模块导入,例如:import time,在引用时格式为:time.sleep(1)。

  2. 将整个模块中全部函数导入,例如:from time import *,在引用时格式为:sleep(1)。

  3. 将模块中特定函数导入,例如:from time import sleep,在引用时格式为:sleep(1)。

  4. 将模块换个别名,例如:import time as abc,在引用时格式为:abc.sleep(1)。

命令行参数

很多程序可以执行一些操作来查看一些基本信息,Python可以使用-h参数查看各参数帮助信息:

$ python -h
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-c cmd : program passed in as string (terminates option list)
-d     : debug output from parser (also PYTHONDEBUG=x)
-E     : ignore environment variables (such as PYTHONPATH)
-h     : print this help message and exit

[ etc. ]

在使用脚本形式执行 Python 时,可以接收命令行输入的参数,具体使用可以参照 Python 3 命令行参数。

可直接运行的 Python 脚本

16.1.2. Executable Python Scripts

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.




出处:https://www.cnblogs.com/wanderoff-night/p/18006309

相关教程