Python Notes (5) - Loops

转载请注明出处:http://blog.csdn.net/cxsydjn/article/details/71303117

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值