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