一、中文编码
- 在
Python 3.x
中,源码文件默认以UTF-8
编码,所有字符串都是unicode
字符串 - 在
Python 2.x
中,源码文件默认以ASCII
编码,需要指定编码格式,即可正常解析中文
# -*- coding: UTF-8 -*-
#coding=utf-8
PyCharm 小技巧:
- 进入
File > Settings
,在输入框搜索Encoding
- 找到
Editor > File Encodings
,将IDE Encoding
和Project Encoding
设置为UTF-8
二、标识符
- 第一个字符必须是 小写字母或下划线
- 其他的部分 由字母、数字和下划线组成
- 单词与单词之间使用 下划线连接
- 区分 大小写字母
三、关键字
- 不能 把它们用作任何标识符名称
import keyword
print(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']
四、单行注释
- 单行注释以
#
开头
# 单行注释
print("单行注释") # 单行注释
-> 单行注释
五、多行注释
- 多行注释用三个单引号
'''
或者三个双引号"""
将注释括起来
"""
多行
注释
"""
print("多行注释")
-> 多行注释
六、函数注释
- 基本注释
def sum_2_num(num1, num2):
"""两数求和"""
result = num1 + num2
print("%d + %d = %d" % (num1, num2, result))
- 参数注释
def sum_2_num(num1, num2):
"""两数求和
:param num1: 第一个数
:param num2: 第二个数
"""
result = num1 + num2
print("%d + %d = %d" % (num1, num2, result))
PyCharm 小技巧:
- 定义函数时,上下行与函数、类的方法之间需要空出两行,空行也是程序代码的一部分
- 选中需要注释的行,按下
Ctrl + /
, 即可快速进行单行块注释 - 把光标放在函数上,出现黄色小灯泡并点击,选择
Insert documentation string stub
,即可进行参数注释 - 把光标放在函数上,按下
Ctrl + q
, 即可查看快速文档
七、行与缩进
- 使用 缩进 来表示代码块,不需要 使用大括号
- 同一个代码块的语句必须包含 相同的缩进空格数
if True:
print ("True")
else:
print ("False")
-> True
八、多行语句
- 使用反斜杠
\
来实现多行语句
total = item_one + \
item_two + \
item_three
- 在
[], {}, ()
中的多行语句,不需要使用反斜杠\
total = ['item_one', 'item_two', 'item_three',
'item_four', 'item_five']
九、等待用户输入
input("按下 Enter 键后退出:")
十、同一行显示多条语句
- 同一行中使用多条语句,语句之间使用分号
;
分割
import keyword; print(keyword.kwlist)
十一、输出结果
print
默认输出是 换行 的- 如果要实现 不换行,需要在变量末尾加上
end=""
x = "a"
y = "b"
# 换行输出
print(x)
print(y)
print('---------')
# 不换行输出
print(x, end=" ")
print(y, end="")
print(y, x)
-> a
-> b
-> ---------
-> a bb a
十二、导入模块
- 将整个模块导入
import keyword
- 从某个模块中导入某个函数
from keyword import kwlist
- 从某个模块中导入多个函数
from keyword import kwlist, iskeyword
- 将某个模块中的全部函数导入
from keyword import *
十三、命令行参数
- 很多程序可以执行一些操作来查看一些基本信息
$ python -V
-> Python 3.7.2
$ 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. ]
十四、代码规范
- 官方英文版:PEP 8 – Style Guide for Python Code
- 谷歌中文版:Python 风格指南 - 内容目录
https://zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/contents/