资料:一译中文文档python api
要记得加冒号。相比于c++,python里 and 对应 && , or 对应 || ,not 对应 !
还有三目运算 B if A else C ,如果A为true,则执行B;A为false,则执行C
#coding=utf-8
a=1
b=0
if a and b:
print "1"
elif a or b:
print "2"
elif not b:
print "3"
else:
print "4"
print 'a is equal to 1' if a==1 else 'a is not equal to 1'
额外资料:跟老齐学Python之print详解
字符串用\和+号进行连接,用*号可以进行重复运算,”’ ”’这样的字符串很像Matlab里的向量。
#我认为'abc'和"abc"是一样的,'''abc'''和"""abc"""是一样的。只要注意对称使用。
a='aaaaaa'
print a
b="bbbbbb"
print b
c='''cccccc'''
print c
d='ddd\
ddd'
print d
e='eee' \
'eee'
print e
f='fff''fff'
print f
g='ggg'+'ggg'
print g
h="hh'hh'hh"
print h
i='ii"ii"ii'
print i
j='''j1
j2
j3'''
print j
k="""k1
k2
k3"""
print k
m='a'*15
print m
aaaaaa
bbbbbb
cccccc
dddddd
eeeeee
ffffff
gggggg
hh’hh’hh
ii”ii”ii
j1
j2
j3
k1
k2
k3
aaaaaaaaaaaaaaa
转义跟c语言一样。第三个例子,字符串前面加了个r,让字符串变为自然字符串,失去转义的作用。
print 'It\'s a book'
print 'hello\nworld'
print r'hello\nworld'
It’s a book
hello
world
hello\nworld
s = '123456789'
s1 = s[5]
print s1
s2 = s[:5]
print s2
s3 = s[3:5]
print s3
6
12345
45
for i in range(1, 3):
print i
else:
print "end"
1
2
end
for i in range(5, 10):
print i
if i == 7:
break
else:
print "end"
5
6
7
for i in range(1,15,3): #从1开始递增到14,每次的增量是3
print i
1
4
7
10
13
a=2
while a < 5:
print a
a += 1
else:
print "end"
2
3
4
end
a=2
while a < 5:
print a
a += 1
if a==3:
break
else:
print "end"
2
a=10
while a < 5:
print a
a += 1
if a==3:
break
else:
print "end"
end
# coding=utf-8
class Hello():
def __init__(self,name):
self._name=name
def sayHello(self):
print("{0}".format(self._name))
class Hi(Hello):
def __init__(self,name):
Hello.__init__(self,name)
def sayHi(self):
print("{0}".format(self._name))
def max(a,b):
if a>b:
return a
else:
return b
def ret():
for i in range(0,5):
print("Item {0},{1}".format(i,"Hello Python"))
h=Hello("Hello")
h.sayHello()
h1=Hi("Hi")
h1.sayHi()
print(max(2,3))
ret()
Hello
Hi
3
Item 0,Hello Python
Item 1,Hello Python
Item 2,Hello Python
Item 3,Hello Python
Item 4,Hello Python
#coding=utf-8
import pickle
lista = ["123", "456", "789"]
listb = pickle.dumps(lista) #将对象序列化
listc = pickle.loads(listb) #将对象恢复为原来格式
print listc
#coding=utf-8
import pickle
group1=("123","456","789")
f1=file('1.pkl','wb') #wb意为‘写’
pickle.dump(group1,f1,True) #将对象序列化
f1.close()
f2=file('1.pkl','rb') #rb意为‘读’
t=pickle.load(f2) #将对象恢复为原来格式
print t
f2.close()