基础语法
- 变量定义:
test = 1
test2 = 'abc'
- 区块 使用 :与缩进对齐来标示一个区块, 如其他语言中大括号中内容
if True:
a = 1
b = 2
...
- 函数定义
def fun(a, b, c = 1, d = 'a'):
print(a, b, c)
def fun2(*nums, end='\n'):
for n in nums:
print(n)
print(end)
- 控制结构
if cond1 or cond2 and cond3 and not cond4:
pass
elif condition:
pass
else:
pass
for i in range(5):
print(i);
a = 5;
while a > 0:
print(a)
a = a - 1
- 容器
l = [1, 2, 'a', 'abc']
l.append('end')
l.remove('a')
l.pop(3)
t = (1,)
t = ('a', 1, [1, 2])
d = {'a':1, 'b':2, 'c':[1,2,3]}
d.get('d', -1)
s = set([1,2,3])
s1 = set([3,4])
print(s & s1)
print(s | s1)
l[0:3] 或 l[:3] 获取前三项
l[3:]
l[-3:]
l[::-1]
L[:10:2]
- 关键字
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']
- 读写文件
import os
f = open(filepath, 'r')
f = open(filepath, 'r', encoding='gbk', errors='ignore')
f.read()
f.read(size)
f.readlines()
f.write("something")
f.close()
with open(filepath, 'w') as f:
pass
os.path.join('/Users/michael', 'testdir')
os.path.split('/Users/michael/testdir/file.txt')
os.path.splitext('/path/to/file.txt')
[x for x in os.listdir('.') if os.path.isdir(x)]
- 面向对象
class TestClass(object):
__slots__ = ('name', 'age')
static_name = 'TestClass'
def __init__(self, name):
self.name = name
self.load(name)
def load(self, name):
pass
def __private_fun(self):
pass