Practice: for Loop
Q1. Print squares
Print the square of each number in [1, 2, 3, 4] on separate lines.
Goal: Loop over a list.
Q2. Uppercase letters
Print each letter of 'abc' in uppercase on its own line.
Goal: Loop over a string.
Q3. Numbered list
Print the items of ['tea', 'milk', 'rice'] as numbered lines starting at 1, like '1 tea'.
Goal: Use enumerate.
Q4. Pair names and scores
Using zip, print 'Asha 90' and 'Ravi 85' from two lists.
Goal: Use zip.
Q5. Largest number
Find and print the largest number in [4, 19, 7, 12] without using max().
Goal: Use a loop to find a maximum.
Q6. Dictionary total
Add all the values of {'a': 5, 'b': 10, 'c': 20} and print the total.
Goal: Loop over dictionary values.
Q7. Triangle pattern
Print a triangle of stars with rows of 1, 2 and 3 stars.
Goal: Use a loop to draw a pattern.
Q8. Dictionary default
What does this print?
d = {'x': 1, 'y': 2}
for k in d:
print(k)Goal: Know dictionary iteration.
Q9. Enumerate start
What does this print?
for i, c in enumerate('hi', start=5):
print(i, c)Goal: Trace enumerate.
Q10. Zip shortest
What does this print?
for a, b in zip([1, 2, 3], ['x', 'y']):
print(a, b)Goal: Understand zip length.
Q11. Nested count
What does this print?
c = 0
for i in range(3):
for j in range(2):
c += 1
print(c)Goal: Count nested iterations.
Q12. For else
What does this print?
for n in [2, 4, 6]:
if n > 5:
print('big', n)
break
else:
print('none')Goal: Understand for-else.
Q13. Slice loop
What does this print?
for ch in 'python'[1:4]:
print(ch, end='-')Goal: Loop over a slice.
Q14. Fix the colon
Fix the code so it prints each name.
for name in ['A', 'B']
print(name)Goal: Fix syntax errors.
Q15. Fix the removal bug
The code should remove all even numbers, but it skips some. Fix it so the result is [1, 3, 5].
nums = [1, 2, 4, 5, 6]
for n in nums:
if n % 2 == 0:
nums.remove(n)
print(nums)Goal: Avoid modifying a list while looping.
Q16. Why enumerate
Explain in a sentence why enumerate() is better than range(len(items)).
Goal: Explain enumerate.
Q17. Dictionary default meaning
What do you get if you write for x in {'a': 1}? Explain.
Goal: Understand dictionary loops.
Q18. Count words longer than 3
Given words = ['sun', 'moon', 'star', 'sky'], print how many have more than 3 letters.
Goal: Combine loop and filter.