FOR LOOP:
The for loop takes a collection of items and executes a block of code once for each item in the collection.
WHILE LOOP:
The while loop runs as long as, or while, a certain condition is true
This is REALLY IMPORTANT... While loops will continue to run until a certain condition is met
We need a way out of a while loop, otherwise we have an INFINITE LOOP... More on this later
True or False
Counter
Condition
#Create a counter for the while loop:
current_number = 1
#Start the while loop
while current_number <= 5:
print(current_number)
#You MUST do something with the counter!!
current_number = current_number + 1
You don't have to count up! You can change the counter any way you'd like!
Counters can count up, down, or jump around in increments too!!
The short answer? No. We don't need one, but we need a way to exit our for loop. This can be:
a word that the user types in
a flag that sets a run condition
a break
#Create a counter for the while loop:
run_me = True
#Start the while loop
while run_me:
user_in = input("Keep Going?? (Y or N): ")
if(user_in == N):
#Set this to false, so the loop will stop!
run_me = False
#Create a counter for the while loop:
while True:
num = int(input("Enter a Number: "))
if num > 10:
print("Run My Loop...")
else:
print("We're stopping now!")
break;
Using the syntax above, create 3 different while loops which:
Counts from 1 to 10 but only prints even numbers
Creates a countdown from 10 to 1, then print "Lift-off!" at the end.
See if you can implement time.sleep in this one!
Prints the word Banana until the user tells it to stop
Hint... You Need User Input In This Loop!!!
#Create a counter for the while loop:
current_number = 1
#Start the while loop
while current_number <= 5:
print(current_number)
What happens when we have a counter, but we don't do anything with it inside the for loop?? We get something called an INFINITE LOOP
This type of loop never stops running, and will eventually crash your program because it uses up all of the computers memory!! NO BUENO!
Be really careful when dealing with counters!
Write a simple program which will output what's shown, BUT...
You Must use a flag or break to exit
ANY version typed of yes or no should be registered as a yes or no. That means: Yes, yes, YeS, yES, etc... should work
Add a counter for yes and maybe replies and display the count when exiting
Add a random fun response every time they say yes.
Add a maybe response
if the user selects maybe, the computer randomly decides yes or no, alerts the user what it decided, and the program continues based on the computer's decision
BONUS:
Randomly assign a point system after every yes that keeps track of the user's SCORE.
For instance, a yes can be worth 1, 0, or -1 points, so, you never know how much you'll get per yes!
Make the user play at least 3 times. If they quit when their score is positive, they win. If they quit when the score is negative, they lose