美文网首页
Python Notes (5) - Loops

Python Notes (5) - Loops

作者: SilentSummer | 来源:发表于2018-03-19 21:46 被阅读13次

    Loops allow you to quickly iterate over information in Python. The note will cover two types of loop: 'while' and 'for'.

    Python notes of open courses @Codecademy.

    While Loops

    • The while loop is similar to an if statement: it executes the code inside of it if some condition is true.

    • The difference is that the while loop will continue to execute as long as the condition is true. In other words, instead of executing if something is true, it executes while that thing is true.

    • Exit Method 1: Condition

      • The condition is the expression that decides whether the loop is going to be executed or not.

      • Example:

        while loop_condition:
            # Do something for each loop
            # until loop_condition = False
        
    • Exit Method 2: break

      • First, create a while with a condition that is always true. The simplest way is shown.

      • Using an if statement, you define the stopping condition. Inside the if, you write break, meaning "exit the loop."

      • The difference here is that this loop is guaranteed to run at least once.

      • Example:

        while True:
            # Do something for each loop
            if loop_condition == False:
                break
        
    • while/else:

      • Python is the while/else construction. while/else is similar to if/else, but there is a difference:
        • the else block will execute anytime the loop condition is evaluated to False. This means that it will execute if the loop is never entered or if the loop exits normally.
        • If the loop exits as the result of a break, the else will not be executed.

    For Loops

    • An alternative way to loop is the for loop.

      • The syntax is as shown; this example means "for each x in a, do sth".

      • The above a could be a list, a string or a dictionary, etc.

        # A sample loop would be structured as follows.
        for x in a: 
            # Do something for every x
        
    • enumerate:

      • for index, item in enumerate(list):
      • It works by supplying a corresponding index to each item in the list.
    • zip:

      • for a, b in zip(list_a, list_b):
      • It will create pairs of elements when passed two lists, and will stop at the end of the shorter list.
      • It can handle three or more lists.
    • for/else:

      • Just like with while, for loops may have an else associated with them.
      • In this case, the else statement is executed after the for, but only if the for ends normally — that is, not with a break.

    External Resources

    相关文章

      网友评论

          本文标题:Python Notes (5) - Loops

          本文链接:https://www.haomeiwen.com/subject/utlafftx.html