if,while,for的快速掌握
一、python的缩进和冒号
a = 20
if a>10:print('a>10, pass')print('abc')
b= 1
print('#'*10)if b<0:print('b<0, pass')print('b>0')
打印结果如下:
a>10, passabc## # # # # # # # #
b>0
总结:同一数量级下,使用tab缩进,来区分代码的逻辑性
二、if 条件判断
格式如下:
if 判断条件:
执行语句...
elif 判断条件:
执行语句...
else 判断条件:
执行语句...
#其中elif这部分可选
print('if'*10)
x= 6
if x<=-1:print('x是负数')elif x==0:print('x等于0')else:print('x是正数')
打印结果如下:
x是正数
三、while条件判断
格式如下:
while 判断条件:
执行语句...
注意:
容易造成无限循环,判断条件为真,执行语句后,会返回接着判断
while 1:print('1111')print('2222')print('3333')print('4444')
使用debug模式,在while条件位置打断点,按F8
y = 6
while y<8:print('1111')print('2222')print('3333')print('4444')
y+= 1
print('abc'*10)
abc= 6
print('***the script starts***')while abc >0:print('abc = %d' %abc)
abc-= 1
print('***The script end***')
显示结果
abc abc abc abc abc abc abc abc abc abc***the script starts***abc= 6abc= 5abc= 4abc= 3abc= 2abc= 1
***The script end***
四、for循环
用来遍历列表,字符串,文件等操作,默认是循环到元素完为止。
格式如下:
for iterating__var in sequence:
statement(s)
示例
print('for'*10)
test= dict(a=1, b=2, c=3, d=4)
z=list('linux')print(test)for j,k inenumerate(z):print(j,k)#这里print(j,k)相当于print(j,z[j])
print('wait the next for*')for key1,value1 intest.iteritems():print(key1,value1)
显示结果
for for for for for for for for for for{'a': 1, 'c': 3, 'b': 2, 'd': 4}
(0,'l')
(1, 'i')
(2, 'n')
(3, 'u')
(4, 'x')
wait the nextfor*('a', 1)
('c', 3)
('b', 2)
('d', 4)
range与xrange对比
range 一次打印出范围内所有值,相比较容易占用较多内存
xrange每次用的时候才取一次,节约资源,效率更高
range示例1:
print(range(10))
显示结果
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range示例2:
print(range(1,10))
显示结果
[1, 2, 3, 4, 5, 6, 7, 8, 9]
xrange示例1:
print(xrange(1,10))
显示结果
xrange(1, 10)
xrange示例2:
print(type(xrange(1,10)))
显示结果
xrange示例3:
for i in xrange(1,10):print(i, )
显示结果
(1,)
(2,)
(3,)
(4,)
(5,)
(6,)
(7,)
(8,)
(9,)
五、continue与break
continue 跳出本次循环,不执行continue后面紧跟的内容,直接回到循环体开始位置,进入下一次循环。
break 不执行break后面紧跟的内容,并且跳出整个循环体
for i in xrange(1,4):print(i)if i == 2:print('Hello world')continueprint('inside of if')print('i = %d' %i)print('outside of for')
显示结果
i = 1
2Hello world3i= 3outside offor
===========================================
for i in xrange(1,4):print(i)if i == 2:print('Hello world')breakprint('inside of if')print('i = %d' %i)print('outside of for')
显示结果
1i= 1
2Hello world
outside offor