KwicKode Tutorial Part B: Loop Blocks and Function Blocks
Order Kwickode Today:
KwicKode – Springboard to Python
Go to Tutorial Part A: The Basics
Go to Tutorial Part C: Lists and File I/O
| Caution: This tutorial presents only a cursory overview of the KwicKode commands. It in no way purports to teach programming. Designing an application and details of program structure are covered in more detail in my book, KwicKode-Springboard to Python. |
In Part A you leaned seven basic KwicKode commands. Among these were the if/then/else conditional commands that require you to define blocks of code using square brackets to delineate the start and end of each block. In this chapter, the two remaining block structures, loops that define code that is repeated multiple times, and function blocks that are used to break complex programs down into smaller, manageable blocks of code.
The following sample program illustrates a simple loop in which the numbers from one to ten are displayed on the monitor. (The accent marks ```` are used to force Word Press to recognize tab indents.)
Comment: Simple KwicKode looping example.
[Repeat block while cntr<10 with cntr:
````Display cntr+1.
````End of repeat block.]
Loop Blocks
There are several aspects about this command to keep in mind. First, the loop structure uses the syntax for blocks that you have already encountered: starting and ending square brackets surrounding the code to be repeated; the End of repeat block.] that is the last line in the block; the optional indentation for the code within the block.
All loops in KwicKode involve a variable that keeps track of the number of cycles the loop has performed. You can give this variable any allowed name, ‘cntr‘ in this example. KwicKode automatically assigns a value of zero to this variable at the start of the looping process and automatically increments it by +1 at the end of the block. (This is why one is added to cntr at the display command. Otherwise the numbers zero through nine would be displayed.)
The conditional expression in the first line is also required. If the loop is an iterative loop that is to cycle a set number of times, it may be desirable to include the loop’s counting variable as part of the conditional expression, as in this example. However, any valid conditional expression can be used. As long as the condition presented evaluates to ‘true’, the loop will proceed. The moment it evaluates to ‘false’, the block is skipped and the computer continues with the line of code following the end of the block.
Here is an example of a loop that does not use the counting variable. In this case, it is just ignored, even though its presence is required.Comment: Example of a KwicKode loop that doesn't.
Comment: use a loop variable.
Assign "A" to letter.
[Repeat block while letter<="Z" with indx:````Display chr(letter+indx).````End of repeat block.]
Since computers assign binary numbers to everything, the letter “A” has the internal machine value 1000001, or 65 in decimal. So, successively adding +1 traces values from “A” to “Z”. The final Display … command uses Python’s function that converts internal numbers to their corresponding characters. Thus, the program above recites the English alphabet. Note also the use of two comments in a row to handle long comments and that both Comment lines end in a period, even if that doesn’t make good English sense. Nobody’s perfect!
Where loops really exhibit their power is with lists. Recall that a list is a variable name that contains many items, each accessed by means of an index number. If a loop counter is used within the loop as an index number for items in a list, each successive pass through the loop will access the next item in the list. So if you have a list called ‘members’ for your book club that contains 35 individuals’ names, the following loop would print out all 35 names:Assign len(members) to member_count.
[Repeat block while indx < member_count with indx:
````Display members[indx].````End of repeat block.]
Of course, for this simple case, the same result could be obtained with Display members as list. More useful examples are presented in Part C that deals specifically with lists.
Two very important notes about KwicKode’s loop counters. KwicKode is the only language I am aware of that allows you to change the counter’s value during the course of loop cycling. For example, if you wanted the earlier program to count by two’s, place the assignment statement: Assign cntr+1 to cntr. before the end of the loop. In this way, cntr gets incremented by 2 with each cycle instead of just 1. A second important feature is that the loop variable and its final value are available for the program’s use even after the loop has terminated. This too is an important difference from other programming languages.
Function Blocks
Imagine you are working with a program containing 15,000 lines of code and the program has no breaks from beginning to end. There is a program bug that prints out all the information in a database except the last record. You need to find that one line of code that needs to be corrected. It could take you all day, and even when you’ve made a change, you can’t be sure your edit was in the place it needed to be.
Now imagine that this program was divided into dozens of ‘chapters’ with each chapter controlling one simple, small aspect of the overall program. If each chapter began with a comment line telling what that chapter covered, it might take you ten minutes to find the chapter dealing with printing out the database contents and right away you see the problem. You need to add a ‘+1’ to the conditional expression in the loop command controlling the printout. Problem solved.
Function blocks are the equivalent of chapters. The code within a function block is designed to perform one specific action, or ‘function’, and return the result to the main program from which the function was called. This raises two important points. The first is that all function blocks must physically appear before the main program code. This means there may be a lot of code before you get to the first line in the main program, so it’s a help to begin the main program with a comment like:
Comment: Main Program begins here.
The second point is that, in addition to the KwicKode commands that are used by the function itself, there is also a KwicCode command that is used to call (or activate) the function.
So, first for the function block itself. Here is an example of a function that is designed to calculate the gas consumption of the user’s vehicle.[Function mpg_calculator using (miles_driven, gallons_used):````Assign (miles_driven / gallons_used) to consumption.````Return consumption.````End of function block.]
Note the usual syntax for designating blocks of code. The function name can be anything you choose, but if it is descriptive as above, there may be no need for a comment line to describe what the function is for. Following the word ‘using’, and in parentheses, is a list of variables that contain values sent to the function from the main program. These are the variables the function needs to accomplish its task. Finally, when the function has performed that task and calculated a result for the program to use, it uses the Return xyz. command to send the value back to the calling command.
As mentioned, functions must appear ahead of the main program. They may be as short as four lines (above) or several dozen lines long. To be effective, however, you should try to keep them as short as possible and as focused on producing a single result.
Now for the command in the main program that calls, or activates, the function. For the example above, it might look like this:
Call mpg_calculator with (distance, fuel_qty) for mpg.
The name of the function is followed by the word ‘with’ and a list, in parentheses, of the variables containing the values to be passed to the function for it to work with. The word ‘for’ is followed by the name of the variable that will receive the value sent back by the function’s ‘return’ command.
Note that in this example, the variable names used by the call command are all different from those used by the function itself. This is optional. Some programmers believe it simplifies things to use the same names. The reason it doesn’t make any difference is that, so long as the variables aren’t list variables, the variable names used within the function stay with that function and are isolated from the rest of the program. Their values evaporate the minute the ‘return’ command is executed.
Here is a program example that uses all of the commands presented in Part A and Part B except for loops. See if you can follow exactly what the program is doing from start to finish. (Hint: Always begin reading at the first line of the main program, not at the functions that appear first.)
Comment: Sample KwicKode program that uses 10 of KwicKode's 16 commands.[Function mpg_calculator using (miles_driven, gallons_used):````Assign (miles_driven / gallons_used) to consumption.````Return consumption.````End of function block.][Function distance_calculator using (mpg, gallons_used):````Assign (mpg * gallons_used) to distance.````Return distance.````End of function block.]Comment: Main Program begins here.
Display "Use this program to: 1. Calculate fuel efficiency (mpg), or ".
Display "2. Calculate how far you can travel on a given amount of gas.".
Display "Enter 1 or 2 for your choice...".
Get string for choice.
[If choice == "1" then:````Display "Gas consumption calculator. Enter miles driven...".````Get string for miles_driven.````Assign int(miles_driven) to miles_driven.````Display "How many gallons of gas did you use...".````Get string for gas_gallons.````Assign float(gas_gallons) to gas_gallons.````Call function mpg_calculator with (miles_driven, gas_gallons) for mpg.````Display "Your gas efficiency rating is ", mpg, " mpg.".````End of if block.][Else:````Display "Distance calculator. Enter your fuel efficiency (mpg)...".````Get string for mpg.````Assign float(mpg) to mpg.````Display "How many gallons of fuel are available?".````Get string for gas_gallons.````Assign float(gas_gallons) to gas_gallons.````Call function distance_calculator with (mpg, gas_gallons) for distance.````Display "With ",gas_gallons," gallons of gas, you can go ".````Display distance," miles.".````End of else block.]With this chapter, you have covered eleven of the sixteen commands that define KwicKode. In it, you have learned about loop blocks and their associated counting variables. You have also learned about function blocks with their parameter lists and return commands, and their associated call command using argument lists that pass values to the function parameters. Chapter C covers lists in more detail with three commands devoted exclusively to lists, and introduces the two KwicKode commands that handle file input and output, essential for saving and retrieving data to your computer’s data storage device.
Order Kwickode Today:
KwicKode – Springboard to Python
Go to Tutorial Part A: The Basics
Go to Tutorial Part C: Lists and File I/O
Go to Home Page