#coding=utf-8
#!/usr/bin/python3
循環(huán)語句 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"]
循環(huán)語句for
sites = ["Baidu", "Google","Runoob","Taobao"]
for site in sites:
if site == "Runoob":
print("菜鳥教程!")
break
print("循環(huán)數(shù)據(jù) " + site)
else:
print("沒有循環(huán)數(shù)據(jù)!")
print("完成循環(huán)!")
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
遍歷數(shù)組
a = ["a","b","c","d","e","f","g"]
for i in range(len(a)):
print("第%d個數(shù)為:%s" % (i + 1,a[i]))
a = list(range(100)) # 創(chuàng)建一個列表
# print a
break 和continue 語句及循環(huán)中的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時跳過這次循環(huán) 繼續(xù)進行下一輪循環(huán)
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是質(zhì)數(shù)" % n)
## Python pass是空語句壶熏,是為了保持程序結構的完整性阅畴。
pass 不做任何事情,一般用做占位語句燕差,如下實例
最小的類
class MyEmpty:
pass
# while True:
# pass
for letter in "runoob":
if letter == "o":
pass
print "執(zhí)行pass塊"
print("當前字符是:%s" % letter)
print "good bye"