Python: Loops (for and while)
Practice tracing, writing, and choosing loops in Python
Practice tracing, writing, and choosing loops in Python
CS - Grade 6-8
- 1
What does this code print? for i in range(4): print(i)
- 2
Write a for loop that prints the numbers 1 through 5, one number per line.
- 3
What does this code print? count = 3 while count > 0: print(count) count = count - 1 print("Go!")
- 4
Choose the better loop type for this task and explain why: Print each item in a list of favorite foods.
- 5
Choose the better loop type for this task and explain why: Keep asking a user for a password until they type the correct password.
- 6
Fill in the blank so the loop prints 2, 4, 6, 8, and 10. for n in range(2, 11, ____): print(n)
- 7
Trace this code and write the final value of total. total = 0 for n in range(1, 4): total = total + n
- 8
This code is supposed to print 1, 2, and 3, but it has a bug. Fix it. x = 1 while x <= 3: print(x)
- 9
What does this code print? for letter in "cat": print(letter)
- 10
Write a while loop that prints the numbers 5 down to 1, one number per line.
- 11
Look at this code. for i in range(3): print("Hello") How many times does it print Hello?
- 12
Complete the code to print each animal in the list. animals = ["dog", "cat", "rabbit"] for animal in animals: __________
- 13
What is the value of x after this code runs? x = 10 while x < 20: x = x + 3
- 14
Write a for loop that prints the square of each number from 1 through 4. The output should be 1, 4, 9, and 16 on separate lines.
- 15
Explain the difference between a for loop and a while loop in Python. Give one example of when each loop type is useful.
Related Cheat Sheets
More CS Worksheets
CS: Algorithms and Flowcharts
Grade 6-8 · 12 problems
CS: Arrays and Lists
Grade 9-12 · 12 problems
CS: Big-O Notation and Algorithm Efficiency
Grade 9-12 · 12 problems
CS: Binary Numbers and Number Systems
Grade 6-8 · 12 problems
More Grade 6-8 Worksheets
Ratios & Proportions
Math · 8 problems
Forces & Motion
Physics · 8 problems
Figurative Language
Language Arts · 8 problems
US Government & Civics
Social Studies · 8 problems