5. Loops and list comprehension Flashcards
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']
for planet in planets: print(planet, end=' ') # print all on same line
What are the four components of a For loop
- 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.
In a For loop, can you use a tuple as the set of values to loop over?
Yes, can use a tuple!
How would you loop through the characters in the string “hello” and print each of them out in the same line?
for char in "Hello": print(char,end='')
Print numbers 1 to 5 using range() and for loop
for i in range(5): print(i+1)
Using a while loop, print the numbers from 1 to 10 on one line
i=1 while i < 11: print(i, end = ' ') i = i + 1
L— c———- are one of Python’s most beloved and unique features
List comprehensions
Create a list with the squares of the numbers from 1 to 10
squares = [n**2 for n in range(1,11)]
Create a list with the squares of the odd numbers from 1 to 10, using list comprehension
squares = [n**2 for n in range(1,11) if n%2==1]