Python 语法
Python语法包括:
- 模块函数导入
- 赋值
- 判断循环语句
模块导入
import somemodule
somemodule.somefunc
from somemodule import somefunc
somefunc
import math
math.pow(2,3)
8.0
from math import pow
pow(2,3)
8.0
赋值
- 序列解包
- 链式赋值
- 增量赋值
x,y=1,2
x,y
(1, 2)
x,y=y,x
x,y
(2, 1)
x=y=3
x,y
(3, 3)
x+=1
x
4
判断语句
if 条件
条件包括:>,>=,<,<=,!=,<>,==,in,not,and,or
x=10
if x>5:
print 'greater'
else:
print 'less'
greater
x=10
assert x > 5
x=1
assert x > 1
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-13-693571434f5b> in <module>()
1 x=1
----> 2 assert x > 1
AssertionError:
while循环
i=1
sum=0
while i<100:
sum+=i
i+=1
sum
4950
for循环
sum=0
for i in range(1,100):
sum+=i
sum
4950
循环立遍字典元素
d={'x':1,'y':2,'z':3}
for key, value in d.items():
print key,value
y 2
x 1
z 3
a=['x','y','z']
b=[1,2,3]
zip(a,b)
[('x', 1), ('y', 2), ('z', 3)]
for name,value in zip(a,b):
print name,value
x 1
y 2
z 3
strings=['hello','hi','apple']
for index, string in enumerate(strings):
if 'h' in string:
strings[index]='replaced'
strings
['replaced', 'replaced', 'apple']
break,else语句
from math import sqrt
for n in range(99,1,-1):
root=sqrt(n)
if root==int(root):
print n
break
else:
print 'did not find it'
81