Loops

and Exception Handling

(and some math and strings and debugging)

Reading

7. Iteration

A. Debugging

Video

Learn to Program 2 : Looping (30:23)

Code and Transcript

Video

Learn to Program 3 : Math Strings Exception Handling (29:09)

Code and Transcript

Most Important Concepts

  • You could always use a while loop.

  • while loops are condition controlled.

  • for loops are count controlled.

  • Use a while loop when you don't know how many times it will have to repeat, like a user entering bad input.

  • There must always be something inside the loop that changes the loop condition. If not, you get an infinite loop.

  • The name for a variable that keeps a running total is an accumulator, i.e. runningTotal += anotherNumber

  • The name for one loop execution is an iteration.

  • Sentinel - special value to stop loop

  • You can use a loop to make sure you have good input.

got_good_input = False

while got_good_input == False:

try:

x = int(input("Please enter a number: "))

got_good_input = True

except ValueError:

print("That was not a valid number. Try again...")

Explanation:

  • The input function returns a string so nothing could go wrong there.

  • The int function attempts to convert a string to an integer.

  • If the user enters an integer, like 2, this would work fine.

  • If the user enters something else, like two, this would not work and it would cause an exception.

  • An unhandled exception would cause the program to crash.

  • By putting that line of code that could cause an exception into a try statement, instead of the program crashing, program execution would jump from the line that caused the exception to the line that starts with except.

  • With this code, the only way it could get to the line where got_good_input is set to True would be if the line with int did not cause an exception.

Sample Program

# Prof. Vanselow

# An integration of everything I have learned about programming

print("Welcome to my Integration Project!")

continueProgram = True

while continueProgram:

print("Enter the choice for what you would like to see")

print("1. Area calculator")

print("2. Output formatting")

print("5. Quit")

userChoice = int(input())

if userChoice == 1:

# side is a variable

# a variable is a name for a location in memory

side = int(input("Enter the length of the side of a square to get the area:"))

area = side * side

print(area)

# You could also do print(side * side)

elif userChoice == 2:

print("Output can be formatted to two decimal places with format(variableName, '.2f')")

price = 599.9999

print("For example, 599.999 becomes:", format(price, '.2f'))

elif userChoice == 5:

continueProgram = False

else:

print("Invalid selection. Try again.")