2nd Semester Intro to Computer Science

What you will learn

Reading

Do Now

1. In your Notebook

Answer the following

  1. How would you print out something 10 times? What about 100? What about 1,000?
  2. Can you remember something from Snap! that might allow that?

2. Open up the console

Type the following code using interactive mode

while True:
    print('a')

3. In your Notebook

Write responses for the following

  1. What happens when you run this code?
  2. Try using other Boolean expressions instead of True (e.g. 4 > 5 and 9 != 2), and explore what happens.

  3. How would you print out something 10 times? What about 100? What about 1,000?

  4. Can you remember something from Snap! that might allow that?

4. Open up the console

Type the following code

while True:
    print('a')

5. In your Notebook

continue responses for the following

  1. What happens when you run this code?
  2. Try using other Boolean expressions instead of True (e.g. 4 > 5 and 9 != 2), and explore what happens.

6. Open up the console

Type and run the following code (Remember this from Unit 2?)

if animal in ['cat', 'dog']:
    print("A great pet!")

Lab

1. In your Notebook

Predict what will be printed then type the program in your console to confirm

Example 1

    a = 0
    while a < 10:
        print(a)
Predicted Output Actual Output


Example 2

    a = 0
    while a < 10:
        a = a + 1
        print(a)
Predicted Output Actual Output


2. In your Notebook

Create a set of test cases for the following sample code and predict the behavior

    a = input("Would you like to quit: ")
    while a != "y" and a != "n" :
        a = input("Would you like to quit: ")
Predicted Output Actual Output


3. Implement the Tic Tac Toe game using a while loop

tic-tac-toe

Bonus

Create a variable-sized board. So instead of a classic 3 x 3 board, create a way for the user specify the size of the board they want to play with.

Check your understanding

Pick an answer for each question. You can try again until you get it right.

1. What does this code print?

n = 0
while n < 3:
    n = n + 1
print(n)
  • 3
  • 0
  • 2
  • Nothing, it loops forever

The loop repeats while n < 3, and stops once n reaches 3.

2. Why does this loop never end?

count = 0
while count < 5:
    print(count)
  • Because print cannot be used in a loop
  • Because 5 is too large
  • Because count never changes, so the condition stays true
  • Because while loops run only once

Nothing inside the loop changes count, so count < 5 is always true.

3. When does the code inside a while loop run?

  • Only once, before the condition is checked
  • Repeatedly, as long as the condition is true
  • Only when the condition is false
  • Exactly 10 times

A while loop checks its condition before each pass and repeats the body while it is true.

Downloads