Python学习笔记五--条件和循环

5.1 if语句

没什么好说,if语句语法如下:

if expression:

   expr_true_suit

5.1.1多重条件表达式

单个if语句可以通过布尔操作符and,or,not实现多重条件判断或否定判断。

if not warn and (system_load>=10):

    print 'WARNING:LOSING RESOURCE'

    warn+=1

5.2 else 语句

如果if条件为假程序将执行else后的语句。

if expression:

    expr_true_suit

else:

    expr_false_suit

5.3 elif 即 else-if

elif用来检查多个表达式是否为真,若位置执行其后的语句。elif可以有任意个,但else只能有一个。

语法如下

if expression1:

    expr1_true_suit

elif expression2:

    expr2_true_suit

elif expression3:

    expr3_ture_suit

else:

    none_of_the_above_suit

5.4 三元表达式

python原来并不支持三元表达式(c?x:y)在python2.5中加入了该语法支持,并且相当美观。语法:X if  C else Y

>>>x,y=4,3
>>>smaller=x if x<y else y
>>>smaller
3

5.5 while循环

5.5.1 一般语法

当条件为真是循环执行语句块内的语句,直到条件为假。

while expression:

    suite_to_repeat

5.5.2 计数循环

在语句快中加入计数语句当循环执行一定次数后结束,例子如下。

count=0

while(count<9):

    print 'the index is:',count

    count+=1

5.5.3无线循环

condition永远为真,程序永远在循环中执行。

while True:

    suite_to_repeat

5.6 for循环

python提供的另一个循环for循环,它可以遍历序列成员,可以用在列表解析和生成器中,它会自动调用next()方法。

1、用于序列类型

for可以迭代不同的序列对象包括,字符串,列表,元组。

>>>for eachLetter in 'Names'

        print 'current letter:',eachLetter

current letter:N

current letter:a

current letter:m

current letter:e

current letter:s

对于列表与元组的迭代与上面相似。

2、通过序列索引迭代

首先要建立序列的索引使用range(len(list))来建立索引

>>>string='python'
>>>range(len(string))
[0,1,2,3,4,5]
>>>for index in range(len(string)):
>>>     print string[index]
p
y
t
h
o
n

3、使用项和索引迭代

使用内建函数enumerate()函数同时迭代项和索引。

>>>namelist=['Donn','Ben',‘David’,'Wendy']
>>>for i,eachname in enumerate(namelist):
...       print '%d,%s'%(i+1,eachname)
1,Donn
2,Ben
3,David
4,Wendy

5.7 break

break用在while和for循环中,当执行到break语句跳出当先循环执行下一语句。

def factor(num):
    count=num/2
    while count>0:
        if num%count==0:
            print count,'is largest factor of',num
            break
        count-=1
factor(input('please enter the number:'))

改程序用于计算数字的最大公约数。

5.8 continue

与其他语言中的continue一样,continue意为结束当前循环立即开始下一次循环,当然前提是循环先决条件依然满足。

valid=False
count=3
while count>0:
    input=raw_input('enter password:
')
    for eachpwd in passwdList:
        if eachpwd==input:
            valid=True
            print 'welcome back'
            break
    if not valid:
        print 'invalid input'
        count-=1
        continue
    else:
        break

以上代码为continue的使用示例。

5.9 pass语句

Python中提供pass语句作为占位符。如果在某处语句块中没有任何语句编译器会报错,这时可以使用pass语句作为占位,它不做任何事情,可以作为你以后再补上代码的标记。

5.10 else的其他用法

在其他语言例如C中else不会出现在条件语句以外,但是Python中可以在循环外使用else。这很容易理解,因为循环要做的首先也是条件判断,那么必然就有条件不满足时需要执行的语句。

def MaxFactor(num):
    count=num/2
    while count>1:
        if num%count==0:
            print 'Largest Factor of %d is %d'%(num,count)
            break
        count-=1
    else:
        print num,'is prime'

for eachNum in range(10,21):
    MaxFactor(eachNum)
原文地址:https://www.cnblogs.com/xiaobing-zombie/p/4235539.html