# Preamble script block to identify host, user, and kernel
import sys
! hostname
! whoami
print(sys.executable)
print(sys.version)
print(sys.version_info)
Count-controlled repetition is also called definite repetition because the number of repetitions is known before the loop begins executing. When we do not know in advance the number of times we want to execute a statement, we cannot use count-controlled repetition. In such an instance, we would use sentinel-controlled repetition.
A count-controlled repetition will exit after running a certain number of times. The count is kept in a variable called an index or counter. When the index reaches a certain value (the loop bound) the loop will end.
Count-controlled repetition requires
We can use both for
and while
loops, for count controlled repetition, but the for
loop in combination with the range()
function is more common.
FOR
loop¶We have seen the for loop already, but we will formally introduce it here. The for
loop executes a block of code repeatedly until the condition in the for
statement is no longer true.
An iterable is anything that can be looped over - typically a list, string, or tuple. The syntax for looping through an iterable is illustrated by an example.
First a generic syntax
for a in iterable:
print(a)
Notice our friends the colon :
and the indentation.
Now a specific example
# set a list
MyPets = ["dusty","aspen","merrimee"]
# loop thru the list
for AllStrings in MyPets:
print(AllStrings)
range()
function to create an iterable¶The range(begin,end,increment)
function will create an iterable starting at a value of begin, in steps defined by increment (begin += increment
), ending at end
.
So a generic syntax becomes
for a in range(begin,end,increment):
print(a)
The example that follows is count-controlled repetition (increment skip if greater) (change from RAW to CODE to run)
1904 was a leap year. Write a for loop that prints out all the leap years from in the 20th century (1900-1999).
# Exercise 1
When loop control is based on the value of what we are processing, sentinel-controlled repetition is used. Sentinel-controlled repetition is also called indefinite repetition because it is not known in advance how many times the loop will be executed. It is a repetition procedure for solving a problem by using a sentinel value (also called a signal value, a dummy value or a flag value) to indicate "end of process". The sentinel value itself need not be a part of the processed data.
One common example of using sentinel-controlled repetition is when we are processing data from a file and we do not know in advance when we would reach the end of the file.
We can use both for
and while
loops, for Sentinel controlled repetition, but the while
loop is more common.
WHILE
loop¶The while
loop repeats a block of instructions inside the loop while a condition remainsvtrue.
First a generic syntax
while condition is true:
execute a
execute b
....
Notice our friends the colon :
and the indentation again.
The while loop structure just depicted is a "decrement, skip if equal" in lower level languages. The next structure, also a while loop is an "increment, skip if greater" structure.
Nested repetition is when a control structure is placed inside of the body or main part of another control structure.
break
to exit out of a loop¶Sometimes you may want to exit the loop when a certain condition different from the counting condition is met. Perhaps you are looping through a list and want to exit when you find the first element in the list that matches some criterion. The break keyword is useful for such an operation. For example run the following program:
Next change the program slightly to:
In the first case, the for loop only executes 3 times before the condition j == 6 is TRUE and the loop is exited. In the second case, j == 7 never happens so the loop completes all its anticipated traverses.
In both cases an if
statement was used within a for loop. Such "mixed" control structures
are quite common (and pretty necessary).
A while
loop contained within a for
loop, with several if
statements would be very common and such a structure is called nested control.
There is typically an upper limit to nesting but the limit is pretty large - easily in the
hundreds. It depends on the language and the system architecture ; suffice to say it is not
a practical limit except possibly for general-domain AI applications.
We can also do mundane activities and leverage loops, arithmetic, and format codes to make useful tables like
Write a Python script that takes a real input value (a float) for x and returns the y value according to the rules below
\begin{gather} y = x~for~0 <= x < 1 \\ y = x^2~for~1 <= x < 2 \\ y = x + 2~for~2 <= x < 1 \\ \end{gather}Test the script with x values of 0.0, 1.0, 1.1, and 2.1
# Exercise 2
using your script above, add functionality to automaticaly populate the table below:
x | y(x) |
---|---|
0.0 | |
1.0 | |
2.0 | |
3.0 | |
4.0 | |
5.0 |
# Exercise 3
Modify the script above to increment the values by 0.5. and automatically populate the table:
x | y(x) |
---|---|
0.0 | |
0.5 | |
1.0 | |
1.5 | |
2.0 | |
2.5 | |
3.0 | |
3.5 | |
4.0 | |
4.5 | |
5.0 |
# Exercise 4
continue
statement¶The continue instruction skips the block of code after it is executed for that iteration. It is best illustrated by an example.
When j ==6 the line after the continue keyword is not printed. Other than that one difference the rest of the script runs normally.
try
, except
structure¶An important control structure (and a pretty cool one for error trapping) is the try
, except
statement.
The statement controls how the program proceeds when an error occurs in an instruction. The structure is really useful to trap likely errors (divide by zero, wrong kind of input) yet let the program keep running or at least issue a meaningful message to the user.
The syntax is:
try:
do something
except:
do something else if ``do something'' returns an error
Here is a really simple, but hugely important example:
So this silly code starts with x fixed at a value of 12, and y starting at 12 and decreasing by 1 until y equals -1. The code returns the ratio of x to y and at one point y is equal to zero and the division would be undefined. By trapping the error the code can issue us a measure and keep running.
Modify the script as shown below,Run, and see what happens
Modify your Exercise 3 script to prompt the user for three inputs, a starting value for $x$ an increment to change $x$ by and how many steps to take. Your script should produce a table like
x | y(x) |
---|---|
0.0 | |
1.0 | |
2.0 | |
3.0 | |
4.0 | |
5.0 |
but the increment can be different from 1.0 as above.
Include error trapping that:
Once you have acceptable input, trap the condition if x < 0 and issue a message, otherwise complete the requisite arithmetic and build the table.
Test your script with the following inputs for x, x_increment, num_steps
Case 1) fred , 0.5, 7
Case 2) 0.0, 0.5, 7
Case 3) -3.0, 0.5, 14
# Exercise 5