Python Week C

You are reading the homework for Week C of Python.

Let's learn about the while-loop.

What is a while-loop? It is a conditional statement that lets you repeat code, but only if a given condition is true. It's pretty darn useful.

Let's define a variable.

index = 0

I called it index because I'm going to use it to keep count of something.

Now, I want to increment it! Why? I could be keeping track of inventory at some company, students taking role call in class or robots visiting a website.

One way to do that is like this:

index = index + 1

Looks very bizarre, doesn't it? Upon further inspection, it actually makes complete sense: I'm setting the "new" value of index to be whatever the "old" value is plus the number 1.

Don't let the equals sign fool you into thinking that we are dealing with the equality from math. The creator of Python chose to use the equals sign here probably because of the familiarity we all have with it in an effort to make his language more popular, but technically it was a completely arbitrary choice. He could have just as easily have used the following symbol:

index <- index + 1

Which kind of makes more sense to me at least, but it does waste an extra character of space.

Try adding the first two lines above into a python program, print the index variable at the end of your program, and see what it says.

But that's not enough, right? How do we increment it more? A LOT more?

That's where the while-loop comes in.

apples = 0

while apples < 100:
    apples = apples + 1

print(apples)

Type the lines above into your program and run it. What is the value?

Sometimes is useful to be able to run a loop forever. To do that, we use the "True" keyword.

while True:
    print("apple")

Add this code to the end of your program and run it.

Wanna get crazier? I know exactly how.

apples = ""

while True:
    apples = apples + "apple"
    print(apples)

Add the code above to the end of your program and run that as well.

Alright, let's calm down, because we're done.

P.S. If you only want to run your while-loop finitely many times, try using a for-loop instead.

for count in range(20):
    print("Number: " + str(count))

Run the for-loop above in your program. Notice anything odd?

Okay, now you're done. For real this time.