For Loops

Last time we introduced while loops. Today we talk about the for loop which has the same amount of power as a while loop, but provides more ease-of-programming convenience for common counting operations. We'll also discuss nested loops, syntax, and strategies for choosing the correct type of loop.

Reading: Chapter 5

Continue reading Chapter 5 from "Definite loops using for" to the end.

Today in Class

We will discuss and learn about:

You should be able to understand these programs.

And run it yourself right here!

# Print "hello" N times
N = input("How many times? ")
N = int(N)
      
for i in range(N):
    print("Hello friend!")

Compute the factorial of a user's input number.

# Compute N!
N = input("What number? ")
N = int(N)

# Compute N!      
prod = 1
for i in range(1,N+1):
      prod = prod * i

# Remember: Integers need to convert to strings when concatenating
print(str(N) + "! = " + str(prod))