Fork/Clone Ch.05 Looping Jedi Training
Fork/Clone Ch.05 Looping Jedi Training
There are two major types of loops in Python, FOR loops and WHILE loops. If you want to repeat a certain number of times, use a FOR loop. If you want to repeat until something happens (like the user hits the quit button) then use a WHILE loop.
For example, a FOR loop can be used to print all student records since the computer knows how many students there are. A WHILE loop would need to be used to check when a user hits the mouse button since the computer has no idea how long it will have to wait.
The FOR loop example below runs the print statement five times. Create a new file and try out the code. It could just as easily run 100 or 1,000,000 times just by changing the 5 to the desired number of times to loop. Note the similarities of how the FOR loop is written to the IF Statement. Both end in a colon, and both use indentation to specify which lines are affected by the statement.
for i in range(5):
print("I love Python!")
The i is a variable that keeps track of how many times the program has looped. It is a new variable and can be named any legal variable name. Programmers often use i for the variable name, because the i is short for increment or item. This variable helps track when the loop should end. A program does not need to name the variable i, it could be named something else. For example a programmer might use lineNumber if she was processing a text file.
The range function controls how many times the code in the loop is run. In this case, five times.
The next example code will print "Please," five times and "Help me learn Python!" only once. "Help me learn Python!" is not indented so it is not part of the FOR loop and will not print until the FOR loop completes.
for i in range(5):
print("Please,")
print("Help me learn Python!")
This next code example takes the prior example and indents line 3. This change will cause the program to print "Please," and "Help me learn Python!" five times. Since the statement has been indented "Help me learn Python!" is now part of the for loop and will repeat five times just like the word "Please,".
for i in range(5):
print("Please,")
print("Help me learn Python!")
Predict what the following code will do and then try it out.
for i in range(10):
print(i)
Did the code do what you expected? Did it print 10 numbers? YES! Did it print the 10 numbers you were expecting? Probably not! The code above printed the numbers 0 to 9. Notice that the loop starts at 0 and does not include the number 10. It is natural to assume that range(10) would include 10, but it stops just short of it. If you remember numbering systems this makes sense. Numbering systems start with 0. Although this actually makes sense it seems to be a very difficult thing for many programmers to remember.
If a programmer wants to go from 1 to 10 instead of 0 to 9, there are a couple ways to do it. The first way is to send the range function two numbers instead of one. The first number is the starting value, the second is just beyond the ending value.
It does take some practice to get used to the idea that the FOR loop will include the first number (INCLUSIVE), but not the second number (EXCLUSIVE). The example below specifies a range of (1,11), and the numbers 1 to 10 are printed. The starting number 1 is included, but not the ending number of 11.
for i in range(1, 11):
print(i)
Another way to print the numbers 1 to 10 is to still use range(10) and have the variable i go from 0 to 9. But just before printing out the variable the programmer adds one to it. This also works to print the numbers 1 to 10. Either method works just fine.
# Print the numbers 1 to 10.
for i in range(10):
print(i + 1)
If the program needs to count by 2's or use some other increment, that is easy. Just like before there are two ways to do it. The easiest is to supply a third number to the range function that tells it to count by 2's. The third parameter of the range function is called the STEP. The second way to do it is to go ahead and count by 1's, but multiply the variable by 2. The code example below shows both methods.
# Two ways to print the even numbers 2 to 10
for i in range(2,12,2): #Could also use 11 as the second number
print(i)
for i in range(5):
print((i + 1) * 2)
It is also possible to count backwards down towards zero by giving the range function a negative STEP. In the example below, start at 10, go down to but not including 0, and do it by -1 increments. The hardest part of creating these loops is to accidentally switch the start and end numbers. The program starts at the larger value, so it goes first. Normal FOR loops that count up start with the smallest value listed first in the range function.
for i in range(10, 0, -1):
print(i)
If the numbers that a program needs to iterate through don't form an easy pattern, it is possible to pull numbers out of a list. (A full discussion of lists is covered later. This is just a preview of what you can do.)
for i in [2,6,4,2,4,6,7,4]:
print(i)
The following two blocks of code are very similar but have different output. Try to predict the output of each block of code and record in your notebook. Then try to run them to see if you are a true CODER yet or not!
# BLOCK 1: What does this print? Why?
for i in range(3):
print("a")
for j in range(3):
print("b")
# BLOCK 2: What does this print? Why?
for i in range(3):
print("a")
for j in range(3):
print("b")
print("Done")
A common operation in working with loops is to keep a running total. This "running total" code pattern is used a lot. Keep a running total of a score, total a person's account transactions, use a total to find an average, etc. You might want to actually write out this code in your notebook to refer to in the future. In the code below, the user enters five numbers and the code totals up their values.
total = 0
for i in range(5):
new_number = int(input("Enter a number: " ))
total += new_number
print("The total is: ", total)
Note that line 1 creates the variable total, and sets it to an initial amount of zero. It is easy to forget the need to create and initialize the variable to zero. Without it the computer will complain when it hits line 4. It doesn't know how to add new_number to total because total hasn't been given a value yet.
A common mistake is to use i to total instead of new_number. Remember, we are keeping a running total of the values entered by the user, not a running total of the current loop count.
Speaking of the current loop count, we can use the loop count value to solve some mathematical operations. For example, can you determine what the following code does?
# What is the value of sum?
sum = 0
for i in range(1, 101):
sum += i
print(sum)
What does the following code do? Try it out!
total = 0
for i in range(5):
new_number = int(input( "Enter a number: "))
if new_number == 0:
total += 1
print("You entered a total of", total, "zeros")
A programmer that understands the nested for loops and running totals should be able to predict the output of the three programs below. Don't go over this next section too fast. Give it a try and predict the output of each program. Then copy it into a Python program and run it to see if you are right. If you aren't, figure out why.
# What is the value of a?
a = 0
for i in range(10):
a += 1
print(a)
# What is the value of a?
a = 0
for i in range(10):
a += 1
for j in range(10):
a += 1
print(a)
# What is the value of a?
a = 0
for i in range(10):
a += 1
for j in range(10):
a += 1
print(a)
A FOR loop is used when a program knows it needs to repeat a block of code for a certain number of times. A WHILE loop is used when a program needs to loop until a particular condition occurs.
Oddly enough, a WHILE loop can be used anywhere a FOR loop is used. It can be used to loop until an increment variable reaches a certain value. Why have a FOR loop if a WHILE loop can do everything? The FOR loop is simpler to use and code. A FOR loop that looks like this:
for i in range(10):
print(i)
...can be done with a WHILE loop that looks like this:
i = 0
while i < 10:
print(i)
i += 1
Line 1 of the WHILE loop sets up a variable that will be used to count the number of times the loop has been executed. This happens automatically in a FOR loop eliminating one line of code. Line 2 contains the actual WHILE loop. The format of the while loop is very similar to the IF statement. If the condition holds, the code in the loop will repeat. Line 4 adds to the increment value. In a FOR loop this happens automatically, eliminating another line of code. As one can see from the code, the FOR loop is more compact than a WHILE loop and is easier to read. Otherwise programs would do everything with a WHILE loop.
A common mistake is to confuse the FOR loop and the WHILE loop. The code below shows a programmer that can't quite make up his/her mind between a FOR loop or a WHILE loop.
Do not run this code. It will keep going forever and you will have to force quit Pycharm.
while range(10): #DO NOT RUN THIS CODE!
print(i)
The range function only works with the for loop. Do not use it with the while loop!
In your notebook predict the output of the following code then run it.
i = 1
while i <= 2 ** 32:
print(i)
i *= 2
A very common operation is to loop until the user performs a request to quit:
quit = "n"
while quit == "n":
quit = input("Do you want to quit? ")
There are several ways for a loop to quit. Using a Boolean variable to trigger the event is probably the best way of handling this. Here's an example:
done = False
grit = 0
while not done:
quit = input("Do you want to quit? ")
if quit == "y":
done = True
else:
grit+=1
print("You didn't quit ",grit," times!")
Booleans (True or False) can be rather confusing to understand. For example in the above code we set done = False in the first line. The variable "done" could be any word but it is a nice choice because it makes the English sound good:) Sometimes students think that "while not done" should mean "while not false" but this is NOT what it means. The way to read "while not done" is to say "while the variable done is NOT true". Read this paragraph about 10-20 times until you have a good understanding of this Boolean method. You will use this in your future programs.
This is a good of place as any to talk about random numbers in Python. By default, Python does not know how to make random numbers. It is necessary to have Python import a code library that can create random numbers. So to use random numbers, the first thing that should appear at the top of the program is an import statement:
import random
After this, random numbers can be created with the randrange function. For example, the code below creates random numbers from 0 to 49. Remember, the first number is zero and the second number is exclusive. Notice the following format is used: modulename.function()
my_number = random.randrange(50)
The next code example generates random numbers from 100 to 200. Just like the range function the first number is inclusive and the second number is exclusive. Therefore if you want random numbers up to and including 200, specify 201.
my_number = random.randrange(100, 201)
.randrange will also take a 3rd parameter called the step value. Below I can pick a random even number between 2 and 100.
my_number = random.randrange(2, 101, 2)
Another method we can use is .randint. It's like .randrange but will ONLY take a starting and ending value. It will not take the step value. The end value, however, is inclusive. So basically, it is exactly like random.randrange (a, b+1) Below I can pick a random number between 1 and 100 which will include both the 1 and the 100.
my_number = random.randint(1, 100)
All of the prior code generates integer numbers. If a floating point number is desired, a programmer may use the random function. Confusing I know. Here the function has the same name as the module. The code below generates a random number from 0 to 1 such as 0.4355991106620656.
my_number = random.random()
With some simple math, this number can be adjusted. How would I create random floating point numbers between 10 and 15? I'm going to get a number between 0 and 1. Therefore, if I multiply that number by 5, I will have a floating number between 0 and 5. Now if I add 10 I will have a floating number between 10 and 15.
my_number = random.random() * 5 + 10
You might face a situation in which you need to exit a loop completely when an external condition is triggered or there may also be a situation when you want to skip a part of the loop and start next execution. Python provides break and continue statements to handle such situations and to have good control on your loop.
The break statement in Python terminates the current loop and resumes execution at the next statement.
The most common use for break is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while and for loops as seen in the examples below.
# First Example: Prints out death and then stops
for letter in 'DEATH STAR':
if letter == '':
break
print ('Current Letter :', letter)
# Second Example: Counts down from 10-6 but then stops.
var = 10
while var > 0:
print ('Current variable value :', var)
var = var -1
if var == 5:
break
print ("Sorry, the Death Star shot early!")
This will produce the following result:
Current Letter : D
Current Letter : E
Current Letter : A
Current Letter : T
Current Letter : H
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Sorry, the Death Star shot early!
The continue statement in Python returns the control to the beginning of the while loop. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.
The continue statement can be used in both while and for loops also as seen in the examples below.
# First Example: Eliminates the space
for letter in 'DEATH STAR':
if letter == ' ':
continue
print ('Current Letter :', letter)
# Second Example: prints even numbers up to 10
var = 0
while var <=10:
var = var+1
if var%2 != 0:
continue
print ('Current value :', var)
print ("Good bye!")
This will produce following result:
Current Letter : D
Current Letter : E
Current Letter : A
Current Letter : T
Current Letter : H
Current Letter : S
Current Letter : T
Current Letter : A
Current Letter : R
Current value : 2
Current value : 4
Current value : 6
Current value : 8
Current value : 10
Finally, you can also use the keyword pass. This can be just used for a place holder for later code. What happens if you use the following code but you take the pass keyword out?
var = 0
while var <=10:
var += 1
if var%2 != 0:
pass
print ('Current value :', var)
print ("Good bye!")
Ask a user for the number of sides of a polygon and then have the turtle draw it. Have your sides be 100 units long. Can you do it in less than 10 lines of code?
The idea for Camel originally came from the Heath Users Group and was published in 1979. You can play it at http://eturnerx.com/files/stories/camel.html.
The idea is to ride your camel across the desert while being chased. You need to manage your thirst, how tired the camel is, and how far ahead of the natives you are.
The game is flexible. For example, you could create a Star Wars themed versions of this game where you need to ride a tauntaun across Hoth. It is easy to add sandstorms and other random events to the game to make it more interesting. Even though it is only a text-based game, playing it can become very addicting.
One of the Jedi Tasks in the repository is for you to create your own "camel-like" game. Please make it entertaining. The criteria/pseudo code are below.
Here are the steps to complete this program. Feel free to modify and add to it. Remember to comment your code while you are writing it. Try the game with friends and family.
1.) First print the instructions to the screen. Do this with multiple print statements. Don't use one print statement and multiple \n characters to jam everything on one line.
2.) Create a boolean variable called done and set to False.
3.) Create a while loop that will keep looping while not done.
4.) Inside the loop, print out the following:
A. Drink from your canteen.
B. Ahead moderate speed.
C. Ahead full speed.
D. Stop for the night.
E. Status check.
Q. Quit.
5.) Ask the user for their choice. Make sure to add a space before the quote so the user input doesn't run into your text.
6.) If the user's choice is Q, then set done to True. By doing something like user_choice.upper() instead of just user_choice in your if statement you can make it case insensitive.
7.) Test and make sure that you can quit out of the game.
8.) Before your main program loop, create variables for miles traveled, thirst, camel tiredness. Set these to zero.
9.) Create a variable for the distance the natives have traveled and set it to -20. (Twenty miles back.)
10.) Create and set an initial number of drinks in the canteen.
11.) Add an elif in your main program loop and see if the user is asking for status. If so, print out something like this:
Miles traveled: 0
Drinks in canteen: 3
The natives are 10 miles behind you.
12.) Add an elif in your main program loop and handle if the user wants to stop for the night. If the user does, reset the camel's tiredness to zero. Print that the camel is happy, and move the natives up a random amount from 7 to 14 or so.
13.) Add an elif in your main program loop and handle if the user wants to go ahead full speed. If the user does, go forward a random amount between 10 and 20 inclusive. Print how many miles the user traveled. Add 1 to thirst. Add a random 1 to 3 to camel tiredness. Move the natives up 7 to 14 miles.
14.) Add an elif in your main program loop and handle if the user wants to go ahead moderate speed. If the user does, go forward a random amount between 5 and 12 inclusive. Print how many miles the user traveled. Add 1 to thirst. Add 1 to camel tiredness. Move the natives up 7 to 14 miles.
15.) Add an elif in your main program loop and handle if the user wants to drink from the canteen. If the user does, make sure there are drinks in the canteen. If there are, subtract one drink and set the player's thirst to zero. Otherwise print an error.
16.) In the loop, print "You are thirsty." if the user's thirst is above 4.
17.) Print "You died of thirst!" if the user's thirst is above 6. Set done to true. Make sure you create your code so that the program doesn't print both "You are thirsty" and "You died of thirst!" Use elif as appropriate.
18.) Print "Your camel is getting tired." if the camel's tiredness is above 5.
19.) Print "Your camel is dead." if the camel's tiredness is above 8. Like the prior steps, print one or the other. It is a good idea to include a check with the done variable so that you don't print that your camel is getting tired after you died of thirst.
20.) If the natives have caught up, print that they caught the player and end the game.
21.) Else if the natives are less than 15 miles behind, print "The natives are getting close!"
22.) If the user has traveled 200 miles across the desert, print that they won and end the game. Make sure they aren't dead before declaring them a winner.
23.) Add a one-in-twenty chance of finding an oasis. Print that the user found it, refill the canteen, reset player thirst, and rest the camel.
24.) Play the game and tune the numbers so it is challenging but not impossible. Fix any bugs you find.
25.) Remember that it is good idea to put blank lines between logical groupings of code in your program. For example, put a blank line after the instructions, and between each user command.
26.) To prevent bad message combinations, such as printing "You died of thirst." and "You found an oasis!" on the same turn, use the and operator. Such as,
if not done and thirst > 4:
27.) COMMENT, COMMENT, COMMENT!!!!!