CMSC 201

Lab 4: Loops

Loops

What are they?

A loop is a section of code that is repeatedly executed while its test condition is true.

How do I use them?

  • The syntax of a basic while loop is shown below:

  • while condition:    
      complete this statement 
    The above loop would execute until its condition was false. If the condition was never true, the loop would never execute. Similarly if the condition was always true and never became false, the loop would run forever.
  • Example of a while loop:
    i = 0
    while i < 5:
        print(i)
        i = i + 1 
    Output:
    0
    1
    2
    3
    4

  • The code above executes until the test condition i < 5 is no longer true. The variable i starts at 0, so the program prints out 0, 1, 2, 3, 4 and as soon as it reaches 5 the condition is no longer true and the loop stops.
  • You can end a loop by making the test condition false:

  • # Choice is declared & initialized outside the loop. If it was initialized in the loop, it would be re-initialized to "y" with every iteration of the loop!
    choice = input("Welcome to the loop. Would you like to stay (y,n)? ")
    
    while choice == "y":#test condition determines whether the loop executes
      print("Woohoo! A guest!")
      choice = input("What about now (y,n)? ")#user's choice can change the test condition
    print("Okay, goodbye!")
    Output:
    Welcome to the loop. Would you like to stay (y,n)? y
    Woohoo! A guest!
    What about now (y,n)? y
    Woohoo! A guest!
    What about now (y,n)? y
    Woohoo! A guest!
    What about now (y,n)? n
    Okay, goodbye!
  • You can also nest loops, meaning have one loop in another:

  • x = 0
    y = 0
    width = 5
    height = 10
    while x < height:
      while y < width:
        print(y, end="")# the end="" specifies printing without a newline (\n), so that each y is not printed on a seperate line
        y += 1
      print("")
      y = 0
      x += 1
    Output:
    01234
    01234
    01234
    01234
    01234
    01234
    01234
    01234
    01234
    01234
    
  • For more information about how to use print or any python functions, see the official Python Documentation. https://docs.python.org/3.3/index.html