Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
For Loops in Python For Loops Range Breaks For Loops in Python L435/L555 Dept. of Linguistics, Indiana University Fall 2014 1/9 For Loops For Loops in Python For Loops Range Breaks Iteration For loops allow us to iterate over each element of a set or sequence Syntax: f o r < var > i n < set > : do . . . do . . . 2/9 Examples For Loops in Python For Loops Range I Iterating over a list: Breaks words = [ ’ g o t ’ , ’me ’ , ’ l o o k i n g ’ , ’ so ’ , ’ c r a z y ’ , ’ r i g h t ’ , ’ now ’ ] f o r w i n words : p r i n t (w) I Iterating over a string: phrase = ’ l o o k i n g so c r a z y i n l o v e ’ f o r w i n phrase : p r i n t (w) 3/9 The Range Iterator For Loops in Python For Loops Range Iteration Breaks Python has a built-in function, range, which allows us to iterate over the numbers specified in the range. What do these do? list list list list ( range ( 0 , 1 0 ) ) ( range ( 1 0 ) ) ( range ( 1 , 11 , 2 ) ) ( range ( 0 , − 10, − 1)) Note: in Python 3, range is an iterator, so it generates numbers on the fly I the list function compresses them into a list 4/9 Range in Loops For Loops in Python For Loops Range Breaks f o r number i n range ( 0 , 1 0 ) : p r i n t ( number ) a = ’ uh oh uh oh uh oh , oh no no ’ f o r number i n range ( len ( a ) ) : p r i n t ( number , a [ number ] ) 5/9 for vs. while For Loops in Python For Loops Range Breaks a = ’ uh oh uh oh uh oh , oh no no ’ i = 0 while i < len ( a ) : print ( i , a [ i ] ) i += 1 f o r i i n range ( len ( a ) ) : print ( i , a [ i ] ) 6/9 Breaking out of Loops I break: stops the execution of the loop, independent of the test For Loops in Python For Loops Range Breaks f o r x i n range ( 0 , 1 0 0 0 ) : i f ( x % 7 ) == 0 : p r i n t ( ’ f i r s t number d i v i s i b l e by 7 : ’ , x ) break I continue: skip the rest of the loop body, but continue with the loop f o r x i n range ( 0 , 1 0 0 0 ) : i f ( x % 7 ) == 0 : print ( x ) else : continue p r i n t ( x , ” i s d i v i s i b l e by 7 ” ) 7/9 Loop Else For Loops in Python For Loops Range Iteration Breaks else can follow a loop, then it is executed in case the loop is NOT exited by break. f o r x i n range ( 1 0 0 ) : i f x > 101: print ( x ) break else : p r i n t ( ’ n o t found ’ ) Only if the break condition is met will the else not run 8/9 List comprehensions again For Loops in Python For Loops Range Breaks I List comprehensions sasha = [1,2,3,4,5] fierce = [x**2 for x in sasha] I List comprehensions with conditions fierce = [x**2 for x in sasha if x%2==0] 9/9