#coding=utf-8
#!/usr/bin/python3
循环语句 while
n = 100
sum = 0
counter = 1
while counter <= n:
sum = sum + counter
counter += 1
pass
print("1 到%d之和为:%d" % (n,sum))
count = 0
while count < 5:
print("count %d 小于 5" % count)
count += 1
pass
else:
print("count %d 大于等于 5" % count)
languages = ["c","C++","perl","python"]
循环语句for
sites = ["Baidu", "Google","Runoob","Taobao"]
for site in sites:
if site == "Runoob":
print("菜鸟教程!")
break
print("循环数据 " + site)
else:
print("没有循环数据!")
print("完成循环!")
for i in range(5):
print i
for i in range(5,9):
print i # 5 ,6,7,8 没到9
for i in range(0,10,2): # 2是步长(增量) 不写默认为1
print i
for i in range(-10,-100,-30): # 间隔是-30
print i
遍历数组
a = ["a","b","c","d","e","f","g"]
for i in range(len(a)):
print("第%d个数为:%s" % (i + 1,a[i]))
a = list(range(100)) # 创建一个列表
# print a
break 和continue 语句及循环中的else子句
for letter in "runoob":
if letter == "b":
break
print("当前字符是:" % letter)
else:
print letter
print "GoodBye!"
var1 = 10
while var1 > 0:
#print("count %d 小于 5" % count)
print("var1 == %d " % var1)
var1 -= 1
if var1 == 5:
break
print "结束"
var2 = 10
while var2 > 0:
# print("var2 == %d" % var2)
var2 -= 1
if var2 == 5: continue # 当变量为5时跳过这次循环 继续进行下一轮循环
print("变量var2 == %s" % var2)
for n in range(2,10):
for x in range(2,n):
if n % x == 0:
# print(n,"等于",x,"*",n / x)
print("%d等于%d * %d" % (n,x, n/x))
break
else:
print("%d是质数" % n)
## Python pass是空语句,是为了保持程序结构的完整性。
pass 不做任何事情,一般用做占位语句,如下实例
最小的类
class MyEmpty:
pass
# while True:
# pass
for letter in "runoob":
if letter == "o":
pass
print "执行pass块"
print("当前字符是:%s" % letter)
print "good bye"
网友评论