| Goals: |
|
Computers are especially good at iteration, i.e., repeatedly executing a well-defined task. Iteration is accomplished by executing loops. The loop construct we will utilize in Python is called a while loop. A while loop will execute as long as a given conditional (something that evaluates to True or False) remains True. Each time the conditional evaluates as True, the commands within the while loop are executed.
The given code illustrates a while loop:
After setting x equal to 2, the while loop begins. The loop checks on the value of the conditional x <= 16. If the conditional evaluates to True, then the command x = 2*x is executed. If x <= 16 evaluates as False, the command is skipped and the loop is terminated. The following table summarizes the activity of the loop:
When the loop terminates, the value of x is 32.
Suppose is a positive integer. Let’s construct a function that takes as input and outputs the result of the sum
Solution. Here is one way to write it:
The variable i in the loop is called a counter. The command i = i + 1 within the loop is key, as otherwise the loop wouldn’t terminate. (If you happen to write an infinite loop, just close the window and fix the code in IDLE.) The manner in which temp is used is a common way of building a sum (or product). If you run the module and enter f(4) in the Shell, the following happens: n is set to 4, i is initialized to 1, temp is set to 0, and then the loop executes:
Figure 5.16 illustrates:
Remark: Note the last output: 500000500000L. Python stores large integers in a special way, and that’s what the L denotes, but it doesn’t have an effect on the value and can be ignored.
Let’s construct a function that does the following: The function uses randbetween(1,100) to generate a random number between 1 and 100. The function then repeatedly asks the user to guess the value of until correct. When a guess is incorrect, the function informs the user if the guess was too high or too low.
Solution. The following code can work within the definition of the function:
Figure 5.17 illustrates:
Write a function f that will take as input a positive integer and return the result of the sum
Write a function f that will take as input a positive integer and return i.e., return the result of the product:
Recall that is read as factorial.