for
loops - run a predetermined number of times
while
loops - run as long as a specified condition is
true
for i in range(5): print(i) # prints 0, 1, 2, 3, 4
i
starts at 0, and increases by 1 on each iteration of the
loop. The loop variable is often called i
, but it can be
called anything. The range
function determines the number
of times the loop runs. If one argument is passed, the loop variable
goes from 0 to one less than the argument value. If two arguments are
passed, the loop variable goes from the first argument value to one
less than the second argument value.
count = 0 command = "" while command != "quit": command = input("Enter a command: ") count = count + 1 print(f"Loop has repeated {count} times.")
command != "quit"
is true. Once the user types "quit", the loop stops. To have a loop run
forever, simply put True
for the condition.
# start of loop here print(number)
Your code
# start of loop here print(i * 2)
Your code
import random number = 0 # start of loop here number = random.randint(0, 9) print(number)
Your code
command = "" # start of loop here command = input("Enter a command: ")
Your code
# start of loop here print("Still going...")
Your code