if循環python
if elseexpress
if expressionui
statement(s)input
if 1<2:it
print "hello"io
elif 'a':for循環
print "world"import
else:循環
print "END"遍歷
以此種格式運行,if條件成立則運行下面程序,若是不成立則不執行else
例子:
#!/usr/bin/python
a = int(raw_input("please input a number:"))
if a >= 90:
print 'A'
elif a >= 70:
print 'B'
elif a >= 60:
print 'C'
else:
print 'D'
print 'This is you score!'
for循環使用在有次數的循環上
遍歷列表
例子1
#!/usr/bin/python
for i in range(10):
if i % 2 ==0:
print i,
例子2:列表重寫
#!/usr/bin/python
print [i for i in range(10) if i % 2 == 0]
例子3:列表重寫
#!/usr/bin/python
for z in [i for i in range(10) if i % 2 == 0]:
print z
遍歷字典
dic1 = {'a':100, 'b':100, 'c':100, 'd':100}
例子1
for k in dic1:
print k
例子2
for k in dic1:
print k dic1[k]
例子3
for k in dic1:
#,爲去掉換行符
print "%s-->%s" % (k, dic1[k]),
例子4
#使用iteritems()和for循環遍歷字典中的值
for k, v in dic1.iteritems():
print k, v
例子5
#使用for循環寫乘法口訣
for i in xrange(1,10):
for k in xrange(1,i+1):
print "%s X %s = %s" % (i, k, i*k),
for循環的else退出,for循環結束後纔會執行else內容
例子6
#for循環的幾種語法用法
import sys
import time
for i in xrange(10):
if i == 1:
continue
elif i == 3:
pass
elif i == 5:
break
elif i == 7:
sys.exit()
else:
print i
time.sleep(1)
print "2"
例子7使用for循環遍歷文件內容
#!/usr/bin/python
fd = open('/work/python/2.txt')
for line in fd:
print line,
while循環使用在有條件的循環
例子1
#!/usr/bin/python
x = ''
while x != 'q':
print 'hello'
x = raw_input("please input :")
if not x:
break
if x == 'quit'
continue
print 'continue'
else:
print 'world'
使用while循環遍歷文件
例子2
fd = open('/work/python/1.txt')
while True:
line = fd.readline()
if not line:
break
print line,
fd.close()
例子2使用with語法打開文件,能夠不用close關閉文件
with open('/work/python/1.txt') as fd:
while True:
line = fd.readline()
if not line:
break
print line