Practice: for Loop

« Read the chapter

Q1. Print squares

BeginnerCoding

Print the square of each number in [1, 2, 3, 4] on separate lines.

Goal: Loop over a list.

Q2. Uppercase letters

BeginnerCoding

Print each letter of 'abc' in uppercase on its own line.

Goal: Loop over a string.

Q3. Numbered list

BeginnerCoding

Print the items of ['tea', 'milk', 'rice'] as numbered lines starting at 1, like '1 tea'.

Goal: Use enumerate.

Q4. Pair names and scores

IntermediateCoding

Using zip, print 'Asha 90' and 'Ravi 85' from two lists.

Goal: Use zip.

Q5. Largest number

IntermediateCoding

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

IntermediateCoding

Add all the values of {'a': 5, 'b': 10, 'c': 20} and print the total.

Goal: Loop over dictionary values.

Q7. Triangle pattern

AdvancedCoding

Print a triangle of stars with rows of 1, 2 and 3 stars.

Goal: Use a loop to draw a pattern.

Q8. Dictionary default

BeginnerOutput

What does this print?

Code
d = {'x': 1, 'y': 2}
for k in d:
    print(k)

Goal: Know dictionary iteration.

Q9. Enumerate start

BeginnerOutput

What does this print?

Code
for i, c in enumerate('hi', start=5):
    print(i, c)

Goal: Trace enumerate.

Q10. Zip shortest

IntermediateOutput

What does this print?

Code
for a, b in zip([1, 2, 3], ['x', 'y']):
    print(a, b)

Goal: Understand zip length.

Q11. Nested count

IntermediateOutput

What does this print?

Code
c = 0
for i in range(3):
    for j in range(2):
        c += 1
print(c)

Goal: Count nested iterations.

Q12. For else

IntermediateOutput

What does this print?

Code
for n in [2, 4, 6]:
    if n > 5:
        print('big', n)
        break
else:
    print('none')

Goal: Understand for-else.

Q13. Slice loop

AdvancedOutput

What does this print?

Code
for ch in 'python'[1:4]:
    print(ch, end='-')

Goal: Loop over a slice.

Q14. Fix the colon

BeginnerDebugging

Fix the code so it prints each name.

Code
for name in ['A', 'B']
    print(name)

Goal: Fix syntax errors.

Q15. Fix the removal bug

AdvancedDebugging

The code should remove all even numbers, but it skips some. Fix it so the result is [1, 3, 5].

Code
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

IntermediateConceptual

Explain in a sentence why enumerate() is better than range(len(items)).

Goal: Explain enumerate.

Q17. Dictionary default meaning

BeginnerConceptual

What do you get if you write for x in {'a': 1}? Explain.

Goal: Understand dictionary loops.

Q18. Count words longer than 3

IntermediateApplication

Given words = ['sun', 'moon', 'star', 'sky'], print how many have more than 3 letters.

Goal: Combine loop and filter.