Example | ||
---|---|---|
Starting OutIf you are transitioning to Python, this is the example for you. We start by defining a label at the top of your Python program, which will become the first string label in your generated HP42 RPN program. You can then execute code beginning at Note that if you are a Python programmer, there are no such things as labels - so think of this code example as a module (file) and the syntax LBL("main") as a hack to be able to execute that module from the command line, which you would usually do with We then assign some variables e.g. If you don't define a LBL then the first function you define with 'def' becomes the first string label of your generated RPN program. The benefit of using LBL at the top of your program is that you can define variables in the outermost 'global' scope of the Python program, which is outside of any function. These variables will then become accessible inside all functions - often very handy. Python looks for variables by looking in the current function, and if not found, looks to the outer function etc. all the way out to the global scope, which is outside any function. On the other hand, if you define variables inside functions, those variables are private to those functions - the only way to communicate them to other functions is to pass them as parameters to those other functions. |
|
|
Demo 1This example shows off many things: for loops, variable assignments and function calls incl. the passing of parameters. Notice the nifty lowercase
Time saver! P.S. The only difference between alpha() and print() is that print() adds an AVIEW to the RPN. Also |
|
|
Long expressionsYou can type in long complex expressions and they will be converted to RPN. There are limits to how big your expressions can be, because of the HP42S four level stack. The conversion process will generate an error if the stack is at risk.
|
|
|
VarmenuA “variable menu” is a technique for displaying a HP42S menu containing the names of several variables. See page 92 of the HP42S manual. You can then take your time storing values into those variables, and reviewing them, using those same menu buttons (no need to use STO) - then press R/S to continue into the calculation. The Python to RPN converter supports the traditional native commands needed to use this handy facility, as well as supporting an easier way using The simplified varmenu() technique allows you to specify all the variables in the one function call. Then in the generated RPN, “boilerplate” calls to MVAR, VARMENU, STOP and EXITALL are automatically inserted for you. Traditional Technique:
|
|
|
Prompting for inputYou need to specify native uppercase HP42S commands in your Python code for doing user input. The basic difference between HP42S native PROMPT and INPUT is that the former specifies a custom text prompt, whilst the latter prompts with the name of the variable, and shows the current value of that variable. Both commands stop program execution till you press R/S on the calculator. INPUTTakes a normal Python variable as a parameter - do not put variable in quotes. Specifying HP42S registers not supported. E.g. PROMPTDisplay the Alpha register and halts program execution. To store the value entered during the prompt into a variable simply assign to that variable e.g.
* * * DiscussionsHow Python variables are converted to RPN You generally don't have to worry about how Python variables are converted to either RPN named variables vs RPN registers - because when you are programming in Python, you don't really care how your Python variables are converted to RPN. You just basicaly think in Python and treat the generated RPN as "machine code" that you never look at. However, for those interested, read the "RPN tips" in the example code for information on what RPN code is generated. You might be interested in this if you want your Python program to end up with some RPN named variables for use and access later. Its easy to access named variables rather than have to figure out what random numbered register might have been used to store the Python variable. But on the other hand, named variables pollute the global HP42S namespace, thus generally its better to allow the default behaviour of using numbered registers. Interestingly the default numbered register behaviour is not followed with the INPUT command: the variable referred to as the parameter will be converted into RPN as a named variable rather than converted into an auto allocated numbered RPN register. The only exception to this rule is if that variable has previously been assigned to - then it will be converted into RPN as an auto allocated numbered register. I'm not sure why this implementation decision was made and this behaviour may be change in the future. Using AVIEW and INPUT together Interestingly, I have observed that if you do a AVIEW("some message") prior to an INPUT, you get the message on the top line of the HP42S and the input prompt on the second line - nice. Warning: If you are viewing a message using AVIEW("some really long multi-line message") that takes up two lines, then you won't see the subsequent prompt generated by INPUT. This is because the prompt on the second line of the HP42S display is occupied by the multiline alpha string and the INPUT command doesn't seem to clear it. To work around this edge case of Free42/HP42S? behaviour view an empty string in the alpha register using print(""). Clearing the alpha register with CLA() is not enough. Discussion on the forum here. Future developments There is a proposal for this Python to RPN converter to support the native Python
|
|
|
Matrix LoopingLooping through a matrix. |
|
|
ListsYou must use uppercase variables for lists. You can also initialise a list with values then append to it later e.g.
Lists are implemented as matrices with one column, and as many rows as is needed (matrix grows as you append elements). You can get elements of an array with e.g.
You can even store short strings (max 6 chars) as list elements in lists.
|
|
|
For loopsFor loops a common way of looping in Python. The range function specifies from, to and step. You can leave out 'step' and it defaults to a step of 1. Note that under the hood, for range loops are implemented with RPN's |
|
|
WhileWhile loops are a fantastic alternative to |
|
|
MenuThe "programmable menu" feature of the HP42S lets you create your own menu - pressing the key underneath each menu item will execute the associated function. There is both a traditional and new simplified way of building these menus. The new simplified You must of course define the user functions being called, which by default will be converted into local labels beginning with A, and thus won't pollute the global namespace. If you want one of your called functions to be a named label, then as usual, use the comment directive If you want to pass parameters to your functions then key them in onto the stack before pressing the menu button. For example to satisfy the call to Traditional MENU technique If you want to build HP42S the traditional way you can do so thus:
The traditional approach is more laborious, but gives you the advantage of being able to call the menu items something different than the name of the function e.g. notice above that the menu item "Do A" calls the function do_a. With the traditional approach you may need to clear the menu before you build it - because old MENU definitions hang around till explicitly cleared. The simplified Finally, the simplified menu() command implements |
|
|
Square a matrixCreates a matrix of 2's and square them into 4's, then checks the result.
|
|
|
Complex testTest of complex number handling. Note that the HP42S commands The Python way of entering complex numbers is also supported viz. You can also enter complex numbers without this COMPLEX function using native Python syntax e.g. |
|
|
Calculate PiMy version of Walsh algorithm to calculate pi by adding 1/n where n is 1, 3, 5, 7... where you add and subtract alternately. Note that the variable 'subtract' is a boolean, and controls whether we are doing an add or a subtract operation. In HP42S we would have used a flag - in Python we simply use any variable as a flag. Note that when converted to RPN, True and False map to the values 1 and 0, though in Python any non zero value will be treated as True. Note: Call this with max iterations of max 1000 because RPN's ISG has max of 1000. To work around this, the loop could be done with a regular variable and a while loop, which has no limitations. Or the converter could be changed to implement for loops without ISG. |
|
|
While elseNot many people know this advanced Python syntax for while. The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won't be executed. The else clause is executed if you exit a block normally, by hitting the loop condition or falling off the bottom of a try block. It is not executed if you break or return out of a block, or raise an exception. It works for not only while and for loops, but also try blocks. |
|
|
VariablesThe directive rpn: named will force a Python variable to be mapped to a HP42S register of the same name, instead of being mapped to a numeric register. Use this directive any time you want a a Python variable to be stored in a HP42S lowercase named register mapping instead of the default numbered register. Normally Python variables are mapped to numeric registers 00..nn in order to avoid polluting the HP42S global variable namespace. However in some circumstances you may wish to expose the variable to look at or use later. This directive forces the converter to allocate a named register. For example, its useful for the INPUT command to be given descriptive variable names e.g. Normally |
|
|
Assign to variableAll lowercase python variables (recommended) are mapped to RPN registers, in the order that the converter parser sees them. Thus a = 10 and b = 20 will be mapped to registers 00 and 01 respectively. All uppercase python variables are mapped to named string variables. Thus X = 10 will be mapped to register “X”. To allow the creation of lowercase or mixed case named HP42S registers from your Python variable names by using the rpn directive “named” e.g. y = 100 # rpn: named Lists and Dictionaries are always mapped to named registers, because they are implemented as matrices, which need to be in named registers. |
|
|
Displaying InformationExample of all the ways you can display info to the user. And how to prompt for input. |
|
|
Test code for arrays and dictionariesTest code for arrays and dictionaries - runs a suite of tests on your calculator. |
|
|
ReciprocalTo generate the HP42S command 1/X use function Reciprocal. This renaming was necessary because Python does not accept / and many other symbols as part of function names. There are a few other renamed function - for a complete list click on help and then click on RPN command reference. |
|
|
Multiple return valuesTraditionally in RPN you can return multiple values from a subroutine by pushing those values onto the stack. In Python you can return multiple values from a function using the return statement e.g. Various HP42S commands return multiple values and to access those values you will need to use this Python tuple syntax. For example the
|
|
|
Nested MenusAn example of using a master menu in the global scope, launching various sub functions, including a sub menu. Hit the Exit button on Free42 to back out of the submenu. |
|
|
Edit a matrixCreates a matrix and then calls up the built in HP42S matrix editor. In the editor, you can navigate to all the cells and also modify cell values. When you exit the editor by hitting the EXIT key on your calculator or Free42, the program will end. Tip: If you want program execution to resume after editing your matrix, you will need to call EDITN inside a RPN program with an outer menu structure, so that when you hit the EXIT key you will return to the main menu, and then can hit another menu key to continue some processing. Here is part of an example from the manual "HP42S Programming Examples and Techniques" p.158 pure RPN code.
TODO: convert the above example into Python. |
|
|
Matrix InjectionCreate a matrix of 0’s and inject into it a matrix of 1’s. Then goes on to visualise the matrix as pixels! See the full explanation of this example in the help file, including discussion about the NumPy compatible syntax being used here. |
|
|
Matrix MultiplyMultiply two matrices.
Its a kind of boring example. Note that there is a special technique to multiplying matrices, click here to learn about it. Explore this example in Wolfram. For the curious, the Desktop Python equivalent is
|
|
|
DIM MatrixesCreate, redimension and test the size of matrices. |
|
|
Complex MatricesComplex matrices test. |
|
|
List and Dict lookup operationsDemo of list and dict lookup operations. |
|
|
IfA very simple example of if else and expressions. A function which figures out which number is bigger than another, and displays a message on the screen telling you the result. To run |
|
|
Range by 2range with step of two |
|
|
FlagsFlags are not used in Python programming - instead, any Python variable can be used to hold a boolean. However if you need to test, set or clear various HP42S flags then use these functions: This example tests if system flag 21 (controls print on/off from within a HP42S/Free42 program) is set. Note that the HP42S commands |
|
|
FibonacciFound the algorithm here, and adapted it slightly because multiple return statements are not yet supported by the converter. Results in Python and in Free42 are the same: TODO: now that returning multiple values has been implemented, this example could be altered. |
|
|
Export directiveEvery function you define with def (except for the first one) will be a local function with a local label. By adding |
|
|
Pixel drawingDrawing with pixels. |
|
|
Drawing LinesDrawing lines. |
|
|
Draw Demo 1Massive demo of drawing with lines, circles, rectangles, filled rectangles and filled circles. Warning: you need to increase the number of registers from the default of 25 to something like 60 using The graphic drawing functions are:
About coordinate systems. These drawing routines are based on C and javascript algorithms which use a coordinate system:
which is similar to the HP42S graphic coordinate system
Besides the 0 based vs 1 based difference, the main thing to note is that these drawing algorithms treat left to right as x, like on a graph - which sounds right, doesn't it? Interestingly, the 42S treats left to right as columns - which also sounds right when thinking about matrices and tables. Both ways are 'right' depending on what convention you want to adopt. Why does this matter?
|
|
|
Calculate Pi repeatedlyThis calls the algorithm to calculate PI repeatedly, and shows how the value converges towards real PI as the max iterations increases. |
|
|
AssertThe
... you're telling the program to test that condition, and trigger an error if the condition is false. Note: The |
|
|
Function to add positive numbersAdds two numbers if they are both positive, otherwise returns 0. Demonstrates, if statements, boolean operations and returning a calculation. |
|
|
Interested in a modern thermal printer for the Free42 calculator emulator?
Introducing Print42 for Mac and Windows, which echoes your Free42 calculator virtual tape to a fast, modern thermal printer.