5. Loops and list comprehension Flashcards

1
Q

Write a loop that prints out the items in the following list, all on the same line:
planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']

A
for planet in planets:
    print(planet, end=' ') # print all on same line
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the four components of a For loop

A
  • For
  • the variable name to use (in this case, planet)
  • the set of values to loop over (in this case, planets)
  • You use the word “in” to link them together.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

In a For loop, can you use a tuple as the set of values to loop over?

A

Yes, can use a tuple!

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

How would you loop through the characters in the string “hello” and print each of them out in the same line?

A
for char in "Hello":
  print(char,end='')
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Print numbers 1 to 5 using range() and for loop

A
for i in range(5):
print(i+1)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Using a while loop, print the numbers from 1 to 10 on one line

A
i=1
while i < 11:
print(i, end = ' ')
i = i + 1
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

L— c———- are one of Python’s most beloved and unique features

A

List comprehensions

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

Create a list with the squares of the numbers from 1 to 10

A
squares = [n**2 for n in range(1,11)]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Create a list with the squares of the odd numbers from 1 to 10, using list comprehension

A

squares = [n**2 for n in range(1,11) if n%2==1]

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