Loops Python - Nick Reynolds September 31, 2017
Loops ● This Class ● Loop Types Assignment 1 ●
Loops
What’s next on the list? What’s a loop? I have a shopping list: What’s next on the list? Apple ● ● Banana ● Orange I want to pick up each one in order. What’s next on the list? Logically I loop through each until I’m done. What’s next on the list? Nothing! Finished!
For Loops ● Most common loop in >>> shopping = ['Apple', 'Orange', 'Banana'] Python >>> for item in shopping: ... print(item) Apple Orange Banana
For Loops ● Most common loop in >>> shopping = ['Apple', 'Orange', 'Banana'] Temporary loop variable Python ● Item is a temporary variable >>> for item in shopping: that will hold the value for ... print(item) each loop. e.g. Apple Loop 1: Item = ‘Apple’ Orange Loop 2: Item = ‘Orange’ Banana Loop 3: Item = ‘Banana’
For Loops ● Most common loop in >>> shopping = ['Apple', 'Orange', 'Banana'] Temporary loop variable Python ● Item is a temporary variable >>> for item in shopping: that will hold the value for ... print(item) each loop. e.g. Apple Loop 1: Item = ‘Apple’ Orange Loop 2: Item = ‘Orange’ Banana Loop 3: Item = ‘Banana’ >>> for <variable> in <list>: ... # do stuff
Pen and Paper Checkpoint
While Loops ● Continues until the condition >>> shopping = ['Apple', 'Orange', 'Banana'] is false >>> n = 0 ● Used when the loop >>> while n < len(shopping): condition is more complex ... print(shopping[n]) ... n = n + 1 Loop 1: Item = ‘Apple’ Loop 2: Item = ‘Orange’ Apple Loop 3: Item = ‘Banana’ Orange Banana
While Loops ● Item is a temporary variable >>> shopping = ['Apple', 'Orange', 'Banana'] that will hold the value for >>> n = 0 Condition each loop. e.g. >>> while n < len(shopping): ... print(shopping[n]) Loop 1: Item = ‘Apple’ ... n = n + 1 Loop 2: Item = ‘Orange’ Loop 3: Item = ‘Banana’ Apple Orange Banana >>> while <condition>: ... # do stuff
Pen and Paper Checkpoint
Practical
Assignment 1
References ● http://pwp.stevecassidy.net/python/more- python.html ● https://thenounproject.com/
Recommend
More recommend