Loops Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

Definition of loops

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

for loops

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

range

A

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:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

while loop

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

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’:

A
# 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']
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Write a for loop the prints out all the element between -5 and 5 using the range function.

A
# Write your code below and press Shift+Enter to execute
for i in range (-5,6):
    print(i)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

squares=[‘red’, ‘yellow’, ‘green’, ‘purple’, ‘blue’]

for i, square in enumerate(squares):
print(i, square)

A
0 red
1 yellow
2 green
3 purple
4 blue
How well did you know this?
1
Not at all
2
3
4
5
Perfectly