Python: Input and Variables - Loops (
Page 3 of 4 )
Computers are good at doing repetitive tasks; they don't need to take a lunch break or go to the potty, and unless you program them to, they won't spend seven hours of their eight hour work day ambling aimlessly around the Internet. The way we get computers to do these repetitive tasks is through iteration, or loops.
The While Loop
The While Loop basically works like this: Do this, while that is true. Like when my girlfriend nags me. My brain says: Create ulcers, while she complains about me not taking out the garbage. When she stops, so does the ulcer creation. Here it is in code:
#!/usr/local/bin/python
my_count = 0
while my_count < 100:
my_count = my_count + 1
print my_count
This code creates a variable called my_count and stores the value 0 in it. Next it creates a loop that says while the value of my_count is less than 100, print the value of count. It then goes through the loop over and over again, adding 1 to the value of my_count until it reaches 100. The result of this program would be:
1
2
3
4
5
etc
etc
etc
100
A brief note: When working with Python, it is mandatory to indent by four spaces each level. So if you are doing a loop, there must be four spaces. If you add an if to that loop, it must be eight spaces etc. Here is a pseudocode example:
#!/usr/local/bin/python
some code
while variable == variable
morecode
while blah blah
more code
print something
print whatever happens after the while is escaped
We can also use the loop to force a user to enter some data, as in a password program:
#!/usr/local/bin/python
user_password =”something”
while password !=”something”:
password = raw_input(“Enter your password to continue nerd: “)
print “Welcome Captain my Captain! I didn't notice you. Did you gain weight?”
Notice that I indented the line that contained: password = raw_input. This is because it is the next level under the While statement. Then I did not indent the print statement. That is because the print statement occurs OUTSIDE of the loop and is only triggered when the loop is exited. If the user tried to use this program and did not enter the right password several times, here is what it would look like:
Enter your password to continue nerd: apples
Enter your password to continue nerd: oranges
Enter your password to continue nerd: biscuits
Enter your password to continue nerd: something
Welcome Captain my Captain! I didn't notice you. Did you gain weight?