Tuesday, April 23, 2013

While Loops

     Now that you know about for loops, you need to learn while loops, another element of input.
     While loops are loops that keep going unless a condition is false, sort of like an if statement. While loops are said in the same way as an if statement. Of course, the most common way to use while loops is with input, so we will do that. Open a new program and type this:

print("Type 3 to continue, anything else to quit.")
someInput=input()
while someInput == 3:
    print("Thank you for the 3. Very kind of you.")
    print("Type 3 to continue, anything else to quit")
    someInput=input()
print("That's not a 3, so I'm quitting now.")

     Run the program. You should get the first print statement. If you type a 3, you should get "Thank you for the 3. Very kind of you." then "Type 3 to continue, anything else to quit." If you type anything else, you should get "That's not a 3, so I'm quitting now." So, the word after while wasn't the name of a loop. That only happens with for loops. Now, what if you make a mistake with loops? That is called a runaway loop. Runaway loops are loops that keep on going forever because you made a mistake, and there's no way to get out. To get out of a runaway loop, you have to press CTRL+C. That crashes any program.
     Now, what did the while loop do? Well, while loops are like for loops, except they keep going unless a condition is false. While loops always ask the program, "Am I done yet?" until it is done. I hope you get while loops already, since I can't think of anything else to help you get it.
     Well... There wasn't much to talk about in this article. Here, you learned about while loops. There still isn't much you know about loops, but I can challenge you to do this; try to make a runaway loop that uses input (it's easy, trust me), and one that doesn't use input (even easier).

No comments:

Post a Comment