2022年 11月 3日

Python—代码格式规范

1、代码格式规范(可以通过Pycharm检查)

  1. 操作符(operator)两边需要有空格(whitespace)
  2. :(代码块指示符)左边不能有空格(whitespace)
  3. 算数运算等不需要用圆括号(parentheses)
  4. 函数或类末尾需要有两空行(blank lines)
  5. 函数参数直接要有空格

2、案例

  1. # This is a sample Python script.
  2. # Press Shift+F10 to execute it or replace it with your code.
  3. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
  4. def print_hi(name):
  5. # Use a breakpoint in the code line below to debug your script.
  6. print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
  7. a = 100
  8. if a < 1:
  9. print("a > 1")
  10. elif a > 10:
  11. print("a > 10")
  12. else:
  13. print("a is not a valid value")
  14. def test_sum(a: int, b: int) -> int:
  15. print("a+b=", a+b)
  16. return a+b
  17. def print_error(name):
  18. print(f'Warning, {name}')
  19. # Press the green button in the gutter to run the script.
  20. if __name__ == '__main__':
  21. print(__name__)
  22. print_hi('PyCharm')
  23. print_error('Error')
  24. test_sum(2, 10)
  25. # See PyCharm help at https://www.jetbrains.com/help/pycharm/

3、格式检查