(1)基本运算
1.基本运算,第一个是赋值运算,第二个是乘法,最后一个是幂
a = 3
print(a*2)
print(a**2)
输出
6
9
a,b,c = 6,7,8 #这句命令相当于 a = 6 ,b = 7 , c = 8
print("a=%d" %(a))
print("a=%d" %(b))
print("a=%d" %(c))
输出
a=6
a=7
a=8
2.灵活的字符串操作
s = 'I love china'
s = s + ' very very much'
print(s.split(' '))
输出
[‘I’, ‘love’, ‘china’, ‘very’, ‘very’, ‘much’]
(2)判断与循环
a = 4
if a == 1:
print(a)
else:
print(u'a不等于1')
输出
a不等于1
s ,k = 0 , 0
while k < 101:
k = k + 1
s = s + k
print(s)
s = 0
for k in range(101):
s = s + k
print(s)
s = 6
if s in range(4):
print(u's在0,1,2,3中')
if s not in range(1,4,1):
print(u's不在1,2,3中')
输出
5151
5050
s不在1,2,3中
(3)函数
def add(x):
return x +2
print(add(5))
def add2(x = 0,y = 0):
return [x+2,y+2]
def add3(x,y):
return x+3,y+3
a,b = add2(1,2)
print("a = %d,b = %d" % (a,b))
#lambda对简单地功能定义“行内函数
f = lambda x :x + 2 #定义函数f(x) = x+2
q = lambda x,y:x+y #定义函数g(x,y) = x+y
print(q(1,3))
输出
7
a = 3,b = 4
4
(2) 数据结构
(1)列表
a = [1,2,3]
b = []
for i in a:
b.append(i+2)
print(b)
#简化版
a = [7,2,3,8,4]
b = [i+2 for i in a]
print(b)
print(sum(b)) #求和
print(len(b)) #个数
print(max(b)) #最大值
print(min(b)) #最小值
print(sorted(b)) #升序排序
输出
[3, 4, 5]
[9, 4, 5, 10, 6]
34
5
10
4
[4, 5, 6, 9, 10]
(2)字典
d = {'monday':25,'tuesday':26}
print(d['monday'])
print(d['tuesday'])
输出
25
26
(3)集合
#集合
s = {1,2,3,4,5,5}
s = set(s) #set去重
print(s)
t = {1,5,7,2,6}
print(t|s) #并集
print(t&s) #交集
print(t-s) #差集
print(t^s) #对称差集
输出
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5, 6, 7}
{1, 2, 5}
{6, 7}
{3, 4, 6, 7}