Python 流程控制

Python 流程控制条件 if 

if ... elif ... else 

if语句
if expression: #expression 关键字
statement(s)

注:python 使用缩进作为其语句分组的方法,建议使用4个空格

#!/usr/bin/python
if 1:                    #1 为 True, 0为 False, None  也是false 
    print "hello python"         

not 即为非
1 > 2 是不成立的false ,前面加了not ,结果就变成了true

if 条件:
command #条件为true,执行这个command
elif 条件:
command #当上面的条件不成立,这条成立,即执行这条command
else :
command #条件为false ,执行这个command

字符串 > 数字
将字符串变为数值 init('3')

#!/usr/bin/python
while True:
    suma = int(raw_input("please input the number :"))
    if suma >= 90:
        print "A"
    elif suma >= 80:
        print "B"
    elif suma >= 60:
        print "C"
    elif suma == -1:
        break
    else :
        print "D"
print "END"

if else
逻辑值(bool)包含了两个值:
Ture: 表示非空的量(比如: string,tuple,list, set , dictonary),所以非零数
Fals: 表示0,None ,空的量 等。

a.lower() 全小写
a.upper() 全大写

In : a = 'abcd'
In : a.upper()
Out: 'ABCD'

In : a = 'ABCD'
In : a.lower()
Out: 'abcd'

 

python 流程控制循环 for

循环
循环是一个结构,导致程序要重复一定的次数
条件循环也是如此,当条件变为假,循环结束

for 循环:
在序列里,使用for 循环遍历

语法:

  for iterating_var in sequence:
     statement(s)

range() 返回一个真实的列表,可以用来做for循环的遍历

In   : range(10)
Out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In : range(1,11,1)
Out: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In : range(1,11,2)
Out: [1, 3, 5, 7, 9]

In : range(1,11,3)
Out: [1, 4, 7, 10]

In : range(1,11,4)
Out: [1, 5, 9]

In : range(1,11,5)
Out: [1, 6]

查看帮助信息
help(range)

range(...)
    range(stop) -> list of integers
    range(start, stop[, step]) -> list of integers
    
    Return a list containing an arithmetic progression of integers.
    range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
    When step is given, it specifies the increment (or decrement).
    For example, range(4) returns [0, 1, 2, 3].  The end point is omitted!
    These are exactly the valid indices for a list of 4 elements.

取偶数
print [i for i in range(1, 11) if i % 2 ==0] #列表重写

for i in range(1, 11):
    if i % 2 ==0:
        print i

将奇数乘方2
print [i**2 for i in range(1,11) if i % 2 != 0]

for i in range(1,11):
    if i % 2 != 0:     #取奇数
        print i**2      #乘方
In : print [i for i in range(1,11) if i % 2 == 0]
[2, 4, 6, 8, 10]

In : print [i**2 for i in range(1,11) if i % 2 == 0]
[4, 16, 36, 64, 100]

In : for i in range(1,11):
   ....:     if i %2 ==0:
   ....:         print i**2
   ....:         
4
16
36
64
100

In : print [i for i in range(1,11) if i % 2 == 0]
[2, 4, 6, 8, 10]

In : for i in range(1,11):
   ....:     if i % 2 != 0:
   ....:         print i**2 
   ....:         
1
9
25
49
81

写法不同结果相同
sum = sum + i == sum += i

In : sum = 0
In : for i in range(1,11):
   ....:     sum = sum + i
   ....: print sum
   ....: 
55

In : sum = 0
In : for i in range(1,11):
   ....:     sum += i 
   ....: print sum
   ....: 
55

xrange() 返回的是一个对象 object ,只用在for 循环使用时才能正常输出列表值

class xrange(object)
 |  xrange(stop) -> xrange object
 |  xrange(start, stop[, step]) -> xrange object
 |  
 |  Like range(), but instead of returning a list, returns an object that
 |  generates the numbers in the range on demand.  For looping, this is 
 |  slightly faster than range() and more memory efficient.

只用在for 循环使用时才能正常输出列表值

In : xrange(1,11)
Out: xrange(1, 11)

In : a = xrange(1,11)

In : type (a)
Out: xrange

In : print a
xrange(1, 11)

In : for i in a:
   ....:     print i
   ....:     
1
2
3
4
5
6
7
8
9
10

In : for i in a:
   .....:     print i,      #加逗号,去掉换行符
   .....:     
1 2 3 4 5 6 7 8 9 10

for 遍历字典
迭代遍历
遍历序列:将序列中各个元素取出来
直接从序列取值
通过索引来取值

注: "迭代" 指重复执行一个指令。

乘方口诀表 输出方式

#!/usr/bin/python
for i in xrange(1,10):                     #行数定义 1-9
    for x in xrange(1,i+1):               #列数定义,要行数+1
        print "%sx%s=%s" % (i, x, i*x),      #加逗号, 将换行变成一行输出
    print                                                  #默认为换行

执行结果:

[root@hc python]# python for1.py 
1x1=1
2x1=2 2x2=4
3x1=3 3x2=6 3x3=9
4x1=4 4x2=8 4x3=12 4x4=16
5x1=5 5x2=10 5x3=15 5x4=20 5x5=25
6x1=6 6x2=12 6x3=18 6x4=24 6x5=30 6x6=36
7x1=7 7x2=14 7x3=21 7x4=28 7x5=35 7x6=42 7x7=49
8x1=8 8x2=16 8x3=24 8x4=32 8x5=40 8x6=48 8x7=56 8x8=64
9x1=9 9x2=18 9x3=27 9x4=36 9x5=45 9x6=54 9x7=63 9x8=72 9x9=81

iteritems() 返回一个对象object

help(a.iteritems)
iteritems(...)
    D.iteritems() -> an iterator over the (key, value) items of D

定义一个字典

In : dic.fromkeys('abcd',10)
Out: {'a': 10, 'b': 10, 'c': 10, 'd': 10}

赋值给a ,输出一个字典

In : a = dic.fromkeys('abcd',10)
In : a
Out: {'a': 10, 'b': 10, 'c': 10, 'd': 10}

for 循环去遍历字典里的key值

In : for i in a:
   ....:     print i
   ....:     
a
c
b
d

for 循环去遍历字典里的key 和value 值 ,这里用到了索引查value值

In : for i in a:
    print i, a[i]
   ....:     
a 10
c 10
b 10
d 10

格式化输出

In : for i in a:
    print "%s --> %s" % ( i, a[i])
   ....:     
a --> 10
c --> 10
b --> 10
d --> 10

逗号抑制它自动换号

In : for i in a:
    print "%s --> %s" % ( i, a[i]),
   ....:     
a --> 10 c --> 10 b --> 10 d --> 10

将字典换成列表+元组

In : a.items()
Out: [('a', 10), ('c', 10), ('b', 10), ('d', 10)]

列表和元组,for循环去遍历出 key和value

In : for k, v in a.items():
   ....:     print k, v
   ....:     
a 10
c 10
b 10
d 10

将列表里的元组,for循环遍历出来独立的元组

In : for i in a.items():
   ....:     print i
   ....:     
('a', 10)
('c', 10)
('b', 10)
('d', 10)

使用 iteritems() 其输出是一个object

In : for k, v in a.iteritems():
    print k, v
   ....:     
a 10
c 10
b 10
d 10



循环退出

循环退出有以下几项
else :for正常结束才会执行后面代码
break :跳出该循环
continue :当满足条件时,跳过当前,继续执行循环
pass : 相当于站位,不做动作
sys.exit() : exit 立即结束。sys方法必须加载import sys

for 循环的 else
for 循环如果正常结束,才会执行else

import sys         #要使用exit(),所以要加载模块
import time
for i in range(10):
    if i == 8:
        sys.exit()
    if i == 6:
        pass
    if i == 7:
        continue
    time.sleep(1)
    if i == 5:
        break
else:                     #正常结束才可以执行这条
    print "END"      

任务
系统生成一个20以内的随机整数。
玩家有6次机会进行猜猜看,每次猜测都有反馈(大了,小了,对了,结束)
6次中,猜对了,玩家赢了。
否则系统赢了

随机模块
import random
加载模块
random.randint(1,20)
使用

代码如下:

#!/usr/bin/python
import random
num = random.randint(1,20)
print ("OK, play my game")
for i in range(1,7):
    a = input("please input the number :")
    if a >= 1 and a <= 20:
        if num > a:
            print ("input the number is small !")
            print ("keep trying !"), i
        elif num < a:
            print ("input the number is big ! ")
            print ("keep trying !"), i
        elif num == a:
            print ("Congratulations ! you win ! input the number is True !")
            print ("the system num is "),num
            break
    else :
        print "please input the number within 20 !"
    if i == 6:
            print ("game is over ,you loss! the number is "),num

输出结果

[root@hc python]# python test1.py 
OK, play my game
please input the number :3
input the number is small !
keep trying ! 1
please input the number :3
input the number is small !
keep trying ! 2
please input the number :3
input the number is small !
keep trying ! 3
please input the number :3
input the number is small !
keep trying ! 4
please input the number :3
input the number is small !
keep trying ! 5
please input the number :3
input the number is small !
keep trying ! 6
game is over ,you loss! the number is  8

[root@hc python]# python test1.py 
OK, play my game
please input the number :10
input the number is big ! 
keep trying ! 1
please input the number :7
input the number is small !
keep trying ! 2
please input the number :8
Congratulations ! you win ! input the number is True !
the system num is  8

 

python 流程控制循环 while

while 和for 相比
for循环用在有次数的循环上。

while循环用在有条件的控制上。

while 循环,直到表达式变为 false ,才能退出
while 循环,表达式是一个逻辑表达式,必须返回一个true或者false

语法

while expression:
    statement(s)
else:                    #当循环正常退出才会执行下面的内容
     statement(s)

代码:

#!/usr/bin/python
a = ''
while a != 'q' :
    a = raw_input("input the q for quit : ")
    print "hello "
    if not a:
        break
    if a == 'quit':
        continue
    print "continue"
else :
    print "is ture quit!"

结果:

[root@hc python]# python while.py 
input the q for quit : 
hello 
[root@hc python]# python while.py 
input the q for quit : a
hello 
continue
input the q for quit : b
hello 
continue
input the q for quit : c
hello 
continue
input the q for quit : quit
hello 
input the q for quit : q
hello 
continue
is ture quit!


python 访问文件 open and with open

open 打开文件,可以使用读写等命令
查看帮助
help(open)

open(...)
    open(name[, mode[, buffering]]) -> file object
    
    Open a file using the file() type, returns a file object.  This is the
    preferred way to open a file.  See file.__doc__ for further information.

open :
r : 以 读 方式打开 ,默认只读
w : 以 写 方式打开,如果该文件存在则会被覆盖
a : 以 追加 模式

r+ : 以 读写 模式打开
w+ : 以 读写 模式打开(参见w)
a+ : 以 读写 模式打开(参见a)

rb : 以 二进制 读模式打开
wb : 以 二进制 写模式打开(参见w)
ab : 以 二进制 追加模式打开(参见a)

rb+ : 以 二进制 读写模式打开(参见r+)
wb+ : 以 二进制 读写模式打开(参见w+)
ab+ : 以 二进制 读写模式打开(参见a+)

使用 open() 要注意 要打开就要有关闭。
open 打开
close 关闭

使用open
fd.read() #一个一个字符地读取,从文件头读到尾,全部读出

fd.readline() # 只读取一行

fd.readlines() #读多行,从头读到尾,返回列表

fd.next() #也是一行一行的读取

#!/usr/bin/python
fd = open("/tmp/123")
for i in fd.readlines():    #很占用资源  
    print i,
fd.close()

for i in fd:    #这样用,因为fd已经是一个object了,当去for循环去遍历才一行行输出,这样会减少耗费CPU资源
    print i
fd.close()
#!/usr/bin/python
fd = open("/tmp/123")
while True:
    line = fd.readline()
    if not line:
        break
    print line,    #加逗号抑制print的换行符
fd.close()

with open
可以不用最后关闭文件 .close() 它自动关闭
使用:
with open("目录") as 变量:

#!/usr/bin/python
with open("/tmp/123") as fd:        #注意with open的格式
    while True:
        line = fd.readline()
        if not line:
            break
        print line,

和 with open 区别

#!/usr/bin/python
fd = open("/tmp/123")
while True:
    line = fd.readline()
    if not line:
        break
    print line,
fd.close()

他们两个的输出也一样!

[root@hc python]# python open.py 
asd
123
333
zxc
aaa


原文地址:https://www.cnblogs.com/huidou/p/10758078.html