1 Base Types

  1. int
  2. float
  3. bool
  4. str
  5. bytes

2 variables assignment

x = 1.23 + 2.34

a = b = c = 0


a,b,c = 1,2,3

a,b = b,a # 变量换值
x+ = 3 
# 等价于x = x + 3

x-=1 
# 等价于 x = x-1

del x 
# 表示删除x

3 Container Types

ordered sequences

list 列表

[1,5,9]
## [1, 5, 9]
["x",11,8.9]
## ['x', 11, 8.9]

tuple 元组

(1,5,9)
## (1, 5, 9)
11,"y",7.4
## (11, 'y', 7.4)

key container

字典 dict

{"key":"value"}
## {'key': 'value'}
dict(a=3,b=4,k="v")
## {'a': 3, 'b': 4, 'k': 'v'}

set 集合

{"key1","key2"}
## {'key2', 'key1'}
{1,9,3,0}
## {0, 1, 3, 9}

4 conversion 变量转换

基本格式是type(expression)

int("20")
## 20
float("-11.24e8")
## -1124000000.0
round(15.56,1) # 保留1位小数
## 15.6
bool(-1)
## True
str(1111)
## '1111'
chr(64)
## '@'
bytes([72,9,64])
## b'H\t@'
list("abc")
## ['a', 'b', 'c']
dict([(3,"three"),(1,"one")])
## {3: 'three', 1: 'one'}
set(["one","two"])
## {'two', 'one'}

5 Sequence Containers Indexing 索引

计算长度

lst=[10, 20, 30, 40, 50]

索引从0开始

lst[0] 
## 10
lst[-1]
## 50

如果要选取一段, 格式是 lst[start slice:end slice:step]

lst[:-1]
## [10, 20, 30, 40]
lst[1:-1]
## [20, 30, 40]

6 bool 逻辑

< > <= >= == != , and or not

7 module import

from monmod import nom1,nom2 as fct # 导入部分模块
# or   

import monmod #  导入全部模块

8 条件判断


age = 25

if age < 18:
  print("未成年")
elif age >65:
  print("已经退休")
else:
  print("其他")
## 其他

9 基础数学函数

Operators: + - * / // % **


abs(-3.2)  # 绝对值
## 3.2
round(3.57,1) # 保留小数位
## 3.6
pow(4,3) # 指数
## 64

python 中 math 模块包含了常用的数学函数

import math


math.sin(math.pi/4)
## 0.7071067811865475
math.sqrt(81)
## 9.0
math.ceil(12.5) # 向上取整
## 13
math.floor(12.5 ) # 向下取整
## 12

其他常用的数学相关的模块还包括: math, statistics, random, decimal, fractions, numpy

10 错误处理

基本格式是

try:
  normal procesising block
except Exception as e:
  error processing block

11 循环

条件循环

基本格式是:

while logical condition:
  statements block

循环控制的关键词 continue , break

一个简单的例子

s = 0
i = 1

while i <=100:
  s = s + i**2
  i = i + 1
print("sim:", i)
## sim: 101

迭代循环

基本格式是:

for var in sequence:
  statements block

直接根据字符串遍历

这个sequence 序列 , 可以是一个字符串, 也可以是一个数字列表等等

s = "Today , The Earth become square shape"

cnt = 0

for c in s:
  if c=="a":
    cnt = cnt + 1
print("found",cnt,"a")
## found 4 a

还可以通过索引遍历


lst = [11,18,9,12,23,4,17]

lost = []

for idx in range(len(lst)): # range 会创建一个长度为n的从0开头的列表
  val = lst[idx]
  if val > 15:
    lost.append(val)
    lst[idx] = 15
print("modif:",lst,"-lost:",lost)
## modif: [11, 15, 9, 12, 15, 4, 15] -lost: [18, 23, 17]

同时遍历序列的索引和值

基本格式如下所示:

for idx,val in enumerate(lst):

实用range 函数创建序列

基本格式

range([start,] end [,step])
range(5) # 创建长度为5的序列
## range(0, 5)
range(2,12,3) # 创建从2到12 , 间隔为3的序列
## range(2, 12, 3)
range(3,8) # 创建从哪个3到7 的序列


# 根据序列的长度创建序列 : range(len(seq))
## range(3, 8)

12 打印

print("v=",3,"cm :",1,",",4)

 
## v= 3 cm : 1 , 4

关于print 函数的一些参数

  1. sep 间隔符
  2. end = “” , 表示换行
  3. file = sys.stdout 输出文件

13 输入

s = input("Instructions:")

用于接受用户的键盘输入, 输入总是一个字符串

14 关于容器的常用操作 Generic Operations on Containers

len(c)→ items count

min(c) max(c) sum(c)


sorted(c)→ list sorted copy  

val in c  boolean, membership operator in (absence not in)


enumerate(c)→ iterator on (index, value)

zip(c1,c2…)→ iterator on tuples containing ci,items at same index


all(c)→ True if all c items evaluated to true, else False

any(c)→ True if at least one item of c evaluated true, else False

其他一些常用方法

reversed(c)→ inversed iterator

c*5→ duplicate

c+c2→ concatenate(连接)

c.index(val)→ position

c.count(val)→ events count

复制

import copy
copy.copy(c)→ shallow copy of container
copy.deepcopy(c)→ deep copy of container

15 关于列表的操作 list

lst.append(val) add item at end
lst.extend(seq) add sequence of items at end
lst.insert(idx,val) insert item at index
lst.remove(val) remove first item with value val
lst.pop([idx])→value remove & return item at index idx (default last)
lst.sort() lst.reverse() sort / reverse liste in place

16 关于字典的操作


d[key]=value # d[key]→ value

d.clear() # del d[key]

d.update(d2) # update/add  associations


d.keys()
d.values()
d.items() # iterable views on keys/values/associations


d.pop(key[,default])→ value

d.popitem()→ (key,value)

d.get(key[,default])→ value

d.setdefault(key[,default])→value

17 关于集合的操作

一些操作符

  1. → union (vertical bar char)
  2. & → intersection
    • ^ → difference/symmetric diff.
  3. < <= > >= → inclusion relations

其他的一些方法

s.update(s2)

s.copy()

s.add(key)

s.remove(key)

s.discard(key)

 s.clear()
 
 s.pop()

18 文件

基本格式

f = open("file.txt","w",encoding="utf8")
  1. 第一个参数是路径
  2. w 表示写文件, 其他可选包括 ‘r’ read ,‘a’ append
  3. 编码 : utf8 ascii

写文件

f.write("coucou")

f.writelines(list of lines)

f.close() # 关闭文件

读文件

f.read([n]) → next chars , if n not specified, read up to end !

f.readlines([n]) → list of next lines

f.readline() → next line

其他相关方法

f.flush() write cache

f.truncate([size]) resize

f.tell()→position

f.seek(position[,origin])

一个常用的方法

with open(…) as f:
 for line in f :
 # processing ofline

19 函数定义

基本格式是:

def fct(x,y,z):
  """documentation"""
  代码
  return something/none

参数还可以是字典和元组

 def fct(x,y,z,*args,a=3,b=5,**kwargs):

*args 表示tuple 元组

**kwargs 表示字典

函数调用

r = fct(3,i+2,2*i)

20 字符串操作

s.startswith(prefix[,start[,end]])

s.endswith(suffix[,start[,end]])

s.strip([chars])

s.count(sub[,start[,end]])

s.partition(sep)→ (before,sep,after)

s.index(sub[,start[,end]])

s.find(sub[,start[,end]])

s.is…() tests on chars categories (ex. s.isalpha())


s.upper() s.lower() s.title() s.swapcase()

s.casefold() s.capitalize() s.center([width,fill])

s.ljust([width,fill]) s.rjust([width,fill]) s.zfill([width])

s.encode(encoding) s.split([sep]) s.join(seq)

字符串格式化

基本格式:

"modele{} {} {}".format(x,y,r)
print("{:.2f}".format(3.1415926))
## 3.14

常用格式:

  1. {:.2f} : 保留小数点后两位
  2. {:+.2f} : 带符号保留小数点后两位
  3. {:-.2f} : 带符号保留小数点后两位
  4. {:.0f} : 不带小数
  5. {:0>2d} : 数字补零 (填充左边, 宽度为2)
  6. {:x<4d} : 数字补x (填充右边, 宽度为4)
  7. {:x<4d} : 数字补x (填充右边, 宽度为4)
  8. {:,} : 以逗号分隔的数字格式
  9. {:.2%} : 百分比格式
  10. {:.2e} : 科学计数法
  11. {:>10d} : 右对齐 (默认, 宽度为10)
  12. {:<10d} : 左对齐 (宽度为10)
  13. {:^10d} : 中间对齐 (宽度为10)