Sign in to save

Bookmark this page so you can find it later.

Sign in to save

Bookmark this page so you can find it later.

CS Grade 6-8

Python: Loops (for and while)

Practice tracing, writing, and choosing loops in Python

View Answer Key

Practice using for loops and while loops to repeat actions, trace code, fix loop errors, and solve simple programming problems in Python.

Read each problem carefully. Trace the code step by step when needed. Write complete code or explanations in the space provided.

Name:
Date:
Score: / 15

Practice tracing, writing, and choosing loops in Python

CS - Grade 6-8

Instructions: Read each problem carefully. Trace the code step by step when needed. Write complete code or explanations in the space provided.
  1. 1

    What does this code print? for i in range(4): print(i)

  2. 2

    Write a for loop that prints the numbers 1 through 5, one number per line.

  3. 3

    What does this code print? count = 3 while count > 0: print(count) count = count - 1 print("Go!")

  4. 4

    Choose the better loop type for this task and explain why: Print each item in a list of favorite foods.

  5. 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. 6

    Fill in the blank so the loop prints 2, 4, 6, 8, and 10. for n in range(2, 11, ____): print(n)

  7. 7

    Trace this code and write the final value of total. total = 0 for n in range(1, 4): total = total + n

  8. 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. 9

    What does this code print? for letter in "cat": print(letter)

  10. 10

    Write a while loop that prints the numbers 5 down to 1, one number per line.

  11. 11

    Look at this code. for i in range(3): print("Hello") How many times does it print Hello?

  12. 12

    Complete the code to print each animal in the list. animals = ["dog", "cat", "rabbit"] for animal in animals: __________

  13. 13

    What is the value of x after this code runs? x = 10 while x < 20: x = x + 3

  14. 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. 15

    Explain the difference between a for loop and a while loop in Python. Give one example of when each loop type is useful.

LivePhysics™.com CS - Grade 6-8

More CS Worksheets

See all CS worksheets

More Grade 6-8 Worksheets

See all Grade 6-8 worksheets