Last week 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.
Read from this subsection to the end.
We will discuss and learn about:
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))