最新消息:XAMPP默认安装之后是很不安全的,我们只需要点击左方菜单的 "安全"选项,按照向导操作即可完成安全设置。

Python 控制流程控制

XAMPP案例 admin 340浏览 0评论

drr00067

if语句

结构1:if……else

>>> x = 3
>>> if x < 0:
...     x = 0
... else:
...     print("More")
...
More

>>> if  True:
...     print("True")
...
True
>>> if  False:
...     print("False")
...
>>> if  not  False:
...     print("False")
...
False

注意:

  1. Python里面boolean常量值为False(假),True(真)
  2. 浮点数与整数的比较
>>> 1.0 == 1
True #注意,结果为真

>>> if  not  5 < 2:
...     print("True")
...
True
  1. 空字符、列表等被视为False。
  2. if else语句简写例子:

    >>> a,b = 5, 3
    >>> if a>b:
    ...     c = 1
    ... else:
    ...     c = 4
    ...
    >>> print(c)
    1
    

    等价写法

    >>> c = 1 if a>b else  4
    >>> c
    1
    

结构2:if……elif……else

>>> x = int(input("please enter en number:"))
please enter en number:10 # python 2.7输入的数据如果是字符,必须加引号
>>> if x < 0:
...     x = 0
...     print("Negative changed to zero")
... elif x == 0:
...     print("Zero")
... elif x == 1:
...     print("single")
... else:
...     print("More")
...
More

结构3:if……elif

>>> y = "123"
>>> if y == "123":
...     print(y)
... elif y == "test":
...     print(y)
...
123

>>> x = input("please enter en number:")
please enter en number:5     # python 2.7必须加引号
>>> x
'5'

注意:input函数会把接收到的输入都转为字符串形式,所以,如果要将输入值与数字比较,则必须用int()函数转化,否则会提示TypeError: unorderable types: str() <int()错误

for语句

基于字符串的迭代

>>> string = "ishouke"
>>> for w in string:
...     print(w)
...
i
s
h
o
u
k

基于列表的迭代

>>> words = ["i", "shou", "ke"]
>>> for w in words:
...     print(w, len(w))
...
i 1
shou 4
ke 2

基于序列切片的迭代

以列表为例,字符串,元组序列以此类推

>>> words = ["i", "shou", "ke"]
>>> for w in words[2:]:
...    print(w)
...
ke

>>> words = ['i', 'am', 'shou', 'ke']
>>> for w in words[:]:
...    print(w)
...
i
am
shou
ke

>>> words = ['wordone', 'wordtwo', 'wordthree']
>>> for w in words[1:]:
...     if len(w) >5:
...         words.insert(0, w)
...
>>> words
['wordthree', 'wordtwo', 'wordone', 'wordtwo', 'wordthree']

基于元组的迭代

>>> for i in ("i", "shou", "ke"):
...     print(i)
...
i
shou
ke

基于集合的迭代

>>> for i in {"i", "shou", "ke"}:
...     print(i)
...
i
ke
shou

注意:输出结果无序,这种迭代一般没啥用

基于字典的迭代

>>> for i in {1:"i", 2:"shou", 3:"kedd"}:
...     print(i)
...
1
2
3

注意:仅输出了键

基于数字序列的迭代

在数字序列上进行迭代时需要用到range()函数

仅指定生成数字序列的结束值

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4

注意:range()函数在迭代时返回的所需序列的连续序列项,但是并不创建list,以节约空间,如下

>>> range(0, 10) 
range(0, 10)  # 备注:python2.7中,显示为[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print(range(10))
range(0, 10)

指定生成数字序列的起始值,结束值

>>> for i in range(5, 10):
...     print(i)
...
5   #生成数字序列包含起始值
6
7
8
9

指定生成数字序列的起始值,结束值,步长值

>>> for i in range(1, 10, 3):  #指定增长步长值为 3 
...     print(i)
...
1
4 # 起始值+步长值,往下以此类推
7

注意:步长值只能为整形且不能为0,否则出错

结合range()函数,len()函数进行迭代

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
...     print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb

特殊情况

>>> for i in range(-1, -10, 2):
...     print(i)
...   #  输出为空,

注意:通过pdb调试发现,此处的i没定义,也就说,如果步长值+起始值不在[起始值,结束值)区间内,则直接结束循环,如下例子中,i是无定义的,无法取到值,因为末端值是2,不在[2,2)区间内

>>> for i in range(2,2):
...  print(i)
...

>>> for i in range(-1, -10, -2):
...     print(i)
...
-1
-3
-5
-7
-9

注意:以上几种情况,生成序列都不包含给定的序列结束值

while语句

while expression:
    <statements>

如果expression为真,执行语句statements

>>> i = 0
>>> while i < 5:
...     print(i)
...     i = i + 1#python中不存在c、c++中的i++表达式
...
0
1
2
3
4

>>> flag = True
>>> while flag:
...     print(flag)
...     flag = False
...
True

break,continue语句及else从句

for循环为例子,while以此类推

break语句

>>> for x in range(5):
...     if x % 2 == 0:
...         print("x = ", x, "break")
...         break
...
x =  0 break

说明:break语句,跳出整个循环

continue语句

>>> for num in range(2, 5):
...     if num % 2 == 0:
...         print("Found an event number", num)
...         continue
...     print("Found a number", num)
...
Found an event number 2
Found a number 3
Found an event number 4

说明:continue中断本次循环

else从句

>>> for x in range(5):
...     if x%2 == 0:
...         print("x = ", x, "no break")
...     else:
...         print("break")
...         break
...
x =  0 no break
break

>>> for x in range(5):
...     if x%2 == 0:
...         print("x = ",x,"no break")
... else:
...     print("break")
...
x =  0 no break
x =  2 no break
x =  4 no break
break

>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...            print(n, 'equals', x, '*', n//x)
...            break
...     else:
...         # loop fell through without finding a factor
...         print(n, 'is a prime number')
...
2  is a prime number
3  is a prime number
4 equals 2 * 2
5  is a prime number
6 equals 2 * 3
7  is a prime number
8 equals 2 * 4
9 equals 3 * 3

>>> while  False:
...     print("False")
... else:
...     print("True")
...
True

说明:else从句和与之对齐的for、if、while语句匹配

使用itertools.chain类按序遍历多个可迭代对象

>>> from itertools import chain
>>> a = [2, 3, 4]
>>> b = [1, 3, 5]
>>> for x in chain(a, b):
...     print(x)
...
2
3
4
1
3
5
>>> a = (1, 3, 5)
>>> b = (2, 4, 8)
>>> for x in chain(a, b):
...     print(x)
...
1
3
5
2
4
8
>>> b = set([3, 5, 9])
>>> a = set([1, 3, 6])
>>> for x in chain(a, b):
...     print(x)
...
1
3
6
9
3
5

>>> a = (1, 3, 5)
>>> b = (2, 4, 8)
>>> c = [10, 13, 18, 21]
>>> for x in chain(a, b, c):
...     print(x)
...
1
3
5
2
4
8
10
13
18
21

chain类接受一个或多个可迭代对象,返回一个chain对象,可用它按顺序遍历多个可迭代对象

chain(*iterables) –> chain object

仿switch…case…

python中是没有其它语言中的switch…case…语句的,不过有等价替代方法

C语言风格的switch case

switch(index)
{
case 1: print(index);
case 2: print(“test”);
case 3: print(“test3”);
}

等价实现方法1

>>> index = 3
>>> {1:lambda:print(index),
...  2:lambda:print('test'),
...  3:lambda:print('test2')}[index]()
test2

对比实验:

>>> {1:lambda:print(index),
...  2:lambda:print('test'),
...  3:lambda:print('test2')}[index]
<function <lambda> at 0x01EE2DB0>

说明:利用了字典的特征

>>> {"key1":"val1","key":2}["key1"]
'val1'

c语言风格

switch(index)
{
    case 1: add(1, 2);
    case 2: sub(5, 3);
    case 3: multi(4, 6);
}
>>> index = 3
>>> result = {
...           1: lambda arg1, arg2: arg1 + arg2,
...           2: lambda arg1, arg2: arg1 - arg2,
...           3: lambda arg1, arg2: arg1 * arg2}[index]
>>> result(4, 6)
24

等价实现方法2

#!/usr/env/bin python
# -*- coding:utf-8 -*-

class switch:
    def __init__(self, value):
        self.value = value
        self.is_match = False

    def __iter__(self):
        return self

    def next(self):
        if self.is_match == True:
            raise StopIteration
        return self.match

   def match(self, *args):
        '''test if arg given match self.value'''

        if not args: # 如果全不匹配--case()
            self.is_match = True
            return True
        elif self.value in args: # 匹配某个值--case(valuex)
            self.is_match = True
            return True
        else:
            self.is_match = False
            return False

if __name__ == '__main__':
    for case in switch(10):
        if case(1):print(1)
        if case(2):print(2)
        if case(3):print(3)
        if case(10):print('no matched')

运行结果:

no matched

if __name__ == '__main__':
    for case in switch('shouke'):
        if case(1):print(1)
        if case(2):print(2)
        if case(3):print(3)
        if case('shouke'):print('matched')

运行结果:

matched

pass语句

pass语句什么都不做。

>>> for i in range(2, 5):
...     pass

用于要求语法上成立,但不执行何操作的语句,通常用于创建最小的类

>>> class MyEmptyClass:
...  pass
...

pass还可用于函数体或条件体占位符,以便站在更抽象级别上思考,如下

>>> def initlog(*args):
...     pass    # Remeber to implement this!
...

 

转载请注明:XAMPP中文组官网 » Python 控制流程控制

您必须 登录 才能发表评论!