Loops Flashcards
Definition of loops
you might want to repeat a given operation many times. Repeated executions like this are performed by loops. We will look at two types of loops, for loops and while loops.
for loops
The for loop enables you to execute a code block multiple times. For example, you would use this if you would like to print out every element in a list.
dates = [1982,1980,1973] N = len(dates)
for i in range(N): print(dates[i]) # For loop example dates = [1982,1980,1973] N = len(dates) for i in range(N): print(dates[i]) 1982 1980 1973
range
It is helpful to think of the range object as an ordered list. For now, let’s look at the simplest case. If we would like to generate an object that contains elements ordered from 0 to 2 we simply use the following command:
while loop
The while loop exists as a tool for repeated execution based on a condition. The code block will keep being executed until the given logical condition returns a False boolean value.
Write a while loop to copy the strings ‘orange’ of the list squares to the list new_squares. Stop and exit the loop if the value on the list is not ‘orange’:
# Write your code below and press Shift+Enter to execute squares = ['orange', 'orange', 'purple', 'blue ', 'orange'] new_squares = [] i = 0 while (squares[i]=='orange'): new_squares.append(squares[i]) i = i+1 print (new_squares) ['orange'] ['orange', 'orange']
Write a for loop the prints out all the element between -5 and 5 using the range function.
# Write your code below and press Shift+Enter to execute for i in range (-5,6): print(i)
squares=[‘red’, ‘yellow’, ‘green’, ‘purple’, ‘blue’]
for i, square in enumerate(squares):
print(i, square)
0 red 1 yellow 2 green 3 purple 4 blue