Warm-up

  • Get a name from the user.
  • If the user didn't enter a name, print "you didn't enter a name!"
  • Otherwise, print a greeting to the user.

Lesson 2.4

Introduction to While Loops

Why Loops?

  • Let us repeat code without copying and pasting
  • Useful when we don’t know how many times to repeat
  • while checks a condition and keeps going as long as it’s True

Syntax of a while loop

while condition:
    # code that repeats while condition is True

Example

count = 1
while count <= 5:
    print(count)
    count = count + 1
  • Prints 1 through 5

Important: Indentation

  • All code inside the loop must be indented
  • Each cycle is called an iteration

Infinite Loops

while True:
    print("This never stops!")
  • Always check that your loop condition will eventually become False

Classroom Question

What will this print?

x = 3
while x > 0:
    print(x)
    x = x - 1
print("Done!")

Practice Challenge

Write a program that:

  • Asks the user for a password
  • Keeps asking until they type "python"
  • Then prints "Access granted"