zoukankan      html  css  js  c++  java
  • 【转】Python中的条件选择和循环语句

    转:http://www.cnblogs.com/dolphin0520/archive/2013/03/13/2954682.html

    一.条件选择语句

      Python中条件选择语句的关键字为:if 、elif 、else这三个。其基本形式如下:

    复制代码
    if condition:
        block
    elif condition:
        block
    ...
    else:
        block
    复制代码

      其中elif和else语句块是可选的。对于if和elif只有condition为True时,该分支语句才执行,只有当if和所有的elif的condition都为False时,才执行else分支。注意Python中条件选择语句和C中的区别,C语言中condition必须要用括号括起来,在Python中不用,但是要注意condition后面有个冒号。

       下面这个是成绩划分等级的一个例子:

    复制代码
    score=input()
    if score<60:
        print "D"
    elif score<80:
        print "C"
    elif score<90:
        print "B"
    else:
        print "A"
    复制代码

     二.循环语句

      和C语言一样,Python也提供了for循环和while循环(在Python中没有do..while循环)两种。但是Python中的for循环用法和C语言中的大不一样(和Java、C#中的for循环用法类似),while循环用法大致和C语言中的类似。

      for循环的基本形式如下:

    for variable in list:
        block

      举个例子,求算从1加到100的和:

    sum=0
    for var in range(1,101):
        sum+=var
    print sum

      range()是一个内置函数,它可以生成某个范围内的数字列表。比如说range(1,6)就会生成[1,2,3,4,5]这样一个列表,而range(8)会生成[0,1,2,3,4,5,6,7]这样一个列表。

      当然可以有嵌套循环,比如说有一个列表list=['China','England','America'],要遍历输出每个字母。

    list=['China','England','America']
    for i in range(len(list)):
        word=list[i]
        for j in range(len(word)):
            print word[j]

      内置的函数len()不仅可以用来求算字符串的长度也可以用来求列表或者集合中成员的个数。

      下面来看一下while循环的基本形式:

    while condition:
        block

      只有当condition为True时,才执行循环。一旦condition为False,循环就终止了。

      举个例子:

    count=2
    while count>0:
        print "i love python!"
        count=count-1

      如果想要在语句块过程中终止循环,可以用break或者continue。break是跳出整个循环,而continue是跳出该次循环。

    count=5
    while True:
        print "i love python!"
        count=count-1
        if count==2:
            break
    复制代码
    count=5
    while count>0:
        count=count-1
        if count==3:
            continue
        print "i love python!"
        
        
    复制代码

      最后加一点,Python中的for和while循环都可以加else子句,else子句在整个循环执行条件不符合时执行(这种用法现在一般用得比较少了)。看两个例子:

    复制代码
    #这两段循环功能完全相同
    
    for i in range(0,10):
        print i
    else:
        print 'over'
        
        
    for i in range(0,10):
        print i
    print 'over'
    复制代码

      下面是while..else的用法:

    复制代码
    #这两段循环功能完全相同
    
    count=5
    while count>0:
        print 'i love python'
        count=count-1
    else:
        print 'over'
        
    count=5
    while count>0:
        print 'i love python'
        count=count-1
    print 'over'
    复制代码
  • 相关阅读:
    OleDbCommand 的用法
    递归求阶乘
    C#重写窗体的方法
    HDU 5229 ZCC loves strings 博弈
    HDU 5228 ZCC loves straight flush 暴力
    POJ 1330 Nearest Common Ancestors LCA
    HDU 5234 Happy birthday 01背包
    HDU 5233 Gunner II 离散化
    fast-IO
    HDU 5265 pog loves szh II 二分
  • 原文地址:https://www.cnblogs.com/xubc/p/5235648.html
Copyright © 2011-2022 走看看