Python循环语句

2017-10-20  本文已影响24人  Ke爺

1.1 while循环语法结构

while expression
    while_sutie
#!/usr/bin/env python
sum100 = 0
counter = 1

while counter <= 100:
    sum100 += counter
    counter += 1

print "result is %d" % sum100

1.2 break语句

name = ram_input('username: ')
while name != 'tom':
    name  raw_input('username: ')

# 以上语句可以替换成
while True:
    name = raw_input('username: ')
    if name == 'tom'
        break

1.3 continue语句

#!/usr/bin/env python
sum100 = 0
counter = 0
while counter <= 100
    counter += 1
    if counter % 2:
        continue
    sum100 += counter
print "result is %d" % sum100

1.4 else语句

#!/usr/bin/env python

sum10 = 0
i = 1

while i <= 10:
    sum10 += i
    i += 1
else:
    print sum10

2 for循环

2.1 for循环语法结构

for iter_var in interable:
    suite_to_repeat

2.2 range函数

2.3 xrange函数

2.4 列表解析


上一篇 下一篇

猜你喜欢

热点阅读