python中的if、while、for

1、python的缩进

python中的if、while、for

2、if 、 while、for语句

python中的if、while、for

python中的if、while、for

个人感觉三个语句当中if最容易理解,举个if的例子,注意冒号,注意缩进:

name = 'aaa'
if name == 'aaa': 
    print 'this is aaa'
elif name== 'bbb':  
    print 'this is bbb'
else: 
    print 'others'

python中的if、while、for

python中的if、while、for

while循环,只要满足条件,就会循环下去,直到条件不满足,举个例子,开始输入5,结果是几呢?9:

n = int(raw_input("input your number:"))
sum=0
while n>0:
      sum = sum+n;
      n = n-2;
print sum
python中的if、while、for

这个for循环在三个三个语法中最为繁琐,当然了使用熟练了就是把利器,下面听我一一道来。


for...in循环,依次把list或tuple中的每一个元素迭代出来:

list=[1,3,2,1,5,3,2,'asdf', True, False]
for x in list:
     print x
计算1-100的整数之和

sum=0
for x in range(1,101):
    sum=sum+x
print sum 

3、break、continue

python中的if、while、forpython中的if、while、for

举个例子:

for i in xrange(1,5):
    if i == 3:
        print ('three')
    print ('i = %d' % i)
i = 1
i = 2
tree
i = 3
i = 4


需求:i 取值1-4 ,如果i等于3,输入应为three

3和three同时出现了,咋办?

for i in xrange(1,5):
    if i == 3:
        print ('three')
        continue
    print ('i = %d' % i)

i = 1
i = 2
three
i = 4

continue结束本次循环,重启下一次循环

for i in xrange(1,5):
    if i == 3:
        print ('three')
        break
    print ('i = %d' % i)
i = 1
i = 2
three


break比较强势,直接终止循环。