Text
stringlengths
1
9.41k
The dealer turns over their down card, and if their total is less than 17 they must continue to draw until they reach 17 or they go over 21.[1] We donโ€™t know how many cards theyโ€™ll draw, but they must continue to draw until the condition is met.
A while loop will repeat as long as some condition is true, so itโ€™s perfect for a case like this. Hereโ€™s a little snippet of Python code, showing how we might use a ``` while loop. # Let's say the dealer has a five showing, and # then turns over a four.
That gives the dealer # nine points. They *must* draw. dealer = 9 prompt = "What's the value of the next card drawn?
" while dealer < 17: next_card = int(input(prompt)) dealer = dealer + next_card if dealer <= 21: print(f"Dealer has {dealer} points!") else: print(f"Oh, dear.
" f"Dealer has gone over with {dealer} points!") ``` Here the dealer starts with a total of nine.
Then, in the while loop, we keep prompting for the number of points to be added to the dealerโ€™s hand. Points are added to the value of dealer.
This loop will continue to execute as long as the dealerโ€™s score is less than 17.
We see this in the ``` while condition: ``` [1If youโ€™re unfamiliar with the rules of blackjack, see https://en.wikipedia.org/w](https://en.wikipedia.org/wiki/Blackjack) [iki/Blackjack](https://en.wikipedia.org/wiki/Blackjack) ----- ``` while dealer < 17: ... ``` Naturally, this construction raises some quest...
However, a while condition can be any Boolean expression, simple or compound, or any value or expression thatโ€™s truthy or falseyโ€” and in Python, thatโ€™s just about anything!
Examples: ``` lst = ['a', 'b', 'c'] while lst: print(lst.pop(0)) ``` Non-empty sequences are truthy. Empty sequences are falsey.
So as long as the list lst contains any elements, this while loop will continue.
This will print ``` a b c ``` and then terminate (because after popping the last element, the list is empty, and thus falsey). ``` while x < 100 and x % 2 == 0: ... ``` This loop will execute as long as x is less than 100 and x is even. **The condition of a while loop is checked before each iteration** ...
At the start, the dealer has nine points, so dealer < 17 evaluates to True. Since this condition is true, the body of the loop is executed.
(The body consists of the indented lines under while dealer < 17.) Once the body of the while loop has executed, the condition is checked _again.
If the condition remains true, then the body of the loop will be_ executed again.
Thatโ€™s why we call it a loop! ----- _Itโ€™s important to understand that the condition is not checked while_ _the body of the loop is executing._ The condition is always checked before executing the body of the loop. This might sound paradoxical.
Didnโ€™t we just say that after executing the body the condition is checked again? Yes. Thatโ€™s true, and itโ€™s in the nature of a loop to be a littleโ€ฆ circular.
However, what weโ€™re checking in the case of a while loop is whether or not we should execute the body. If the condition is true, then we execute the body, then we loop back to the beginning and check the condition again. **Termination of a while loop** At some point (if weโ€™ve designed our program correctly), the whil...
For example, if the dealer were to draw an eight, then adding eight points would bring the dealerโ€™s score to 17.
At that point, the condition dealer < 17 would evaluate to False (because 17 is not less than 17), and the loop terminates. **After the loop** Once a while terminates, code execution continues with the code which follows the loop. _Itโ€™s important to understand that the while condition is not evaluated_ _again after t...
"` _this line of code, the_ _value of dealer is 9,_ `while dealer < 17:` _so the condition is true._ `next_card = int(input(prompt))` _We enter the loop and_ `dealer = dealer + next_card` _the body of the loop_ _is executed._ ``` if dealer <= 21: print(f"Dealer has {dealer} points!") ...
" f"Dealer has gone over with {dealer} points!") ``` **Figure 11.2** ----- **Figure 11.3** _Loop!_ _Go back to the_ _start of the loop,_ _and check the_ _condition again._ _If the condition is_ _still true, we execute_ _the body again._ **Figure 11.4** _Since weโ€™ve looped,_ _we execute the ...
" ``` _โ€ฆat which point_ `while dealer < 17:` _we exit the loop_ `next_card = int(input(prompt))` _and continue with_ ``` dealer = dealer + next_card ``` _the program code_ _after the loop._ _Note that we donโ€™t_ `if dealer <= 21:` _re-evaluate the condition_ `print(f"Dealer has {dealer} points!")` _af...
" f"Dealer has gone over with {dealer} points!") ``` **Figure 11.7** ###### Another example: coffee shop queue with limited coffee Hereโ€™s another example of using a while loop. Letโ€™s say we have a queue of customers at a coffee shop.
They all want coffee (of course). The coffee shop offers small (8 oz), medium (12 oz) and large (20 oz) coffees.
However, the coffee shop has run out of beans and all they have is whatโ€™s left in the urn.
The baristas have to serve the customers in order, and can only take orders as long as thereโ€™s at least 20 oz in the urn. We can write a function which calculates how many people are served in the queue and reports the result.
To do this weโ€™ll use a while loop.
Our function will take three arguments: the number of ounces of coffee in the urn, a list representing the queue of orders, and the minimum amount of coffee that must remain in the urn before the baristas must stop taking orders.
The queue will be a list of valuesโ€”8, 12, or 20โ€”depending on which size each customer requests.
For example, ``` queue = [8, 12, 20, 20, 12, 12, 20, 8, 12, ...] ``` Letโ€™s call the amount of coffee in the urn reserve, the minimum ``` minimum, and our queue of customers customers.
Our while condition is reserve >= minimum. ``` ----- ``` def serve_coffee(reserve, customers, minimum): customers_served = 0 while reserve >= minimum: reserve = reserve - customers[customers_served] customers_served += 1 print(f"We have served {customers_served} customers, " f"and...
Then, within the body of the loop, we take the customers in order, andโ€”one customer at a timeโ€”we deduct the amount of coffee theyโ€™ve ordered.
Once the reserve drops below the minimum, we stop taking orders and report the results. **What happens if the while condition is never met?** Letโ€™s say we called the serve_coffee() function (above), with the arguments, 6, lst, and 8, where lst is some arbitrary list of orders: ``` serve_coffee(6, lst, 8) ``` In th...
Thus, the body of the loop would never execute, and the function would report: ``` We have served 0 customers, and we have only 6 ounces remaining. ``` So itโ€™s possible that the body of any given while loop might never be executed.
If, at the start, the while condition is false, Python will skip past the loop entirely! ###### 11.3 Input validation with while loops A common use for a while loop is input validation. Letโ€™s say we want the user to provide a number from 1 to 10, inclusive. We present the user with a prompt: ``` Pick a number from ...
Usually what we do in cases like this is we continue to prompt the user until they supply a suitable value. ----- ``` Pick a number from 1 to 10: 999 Invalid input. Pick a number from 1 to 10: -1 Invalid input. Pick a number from 1 to 10: 7 You have entered 7, which is a very lucky number! ``` But hereโ€™...
Will they do so on the first try? On the second try? On the fourth try? On the twelfth try? We just donโ€™t know! Thus, a while loop is the perfect tool. How would we implement such a loop in Python?
What would serve as a condition? Plot twist: In this case, weโ€™d choose a condition thatโ€™s always true, and then only break out of the loop when we have a number in the desired range.
This is a common idiom in Python (and many other programming languages). ``` while True: n = int(input("Pick a number from 1 to 10: ")) if 1 <= n <= 10: break print("Invalid input.") if n == 7: print("You have entered 7, " "which is a very lucky number!") else: print(f"You have ...
Good for you!") ``` Notice what weโ€™ve done here: the while condition is the Boolean literal True. This can never be false! So we have to have a way of exiting the loop. Thatโ€™s where break comes in.
break is a Python keyword which means โ€œbreak out of the nearest enclosing loop.โ€ The if clause includes a condition which is only true if the userโ€™s choice is in the desired range. Therefore, this loop will execute indefinitely, until the user enters a number between one and 10. As far as user experience goes, this is ...
Rather than complaining and exiting, our program can ask again when it receives invalid input. **A note of caution** While the example above demonstrates a valid use of break, break should be used sparingly.
If thereโ€™s a good way to write a while loop without using break then you should do so!
This often involves careful consideration of while conditionsโ€”a worthwhile investment of your time. Itโ€™s also considered bad form to include more than one break statement within a loop.
Again, please use break sparingly. ----- ###### Other applications of while loops Weโ€™ll see many other uses for the while loop, including performing numeric calculations and reading data from a file. ###### Comprehension check 1.
What is printed? ``` >>> c = 5 >>> while c >= 0: ... print(c) ... c -= 1 ``` 2. How many times is โ€œHelloโ€ printed? ``` >>> while False: ... print("Hello") ... ``` 3.
Whatโ€™s the problem with this while loop? ``` >>> while True: ... print("The age of the universe is...") ... ``` 4. How many times will this loop execute? ``` >>> while True: ...
break ... ``` 5. How many times will this loop execute? ``` >>> n = 10 >>> while n > 0: ... n = n // 2 ... ``` 6.
Hereโ€™s an example showing how to pop elements from a list within a loop. ``` >>> while some_list: ... element = some_list.pop() ...
# Now do something useful with that element ... ``` Ask yourself: ----- - Why does this work? - When does the while loop terminate? - What does this have to do with truthiness or falsiness? - Is an empty list falsey? ###### Challenge! How about this loop?
Try this out with a hand-held calculator. ``` EPSILON = 0.01 x = 2.0 guess = x while True: guess = sum((guess, x / guess)) / 2 if abs(guess ** 2 - x) < EPSILON: break print(guess) ``` (abs() is a built-in Python function which calculates the absolute value of a number.) What does this loop d...
Itโ€™s clear that 15 is a divisor of both 120 and 105: 120/15 = 8 105/15 = 7. How do we know that 15 is the greatest common divisor?
One way is to factor both numbers and find all the common factors. Weโ€™ve found the common factors of 120 and 105, which are 3 and 5, and their product is 15.
Therefore, 15 is the greatest common divisor of 120 and 105.
This works, and it may well be what you learned in elementary algebra, however, it becomes difficult with larger numbers and isnโ€™t particularly efficient. ----- ###### Euclidโ€™s algorithm Euclid was an ancient Greek mathematician who flourished around 300 BCE.
Hereโ€™s an algorithm that bears Euclidโ€™s name.
It was presented in Euclidโ€™s Elements, but itโ€™s likely that it originated many years before Euclid.[2] **Euclidโ€™s GCD algorithm** **input : Positive integers, ๐‘Ž** and ๐‘ **output: Calculates the GCD of ๐‘Ž** and ๐‘ **while ๐‘** _does not equal 0 do_ Find the remainder when we divide ๐‘Ž by ๐‘; Let ๐‘Ž equal ๐‘; Let ๐‘ ...
Say we have ๐‘Ž= 342 and ๐‘= 186. First, we find the remainder of 342/186. 186 goes into 342 once, leaving a remainder of 156. Now, let ๐‘Ž= 186, and let ๐‘= 156.
Does ๐‘ equal 0? No, so we continue. Find the remainder of 186/156. 156 goes into 186 once, leaving a remainder of 30. Now, let ๐‘Ž= 156, and let ๐‘= 30. Does ๐‘ equal 0?
No, so we continue. Find the remainder of 156/30. 30 goes into 156 five times, leaving a remainder of 6. Now, let ๐‘Ž= 30, and let ๐‘= 6. Does ๐‘ equal 0? No, so we continue. Find the remainder of 30/6.
6 goes into 30 five times, leaving a remainder of 0. Now, let ๐‘Ž= 6, and let ๐‘= 0. Does ๐‘ equal 0?
Yes, so we are done. The GCD is the value of ๐‘Ž, so the GCD is 6. Pretty cool, huh? ###### Why does it work? If we have ๐‘Ž and ๐‘ both positive integers, with ๐‘Ž> ๐‘, then we can write ๐‘Ž= ๐‘๐‘ž+ ๐‘Ÿ where ๐‘ž is the quotient of dividing ๐‘Ž by ๐‘ (Euclidean division) and ๐‘Ÿ is the remainder.
For example, in the first step of our example (above) we have 342 = 1 ร— 186 + 156. It follows that the GCD of ๐‘Ž and ๐‘ equals the GCD of ๐‘ and ๐‘Ÿ.[3] That is, 2Some historians believe that Eudoxus of Cnidus was aware of this algorithm (c. 375 BCE), and itโ€™s quite possible it was known before that time. 3If we have...
Let ๐‘‘ be a common divisor of ๐‘Ž and ๐‘. Since ๐‘‘ divides ๐‘Ž and ๐‘‘ divides ๐‘, then there exist integers ๐‘›, ๐‘š, such that ๐‘Ž= ๐‘‘๐‘š and ๐‘= ๐‘‘๐‘›.
By substitution, we have ๐‘‘๐‘š= ๐‘‘๐‘ž๐‘›+ ๐‘Ÿ. Rearranging terms we have ๐‘‘๐‘šโˆ’๐‘‘๐‘ž๐‘›= ๐‘Ÿ.
By factoring, we have ๐‘‘(๐‘šโˆ’๐‘ž๐‘›) = ๐‘Ÿ. ----- gcd(๐‘Ž, ๐‘) = gcd(๐‘, ๐‘Ÿ). Thus, by successive divisions, we continue to reduce the problem to smaller and smaller terms.
At some point in the execution of the algorithm, ๐‘ becomes 0, and we can divide no further.
At this point, what remains as the value for ๐‘Ž is the GCD, because the greatest common divisor of ๐‘Ž and zero is ๐‘Ž! This algorithm saves us from having to factor both terms. Consider a larger problem instance with ๐‘Ž= 30759 and ๐‘= 9126. Factoring these would be a nuisance, but the Euclidean algorithm takes only eigh...
Thus, while loops provide a condition, and we loop until that condition (whatever it may be) no longer holds true. Python has another type of loop which is useful when: - we know exactly how many iterations we require, or - we have some sequence (for example, list, tuple, or string) and we wish to perform calcula...
Thus the set of common divisors of ๐‘Ž and ๐‘ is the same as the set of common divisors of ๐‘ and ๐‘Ÿ. Thus the greatest element of each of these sets must be the same.
Therefore, we have gcd(๐‘Ž, ๐‘) = gcd(๐‘, ๐‘Ÿ), as desired. ----- This new kind of loop is the for loop. for loops are so named because they iterate for each element in some iterable.
Python for loops iterate over some iterable. Always.[4] Whatโ€™s an iterable? Something we can iterate over, of course! And what might that be?
The sequence types weโ€™ve seen so far (list, tuple, string) are sequences, and these are iterable. We can also produce other iterable objects (which we shall see soon). Hereโ€™s an example.
We can iterate over a list, [1, 2, 3], by taking the elements, one at a time, in the order they appear in sequence. ``` >>> numbers = [1, 2, 3] >>> for n in numbers: ...
print(n) ... 1 2 3 ``` See? In our for loop, Python iterated over the elements (a.k.a. โ€œmembersโ€) of the list provided. It started with 1, then 2, then 3.
At that point the list was exhausted, so the loop terminated. If it helps, you can read for n in numbers: as โ€œfor each number, n, in the iterable called โ€˜numbersโ€™.โ€ This works for tuples as well. ``` >>> letters = ('a', 'b', 'c') >>> for letter in letters: ...
print(letter) ... a b c ``` Notice the syntax: for <some variable> in <some iterable>:. As we iterate over some iterable, we get each member of the iterable in turn, one at a time.
Accordingly, we need to assign these members (one at a time) to some variable. In the first example, above the variable has the identifier n. 4for loops in Python work rather differently than they do in many other languages.
Some languages use counters, and thus for loops are count-controlled.
For example, in Java we might write ``` for (int i = 0; i < 10; ++i) { // do something ``` In this case, thereโ€™s a counter,} `i, which is updated at each iteration of the loop.` Here we update by incrementing i using ++i (which in Java increments i).
The loop runs so long as the control condition i < 10 is true. On the last iteration, with i equal to nine, i is incremented to ten, then the condition no longer holds, and the loop exits.
This is not how for loops work in Python! Python for loops always iterate over an iterable. ----- ``` >>> numbers = [1, 2, 3] >>> for n in numbers: ...
print(n) ... ``` As we iterate over numbers (a list), we get one element from the list at a time (in the order they appear in the list). So at the first iteration, n is assigned the value 1.
At the second iteration, n is assigned the value 2. At the third iteration, n is assigned the value 3.
After the third iteration, there are no more elements left in the sequence and the loop terminates. Thus, the syntax of a for loop requires us to give a variable name for the variable which will hold the individual elements of the sequence.
For example, we cannot do this: ``` >>> for [1, 2, 3]: ... print("Hello!") ``` If we were to try this, weโ€™d get a SyntaxError.
The syntax that must be used is: ``` for <some variable> in <some iterable>: # body of the loop, indented ``` where <some variable> is replaced with a valid variable name, and <some ``` iterable> is the name of some iterable, be it a list, tuple, string, or other ``` iterable. ###### Iterating over a range of ...
This is a new type that weโ€™ve not seen before. ``` range objects are iterable, and we can use them in for loops. ``` We can create a new range object using Pythonโ€™s built-in function ``` range().
This function, also called the range constructor, is used to create range objects representing arithmetic sequences.[5] ``` Before we create a loop using a range object, letโ€™s experiment a little. The simplest syntax for creating a range object is to pass a positive integer as an argument to the range constructor.
What we get back is a range object, which is like a list of numbers.
If we provide a positive integer, n, as a single argument, we get a range object with n elements. ``` >>> r = range(4) ``` Now we have a range object, named r.
Letโ€™s get nosy. 5An arithmetic sequence, is a sequence of numbers such that the difference between any number in the sequence and its predecessor is constant.
1, 2, 3, 4, โ€ฆis an arithmetic sequence because the difference between each of the terms is 1.
Similarly, 2, 4, 6, 8, โ€ฆis an arithmetic sequence because the difference between each term is 2. Python range objects are restricted to arithmetic sequences of integers. ----- ``` >>> len(r) 4 ``` OK.
So r has 4 elements.
That checks out. ``` >>> r[0] 0 >>> r[1] 1 >>> r[2] 2 >>> r[3] 3 >>> r[4] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: range object index out of range ``` We see that the values held by this range object, are 0, 1, 2, and 3, in that order. Now letโ€™s use a ...
Hereโ€™s the simplest possible example: ``` >>> for n in range(4): ... print(n) ``` What do you think this will print? - The numbers 1 through 4? - The numbers 0 through 4?
(since Python is zero-indexed) - The numbers 0 through 3? (since Python slices go up to, but do not include, the stop index) Hereโ€™s the answer: ``` >>> for n in range(4): ...
print(n) ... 0 1 2 3 ``` Zero through three.