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
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)
字典 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}
基本格式是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'}
计算长度
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]
< > <= >= == != , and or not
from monmod import nom1,nom2 as fct # 导入部分模块
# or
import monmod # 导入全部模块
age = 25
if age < 18:
print("未成年")
elif age >65:
print("已经退休")
else:
print("其他")
## 其他
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
基本格式是
try:
normal procesising block
except Exception as e:
error processing block
基本格式是:
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([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)
print("v=",3,"cm :",1,",",4)
## v= 3 cm : 1 , 4
关于print 函数的一些参数
s = input("Instructions:")
用于接受用户的键盘输入, 输入总是一个字符串
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
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
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
一些操作符
其他的一些方法
s.update(s2)
s.copy()
s.add(key)
s.remove(key)
s.discard(key)
s.clear()
s.pop()
基本格式
f = open("file.txt","w",encoding="utf8")
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
基本格式是:
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)
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
常用格式:
{:^10d} : 中间对齐 (宽度为10)