zoukankan      html  css  js  c++  java
  • Python 第04周:控制与循环

    if语句

    if语句用来检验一个条件, 如果 条件为真,我们运行一块语句(称为 if-块 ), 否则 我们处理另外一块语句(称为 else-块 )。 else 从句是可选的。

    练习: 使用if语句

    number = 23
    guess = int(raw_input('Enter an integer : '))

    if guess == number:
        print 'Congratulations, you guessed it.' # New block starts here
        print "(but you do not win any prizes!)" # New block ends here
    elif guess < number:
        print 'No, it is a little higher than that' # Another block
        # You can do whatever you want in a block ...
    else:
        print 'No, it is a little lower than that'
        # you must have guess > number to reach here

    print 'Done'

    练习输出:

    Enter an integer : 50
    No, it is a little lower than that
    Done

    Enter an integer : 22
    No, it is a little higher than that
    Done

    Enter an integer : 23
    Congratulations, you guessed it.
    (but you do not win any prizes!)
    Done

     

    while语句

    只要在一个条件为真的情况下,while语句允许你重复执行一块语句。while语句是所谓 循环 语句的一个例子。while语句有一个可选的else从句。

    练习: 使用while语句

    number = 23
    running = True

    while running:
        guess = int(raw_input('Enter an integer : '))

        if guess == number:
            print 'Congratulations, you guessed it.'
            running = False # this causes the while loop to stop
        elif guess < number:
            print 'No, it is a little higher than that'
        else:
            print 'No, it is a little lower than that'
    else:
        print 'The while loop is over.'
        # Do anything else you want to do here


    练习输出

    Enter an integer : 50
    No, it is a little lower than that.

    Enter an integer : 22
    No, it is a little higher than that.

    Enter an integer : 23
    Congratulations, you guessed it.
    The while loop is over.
    Done

    练习程序是如何工作的?


    在这个程序中,我们仍然使用了猜数游戏作为例子,但是这个例子的优势在于用户可以不断的猜数,直到他猜对为止——这样就不需要像前面那个例子那样为每次猜测重复执行一遍程序。这个例子恰当地说明了while语句的使用。

    我们把raw_input和if语句移到了while循环内,并且在while循环开始前把running变量设置为True。首先,我们检验变量running是否为True,然后执行后面的 while-块 。在执行了这块程序之后,再次检验条件,在这个例子中,条件是running变量。如果它是真的,我们再次执行while-块,否则,我们继续执行可选的else-块,并接着执行下一个语句。
    当while循环条件变为False的时候,else块才被执行——这甚至也可能是在条件第一次被检验的时候。如果while循环有一个else从句,它将始终被执行,除非你的while循环将永远循环下去不会结束!
    True和False被称为布尔类型。你可以分别把它们等效地理解为值1和0。在检验重要条件的时候,布尔类型十分重要,它们并不是真实的值1。
    else块事实上是多余的,因为你可以把其中的语句放在同一块(与while相同)中,跟在while语句之后,这样可以取得相同的效果。

    for循环

    for..in是另外一个循环语句,它在一序列的对象上 递归 即逐一使用队列中的每个项目。我们会在后面的章节中更加详细地学习序列。

    练习: 使用for语句

    for i in range(1, 5):
        print i
    else:
        print 'The for loop is over'

    练习输出:

    1
    2
    3
    4
    The for loop is over

    练习程序是如何工作的?

    在这个程序中,我们打印了一个 序列 的数。我们使用内建的range函数生成这个数的序列。
    我们所做的只是提供两个数,range返回一个序列的数。这个序列从第一个数开始到第二个数为止。例如,range(1,5)给出序列[1, 2, 3, 4]。默认地,range的步长为1。如果我们为range提供第三个数,那么它将成为步长。例如,range(1,5,2)给出[1,3]。记住,range 向上 延伸到第二个数,即它不包含第二个数。
    for循环在这个范围内递归——for i in range(1,5)等价于for i in [1, 2, 3, 4],这就如同把序列中的每个数(或对象)赋值给i,一次一个,然后以每个i的值执行这个程序块。在这个例子中,我们只是打印i的值。
    记住,else部分是可选的。如果包含else,它总是在for循环结束后执行一次,除非遇到break语句。
    记住,for..in循环对于任何序列都适用。这里我们使用的是一个由内建range函数生成的数的列表,但是广义说来我们可以使用任何种类的由任何对象组成的序列!我们会在后面的章节中详细探索这个观点。

    break语句

    break语句是用来 终止 循环语句的,即哪怕循环条件没有称为False或序列还没有被完全递归,也停止执行循环语句。
    一个重要的注释是,如果你从for或while循环中 终止 ,任何对应的循环else块将不执行。

    练习: 使用break语句

    while True:
        s = raw_input('Enter something : ')
        if s == 'quit':
            break
        print 'Length of the string is', len(s)
    print 'Done'

    练习输出:

    Enter something : Programming is fun
    Length of the string is 18
    Enter something : When the work is done
    Length of the string is 21
    Enter something : if you wanna make your work also fun:
    Length of the string is 37
    Enter something :       use Python!
    Length of the string is 12
    Enter something : quit
    Done

    练习程序是如何工作的?

    在这个程序中,我们反复地取得用户地输入,然后打印每次输入地长度。我们提供了一个特别的条件来停止程序,即检验用户的输入是否是'quit'。通过 终止 循环到达程序结尾来停止程序。
    输入字符串的长度通过内建的len函数取得。
    记住,break语句也可以在for循环中使用。

    continue语句

    continue语句被用来告诉Python跳过当前循环块中的剩余语句,然后 继续 进行下一轮循环。

    练习:使用continue语句

    while True:
        s = raw_input('Enter something : ')
        if s == 'quit':
            break
        if len(s) < 3:
            continue
        print 'Input is of sufficient length'
        # Do other kinds of processing here...


    练习输出:

    Enter something : a
    Enter something : 12
    Enter something : abc
    Input is of sufficient length
    Enter something : quit


    练习程序是如何工作的?

    在这个程序中,我们从用户处取得输入,但是我们仅仅当它们有至少3个字符长的时候才处理它们。所以,我们使用内建的len函数来取得长度。如果长度小于3,我们将使用continue语句忽略块中的剩余的语句。否则,这个循环中的剩余语句将被执行,我们可以在这里做我们希望的任何处理。
    注意,continue语句对于for循环也有效。

    以下题目可在OJ上完成:

    第1题:图形输出 2480


    题目描述
    用基本输出语句打印以下图形:
    #
    ##
    ###
    ####
    #####
    ######
    输入
    本题目没有输入数据
    输出
    输出图形由6行组成,第1行有1个#号,第i行有连续的i个#号:
    #
    ##
    ###
    ####
    #####
    ######
    示例输入
    示例输出
    #
    ##
    ###
    ####
    #####
    ######
    -------------------------

    第2题:交换两个整数的值


    题目描述
    交换两个变量的值,由终端输入两个整数给变量x、y,然后交换x和y的值后,输出x和y。
    输入
    从键盘输入两个整数变量x和y;
    输出
    在交换x、y的值后将x和y输出!
    示例输入
    4 6
    示例输出
    6 4
    -----------------------------------------

    第3题:Python 循环打印图形(循环结构)


    题目描述
    通过使用双重for循环语句,打印下列图形:
    提交
    输入
    输出
    示例输入
    示例输出
       *
      ***
    *****
    *******
    *****
      ***
       *
    -----------------------------------------

    第4题:IBM Minus One


    题目描述
    You may have heard of the book '2001 - A Space Odyssey' by Arthur C. Clarke, or the film of the same name by Stanley Kubrick. In it a spaceship is sent from Earth to Saturn. The crew is put into stasis for the long flight, only two men are awake, and the ship is controlled by the intelligent computer HAL. But during the flight HAL is acting more and more strangely, and even starts to kill the crew on board. We don't tell you how the story ends, in case you want to read the book for yourself :-)

    After the movie was released and became very popular, there was some discussion as to what the name 'HAL' actually meant. Some thought that it might be an abbreviation for 'Heuristic ALgorithm'. But the most popular explanation is the following: if you replace every letter in the word HAL by its successor in the alphabet, you get ... IBM.

    Perhaps there are even more acronyms related in this strange way! You are to write a program that may help to find this out.
    输入
    The input starts with the integer n on a line by itself - this is the number of strings to follow. The following n lines each contain one string of at most 50 upper-case letters.
    输出
    For each string in the input, first output the number of the string, as shown in the sample output. The print the string start is derived from the input string by replacing every time by the following letter in the alphabet, and replacing 'Z' by 'A'.

    Print a blank line after each test case.
    示例输入
    2
    HAL
    SWERC
    示例输出
    String #1
    IBM

    String #2
    TXFSD

  • 相关阅读:
    使用Selenium对付一个点击游戏
    使用Selenium登录新浪微博
    LeetCode题解 #155 Min Stack
    LeetCode题解 #2 Add Two Numbers
    django for monkey(chapter one)
    Django,数据模型创建之数据库API参考(转载)
    python djang suit模板
    Jmeter多机并发压测IP地址问题
    Jmeter进行数据库压测
    fiddler实现手机端抓包(代理)
  • 原文地址:https://www.cnblogs.com/jlxuqiang/p/4051478.html
Copyright © 2011-2022 走看看