While Loops

Close on the heels to if statements in importance is the while loop, and loops in general. Right now you can write programs to input and print, store in variables, and even branch your code into different behavior based on the input. However, you can't go back and repeat something. We need a new mechanism that allows our code to repeat itself. This is important because you'll find that when you need to process data, you typically want to run the same code over and over, but just on different inputs.

Reading: Chapter 5 (stop at "Definite loops using for")

Short reading today! Read Chapter 5 but stop before you reach the for loops.

Today in Class

We will discuss and learn about:

You should be able to understand these programs.

# This program keeps prompting the user until they give a positive integer
num = int(input("Please enter a positive integer: "))

while num < 0:     
    num = int(input("Please try again: "))

print("You entered " + num)		 
# This program counts the number of digits in the input integer.
num = int(input("Please enter a big integer: "))

length = 0
while num >= 1:
    num = num/10  # also works here: n = n//10
    length += 1
# Remember that concatenating strings needs all the variable types to be string      
print("length = " + str(length))