Python Tutorial 5
Python Tutorial 5
Previously I talked about how you can loop with for. We can also continue looping as long as a
condition is true with a while loop. While loops are used when you don't know how many times
you will have to loop.
Here we’ll generate a random number with the random module and randrange(). We will then
use the while loop to guess the random value and output it.
CODE
# The value we increment in the while loop is defined before the loop
i=1
Break and continue are very useful. Continue stops executing the code that remains in the loop
and jumps back to the top. While break ends execution and jumps directly to the code that lies
immediately outside of the loop.
Here we’ll cycle from 0 to 20 with a while loop. If a number is even will use continue to skip
printing it. If it is odd we’ll print it. We’ll then end execution with break if the value ever reaches
15.
CODE
i=1
while i <= 20:
# Increment i
i += 1
For this problem I want you to draw a pine tree after asking the user for the number of rows.
This problem is the most difficult you have had so far, but it will teach a lot. Feel free to use any
resources online to solve it.
Here are some additional tips to help you solve the problem.
Tip 1
Tip 2
I know that this is the number of spaces and hashes for the tree
4-1
3-3
2-5
1-7
0-9
Spaces before stump = Spaces before top
TIP 3
Solution
CODE
# Get the number of rows for the tree
tree_height = input("How tall is the tree : ")
print("#")