IterationUpdating variablesA common pattern in assignment statements is an assignment statement that updates a variable, where the new value of the variable depends on the old. Show
This means “get the current value of If you try to update a variable that doesn’t exist, you get an error, because Python evaluates the right side before it
assigns a value to
Before you can update a variable, you have to initialize it, usually with a simple assignment:
Updating a variable by adding 1 is called an increment; subtracting 1 is called a decrement. The while statementComputers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that computers do well and people do poorly. Because iteration is so common, Python provides several language features to make it easier. One form of iteration in Python is the
You can almost read the More formally, here is the flow of execution for a
This type of flow is called a loop because the third step loops back around to the top. We call each time we execute the body of the loop an iteration. For the above loop, we would say, “It had five iterations”, which means that the body of the loop was executed five times. The body of the loop should change the value of one or more variables so that eventually the condition becomes false and the loop terminates. We call the variable that changes each time the loop executes and controls when the loop finishes the iteration variable. If there is no iteration variable, the loop will repeat forever, resulting in an infinite loop. Infinite loopsAn endless source of amusement for programmers is the observation that the directions on shampoo, “Lather, rinse, repeat,” are an infinite loop because there is no iteration variable telling you how many times to execute the loop. In the case of Sometimes you don’t know it’s time to end a loop until you get half way through the body. In that case you can write an infinite loop on purpose and then use the This loop is obviously an infinite loop because the logical expression on
the
If you make the mistake and run this code, you will learn quickly how to stop a runaway Python process on your system or find where the power-off button is on your computer. This program will run forever or until your battery runs out because the logical expression at the top of the loop is always true by virtue of the fact that the expression is the constant value While this is a dysfunctional infinite
loop, we can still use this pattern to build useful loops as long as we carefully add code to the body of the loop to explicitly exit the loop using For example, suppose you want to take input from the user until they type
The loop condition is Each time through, it prompts the user with an angle
bracket. If the user types
This way of writing Finishing iterations with continueSometimes you are in an iteration of a loop and want to finish the current iteration and immediately jump to the next iteration. In that case you can use the Here is an example of a loop that copies its input until the user types “done”, but treats lines that start with the hash character as lines not to be printed (kind of like Python comments).
Here is a sample run of this new program with
All the lines are printed except the one that starts with the hash sign because when the Definite loops using forSometimes we want to loop through
a set of things such as a list of words, the lines in a file, or a list of numbers. When we have a list of things to loop through, we can construct a definite loop using a The syntax of a
In Python terms, the variable
Translating this Looking at the
In particular, Loop patternsOften we use a These loops are generally constructed by:
We will use a list of numbers to demonstrate the concepts and construction of these loop patterns. Counting and summing loopsFor example, to count the number of items in a list, we would write the following
We set the variable In the body of the loop, we add 1 to the current value of Once the loop completes, the value of Another similar loop that computes the total of a set of numbers is as follows:
In this loop we do use the iteration variable. Instead of simply adding one to the As the loop executes, Neither the counting loop nor the summing loop are particularly useful in practice because there are built-in functions Maximum and minimum loopsTo find the largest value in a list or sequence, we construct the following loop:
When the program executes, the output is as follows:
The variable Before the loop starts, the largest value we have seen so far is After the first iteration, At the end of the loop, we have scanned all of the values and the variable To compute the smallest number, the code is very similar with one small change:
Again, Again as in counting and summing, the built-in functions The following is a simple version of the Python built-in
In the function version of the smallest code, we removed all of the DebuggingAs you start writing bigger programs, you might find yourself spending more time debugging. More code means more chances to make an error and more places for bugs to hide. One way to cut your debugging time is “debugging by bisection.” For example, if there are 100 lines in your program and you check them one at a time, it would take 100 steps. Instead, try to break the problem in half. Look at the middle of the program, or near it, for an intermediate value you can check. Add a If the mid-point check is incorrect, the problem must be in the first half of the program. If it is correct, the problem is in the second half. Every time you perform a check like this, you halve the number of lines you have to search. After six steps (which is much less than 100), you would be down to one or two lines of code, at least in theory. In practice it is not always clear what the “middle of the program” is and not always possible to check it. It doesn’t make sense to count lines and find the exact midpoint. Instead, think about places in the program where there might be errors and places where it is easy to put a check. Then choose a spot where you think the chances are about the same that the bug is before or after the check. Glossaryaccumulator A variable used in a loop to add up or accumulate a result. counter A variable used in a loop to count the number of times something happened. We initialize a counter to zero and then increment the counter each time we want to “count” something. decrement An update that decreases the value of a variable. initialize An assignment that gives an initial value to a variable that will be updated. increment An update that increases the value of a variable (often by one). infinite loop A loop in which the terminating condition is never satisfied or for which there is no terminating condition. iteration Repeated execution of a set of statements using either a function that calls itself or a loop.ExercisesExercise 1: Write a program which repeatedly reads numbers until the user enters “done”. Once “done” is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number, detect their mistake using
Exercise 2: Write another program that prompts for a list of numbers as above and at the end prints out both the maximum and minimum of the numbers instead of the average.
If you find a mistake in this book, feel free to send me a fix using Github. Can you set a for loop to a variable?Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.
Can you put a for loop in a variable Python?A Python for loop has two components: A container, sequence, or generator that contains or yields the elements to be looped over. In general, any object that supports Python's iterator protocol can be used in a for loop. A variable that holds each element from the container/sequence/generator.
How do you assign a statement to a variable in Python?The assignment operator, denoted by the “=” symbol, is the operator that is used to assign values to variables in Python. The line x=1 takes the known value, 1, and assigns that value to the variable with name “x”. After executing this line, this number will be stored into this variable.
Can I assign a function to a variable Python?In Python, we can assign a function to a variable. And using that variable we can call the function as many as times we want. Thereby, increasing code reusability. Simply assign a function to the desired variable but without () i.e. just with the name of the function.
|