The form with has changed a little with version 2. The variables that you can use with have not changed, but their usage has slightly. They are all defined for you when SM starts and each is always correct, tracking the current value of the corresponding internal variable. When you say define angle delete it will once more track the internal value.
Your old code will continue to work, but in many cases it is possible to remove the explicit definition with. This special sort of variable will not be SAVE d, and will not show up if you list the currently defined variables. When writing macros, it is also sometimes useful to know if a variable has been defined. For instance, there is a line define term: There are also commands to read the values of variables from data files defined with the DATA command.
You might prefer to use the macro lsv which won't appear on your history list. Sometimes you may want to terminate a variable name where SM doesn't want to, and this can be done with a trick involving double quotes. When a variable is read, SM skips over all whitespace before the definition, and this can cause problems if you hit control-C in the middle, as the rest of the command will be thrown away.
If you ever hit a control-C , and can't get a prompt, try typing any non-whitespace character. Variables are string -variables, and are not primarily designed for doing arithmetic that's what vectors are for. This is a common source of confusion so let's consider some examples at the risk of anticipating some later sections of the manual. The fact that variables are simply strings can be used to build complex commands; consider for example the macro readem read multiple lines columns with names in row 1 READ ROW names 1.
You could of course loop through names reading each column in turn, but this should be a good deal faster.
Our Air-Cruises 2019-20
In fact, such variables aren't strictly local, they have what's called nested scope, as they are visible from any macros that you may call -- they simply do not propagate backwards up the call stack. You are free to make a variable local in any or all macros, there's no restriction on how deep such local declarations may be nested. It is often very useful to be able to repeat a command, or perhaps correct a mistake in what you have just typed. If you are not familiar with Unix, emacs, or VMS don't despair; a description of the commands and how to invoke them follows in this document. Both of these mechanisms are implemented by the routine which reads input lines.
As each line is sent to the parser, it is copied onto a history list. For example, if I type: In that case there'll be many more commands on the list, but no matter. If the command is given with zero, one, or two arguments, then the specified range is deleted but their numbers are not re-used. If no arguments are given, the last command on the buffer is deleted, and its number is released to be re-used. This means that the command will not appear on the history list, to confuse you when you do a playback.
But if you now innocently use dev in a macro, that macro won't appear on the list either. Still worse, if you use dev twice in one macro, the previous command will be deleted as well which could be quite confusing. You can also delete lines of history using ESC- control-D as described shortly. The numbering is consecutive, starting at zero.
Each command retains its number until you use a HISTORY command to list the remembered commands, in which case they are all renumbered, and it is these new numbers that are listed. By default only 80 lines are remembered, and as you continue typing earlier ones fall off the list. Because the history buffer is also used to compose complex commands, this limit can be aggravating. Alternatively you can define a longer history buffer when you start SM by including an entry history in your environment file. If you set history to be 0 the history list is made infinitely long.
Incidently, it is the total number of commands that matters, not the range of history numbers present. Some people seem to like their history editors to remember where they were, so that after they retrieve and execute a command the next control-P or will retrieve the command one further back on the history list that is, if you have just retrieved command number and executed it as command number , then control-P will get you command number ; you can execute it as command number The editor allows you to modify commands, either as you type them or as you retrieve them from the history list.
The various editing commands may be bound to keys of your choosing, but the default bindings are given in this list of possible commands: Delete character to left of cursor. The deleted string is stored, and may be restored using control-Y , repeatedly if so desired. Some terminals seem to replace control-M with a linefeed control-J , thereby making it impossible to make SM obey you. We therefore make control- equivalent to control-M for emergency use. This is control-space on many terminals. Equivalent to control-P control-E control-M.
If you specify a zero-length string i. By default, characters are inserted before the cursor. If overwrite is set, they replace the character under the cursor. DEL Equivalent to control-H. ESC- control-D Delete this line and remove it from the history list. Note that this is different from just clearing a line with e. ESC-g Go to a given line of a macro, or a given history command.
You'll be prompted for the line number, if you change your mind you can get out with DEL or control-H. ESC-q Quote the next character, turning off any special significance to the editor. ESC-s Search forward for a string. ESC-v The opposite of control-V , go back 5 lines. ESC-y Like control-Y , except that it gets older deletions, cycling back through a collection of currently 5 deleted lines. Some ESC-letter combinations are available which operate upon complete words. A word is defined as a whitespace delimited string, so 2. ESC-b Go to the start of the previous word.
ESC-d Delete to the beginning of the next word. ESC-f Go to the beginning of the next word. ESC-h Delete back to the beginning of the current word.
Ready to Start Planning?
The same as control-W. ESC-u Restore the last word deleted, putting it before the cursor. Further ESC-u 's will restore more words. When no more are available, the bell is rung. Any printing character is inserted before the cursor unless overwrite has been set with control-T. Illegal characters ring the terminal bell. If you insert a non-printing character on a line, the cursor may get confused. If ever you are stuck at the command interpreter, and you want to send a signal to the operating system e.
While it is running i. As mentioned above, it is possible to redefine the meanings of keys to the history and macro editor. The command EDIT keyword key-sequence will make typing that sequence of keys correspond to the command keyword. The keyword can be any in the list below, or any single character. Alternatively, READ EDIT filename will read a file specifying the new bindings which has two lines of header, followed by pairs of keyword key-sequence.
Lines starting with a are comments. An example is the file for VMS users given below. A problem can come up with multiple-key sequences. The solution is to tell SM that control-X is not a legal key, in which case it will either ring the terminal bell if there are no key-sequences starting with an control-X , or wait for the next key. On a somewhat similar topic, the KEY see section Key command may be used to define a key to generate a string. See the end of the section on macros for how this works.
The names of operators, and their default bindings, are given in the following table: You should be warned that some terminal protocols map control-M to control-J , so this use of control-J could render you unable to issue commands. As mentioned above, in an emergency control- can be used instead of control-M. If you try to use a character special to SM such as! This is entirely separate from the problem of describing the terminal's graphics. SM then uses the terminal type specified to look up its properties in the termcap database see section Termcap -- A Terminal Database.
On some terminals, you can only send a cursor to an absolute position and this is chosen to be the bottom of the screen. This is not what you want for, e. In SM, it is possible to define sets of plot commands as "subprogrammes", which can be used just like a plot command, to generate a standard plot. These plot macros allow variables e. Such keyboard macros are discussed under KEY and at the bottom of this section.
The macro facility consists of commands to define macros, delete them, write them to disk files, read them from disk files, delete all those macros defined in a specified disk file and list all currently defined macros. In addition, the help command applied to a macro prints out its definition. If you want to include a space in an argument, enclose it in quotes. If the number of declared arguments is 10 or more, the macro is treated as having a variable number of arguments.
If it is or more the last argument extends to the end of the line. For further discussion see the discussion of how macros are used. Macros defined using an editor on a file may be up to characters. If nargs , the number of arguments, is 0 it may be omitted. To define the macro in a disk file, the file format must be: The next line and any necessary subsequent lines contain the macro definition starting in a column other than the first one. Any number of macros may appear in the same file, as long as the macro name is given in the first column and the definition starts in some other column.
The first two blanks or tabs are deleted in continuation lines, but any further indentation will survive into the macro definition. Tabs will be replaced by spaces as the macro is read. The number of arguments must be declared correctly. As an alternative it is possible to declare that a macro has a variable number of arguments by declaring 10 or more The macro will then expect between 0 and the number declared modulo 10 arguments, all on the same line as the macro itself.
If the number of arguments is or more it is still reduced modulo 10, but the last argument is taken to be the rest of the line which may consist of many words. When you start SM, the error handler is: The symptoms are that a macro either gets the arguments that were passed to the macro that called it, or complains that it can't handle numbered variables at all because it isn't in a macro at all. It is possible to redefine the values of arguments it won't affect the values you originally specified, arguments are passed by value , or to DEFINE values for arguments that you didn't declare.
The latter case allows you to have temporary variables, local in scope to the macro. Newlines are allowed within macros, and as usual any text from a to the next newline is taken to be a comment. If a macro starts with a comment the comment will not affect the macro's speed of execution. If the name is already defined, it will be silently redefined. Macros may be nested freely, and even called recursively. As before, it will think about it forever. To find how a particular macro is defined, type HELP macroname.
Or you could overload list ; see under overload in the index. Macros are written out in alphabetical order. This allows a set of related macros to be written to a file. This allows a file of macros to be read in, used and forgotten again. The SAVE command is probably a better way of saving all current macros. The format of macros on disk is name nargs text , where nargs may be omitted if it is 0. Continuation lines start with a space or tab. It is possible to define macros from the history list. This way of defining macros can be convenient if you have created a useful set of commands on the history buffer, and now want to save it in a macro and go on to other things.
Editing the playback buffer, and then changing its name to something else see next paragraph is a convenient way of saving it that implicitly uses this command. Macros may be edited, using essentially the same keys as described above for the history editor. If this line is changed, except to change name or n , any changes made to the macro will be ignored note that the space after name is required. This can be useful if you decide that you didn't want to make those changes after all. Changing name or n has the obvious effect, except that if n is negative the macro is deleted when you exit the editor.
An empty macro is also deleted when you leave the editor i. The first line that you are presented with is the first line in the macro rather than this special one. Use control-N or to get the next line, control-P or to get the previous line. Carriage return control-M inserts a new line before the cursor, breaking the line in the process, while control-O inserts a new line before the current line. To save the changes and return to the command interpreter use control-X. All other keys have the same meaning as for the history editor e. It is sometimes convenient to define a key to be equivalent to typing some string, such as playback or cursor.
In this case you are not using the history editor to read the key, and you can simply hit the desired key followed by a space and the desired string, terminated by a carriage return. If this sounds confusing, here is an example. Now just hit the PF1 key and see what happens. These keyboard macros are not generally terminal independent, but they can be convenient. If you always use the same terminal you might want to put some KEY definitions in your private startup file see the discussion of startup2 in the section on useful macros.
IF is included here as a flow-of-control keyword. Do loops may be nested, but the name of the variable in each such loop must be distinct. For loops within macros, it's often a good idea to make the loop variable local: Because the body of the loop must be scanned and parsed repeatedly, loops with many circuits are rather slow. If at all possible you should try to use vector operations rather than DO loops. Foreach loops may be nested, but again the variables must be distinct.
If the scalar expression is true i. You can use logical operators within the expr see section If. In a scalar context e. It is possible to write general loops in SM by using of tail-recursive macros. The absence of a space before the closing brace is very important, as it allows SM to discard the macro before calling it again, which means that it won't fill up its call stack and start complaining. A more interesting example is the macro repeat which repeats a given macro while the given condition is true. With a few checks, bells, and whistles the macro looks like: There is an online help command.
The help menu consists of any files in the directory specified by the entry help in the environment file, so for example HELP data types the file data in that directory. The same filter is used by e. If VERBOSE see section Verbose is zero only the lines from the help files matching the pattern are printed; if it is larger you are given a couple of lines of context on each side. It is worth remembering that the index to this manual has an entry under weird , wherein are listed all sorts of strange happenings, with explanations and suggestions for workarounds.
You will be prompted before each class of objects is saved, or you can put the answers on the command line. The file is ascii, and can be edited if you so desire. To restart, RESTORE filename will read them all back, using the same default file as for SAVE if no filename is specified, and replace the current history buffer with the value of all from the savefile.
If the file wasn't written by SAVE it is assumed to be a SM history file, one of those written when you quit SM, and each line is assumed to be a command and written to the end of the history buffer. This is generally useful when you started SM in the wrong directory.
One problem with SAVE is that it saves lots of macros, including some of the system ones. Specifically, all macros are saved except those beginning with " ". This is probably the best way to use the SAVE command. In addition, sav also decides to save variables and macros, only prompting you about saving vectors.
There is no limit to the number of vectors that may be defined. SM allows the user to read vectors from files or define them from the keyboard, to plot them and to perform arithmetic operations upon them. SM's string-valued vectors are less generally useful, but can be used for such purposes as labelling points on a graph. See READ for how to read a string-valued vector. Instead of using simple column-oriented input it is possible to specify a format like those used by C's scanf functions Fortran formats are not supported ; if you provide your own format string you can only read numbers.
For example, if your data file has lines like 1: If a scalar is encountered where a vector is expected, it is promoted to be a vector of the appropriate dimension; all other dimension mismatches are errors. An arithmetic vector x is then defined, and s is redefined as an arithmetic vector too -- you must be careful when dealing with string vectors!
This is a somewhat contrived example, designed mainly to illustrate the convenience of the SET command. The ability to set particular elements is mostly used in macros such as smirnov2 which calculates the Kolmogorov-Smirnov statistic from a pair of vectors. If the first element of a list is a word, the vector is taken to be string-valued: The last two are the dimension of a vector, and an element of the vector with expr a scalar subscript. The expression WORD[expr] is in fact allowed even if expr is not a scalar, in which case the result is a vector with the same dimension as expr , and with the values taken from WORD in the obvious way.
STRING uses the same code as the axis-labelling routines, so FORMAT can be used to modify its behaviour; whether the x- or y-axis formats is used depends on whether the label is more nearly horizontal or vertical. The constant PI is predefined. You can also use WORD [ expr [ , The meanings of the symbols are the same as in C, and as in C the value 0 is false while all other values are true. String vectors may only be concatenated, added, or tested for in equality.
Testing equality for string vectors seems to cause some confusion. There are also a number of less mathematical operations. Note that this may be used as a way of reading large data files that are stored unformatted. The second expression is taken to be the centres of the desired bins: The form vec[expr] may be used to assign to an element of a vector, as usual the index starts at 0. Before you can use SET to assign values to the elements of a vector, you must create it using one of the other forms of the SET command.
You can optionally supply a qualifier to the number , either a. If the IF clause is present, only those elements of expr1 for which the corresponding element of expr2 is true non-zero are copied into vec ; in general vec will have a smaller dimension than expr1. The last SET statement with?: In this form of conditional assignment, the dimension of vec is the same as that of the right hand side.
It may look strange, but it can be just what you want. Each vector also has a help field, which may be used to provide a string describing the vector. Any combination of string- and arithmetic-vectors may be printed. Once you start writing or using complicated macros you'll get bitten by the fact that a macro called by a macro called by a friend's macro uses a scratch vector called x or i , and that this vector quietly overwrites your vector called x or i.
After the command SET x LOCAL in a macro, any redefinitions of x within that macro, or any macros called by it, will be discarded when the macro exits. The vector isn't strictly speaking local to the macro as it's visible from macros that are more deeply nested, but the effect is similar. A word on caution: There are two separate ways to specify special characters to SM, by using a syntax very similar to TeX the type-setting system created by Donald Knuth that we used for this manual , or the traditional Mongo way.
You might ask what are the advantages of TeX? A third would be that you may well know TeX already. You can, of course, undefine it at any time to revert to the old-fashioned strings described below. Using TeX-style strings is strongly recommended by the authors; all future and most recent improvements to SM's labels are only supported in TeX mode. For some devices with hardware fonts for example, postscript printers or a Tektronix terminal , if expand is exactly 1, and angle is exactly 0, the hard fonts will be used for speed.
Various strategies to defeat this are discussed below. TeXsperts should skip this section. If you don't know TeX let's start with an example: These fall into three groups, those that change fonts, those that serve as abbreviations for single characters e. The font changes persist until the end of the string, or the current group, whichever comes first. If a alphabetic name is followed by a space, the space is treated as simply delimiting the name and is discarded.
How do you make just a few characters italic script, old english, etc. Some of these definitions are more complex than just special characters, if you know TeX most of them should be familiar. It's written in SM's TeX emulator which is pretty limited. It produces no output, but defines name to expand to value. Once a definition has been made it is remembered forever well, until you leave SM actually whatever devices you plot on.
You must make sure that all curly brackets are properly paired inside your definition. We have made a number of extensions to TeX that are useful in a plotting package, but wouldn't be especially valuable in a printed document. We have also distorted the meanings of some of TeX's control words; sorry. The by is optional. Now for a few caveats: Thirdly, TeX and our pseudoTeX are rather verbose and labels may not fit on one line. This is probably best done within a macro, as the continuation line won't appear on your history list if typed at the prompt.
You can currently have about 25 continuation lines characters.
- Peret (Sekhmets Light Book 2).
- Navigation menu?
- # PROJECT MANAGEMENT tweet Book01 (Thinkaha).
A final point will only worry TeXies, namely that the emulation isn't perfect: Some of the other discrepancies were listed in the previous section. This is faster, but can lead to two styles of labels in one plot which is ugly. There are various ways to trick SM into always using its own fonts: Tell her to see section The Stdgraph Graphics Kernel.
Private overrides for RHL: If you insist on using old-style labels which are still the default , here's a quick summary. Spaces are treated differently in different fonts, as a greek space is a negative space i. There isn't really any need for this section because SM doesn't distinguish between hardcopy devices such as laser printers and other devices such as graphics terminals, except that it saves up plotting commands for hardcopy devices and sends them all when you are finished. There are, however, hard and easy ways to do anything and this section is intended to make your life a little simpler.
When a device that can produce hardcopy is closed the plot is sent off to the printer using the command given as SY in the device's graphcap entry. The only way to close a device is to open another, any other, so it is just as good to say dev x11 as it is to say hardcopy dev x11 as the macro hardcopy does no more than open the null device. So one way to produce a plot is to say device postscript plotting commands device x11 There are many different printers available, and even if you are using a postscript printer you might want portrait postport or landscape postland plots, so it is traditional to put the name of the desired printer into a variable printer.
The former can be given a single history number e. The latter, if you omit the name of the macro, will prompt you to create a temporary macro that is then printed. If you want to make a hardcopy of the last line you have a choice, either hcopy -1 or hmacro , and then use the history editor to retrieve the desired line. Some sites have many hardcopy devices of the same type, in which case they usually set up the SY command to expect an argument which is the name of the desired printer.
You can deal with this by including it in your printer variable: If all of these fail they take the first argument hcopy or last argument hmacro to be the name of the printer. Of course, you can usually write macros to get around these annoyances, but you can't easily give them the same names as the original commands for these examples the macros are called era , q , and sav.
For example, if you were perverse, you could define points to mean QUIT. Another danger is that you could end up with a recursive call -- for instance if you wrote your own version of box that did all sorts of cunning things, then drew a box. If you said box in your macro, then overloaded the keyword, you'd have a macro that called itself. Despite these warnings, overloading the meaning of SM's keywords can be very convenient. In addition to the semi-trivial use of overloading to allow you to type erase not era , it is possible to add extra functionality to simple commands.
Another example is that when overloaded lines saves the line numbers used, so that you can write a macro to print the top 10 lines of a file it's called head. So how do you do it? You can still use the uppercase form -- you can't overload that. So now that e. If you intend using them and I do all the time you should look at this file.
If you don't like some, e. Most of the changes are benign, but not all. For example, the new definition of relocate allows expressions, but it'll break if you try to say relocate to move to absolute screen coordinates. This brings up another point -- if you overload keywords, you could slow SM down. It isn't that overloading is inefficient, it's just that the macros that replace the old keywords may do a good deal of work, box is a case in point. Even when the macro is short and to the point, it's still extra work to parse the original word and find its value as a macro.
At the time of writing of this manual, startup was defined as: Because some of the values might not be numeric, the comparison is forced to be done on strings by enclosing the quantities in single quotes. If device is defined it is used to set the default plotting device, and both it and printer are used by a couple of macros hcopy and hmacro that produce hardcopy. C, or unformatted fortran. Startup doesn't have to check that macro was successfully defined as it must have been found for startup to have been read in the first place.
Macro specifies where to look for macro libraries, and startup next sets the variable mfiles containing the names of some of the system macros to be loaded, and reads them. The macro load defined below also maintains the mfiles list, as does unload. It is used by the sav macro, which is discussed below the main listing of macros that follows. We also set some variables used by the id macro. This is quite important, as it provides a way to customise SM to your personal taste without convincing the local SM guru that your taste should be foisted on everyone. If you want a prompt that is different, or a definition of q that just quits without asking questions, you can get them by using macro2.
You can see that it is possible to tailor SM pretty much as you wish without changing a line of code, just by playing with the startup macro. SM provides various compatibility macros, and some to package often-used functions. To see a current list, either look at the files directly, set VERBOSE to zero and list all the macros, look at the listing in this manual see section The System Macro Libraries , or use lsm to list macro files this only works if you are running Unix; try lsm demos.
A discussion of a few of the more interesting or obscure follows. Keywords are written in uppercase, because you might have been playing tricks with overloading the lowercase equivalents. In the interest of brevity we have omitted most of these initial comments. Cumulate is given as a way not to write macros if you can help it in this case, I couldn't. A better example is reverse which reverses the order of the elements in a vector without resorting to a DO loop.
The macro da provides a set of double quotes to escape these unwanted interpretations. DELETE HISTORY deletes the last command on the history buffer, so del1 alone on a line will delete itself, which can be used to prevent a command from appearing on the history list, for example changing devices with dev ; dev also defines a variable device which is used by the hcopy and hmacro macros to make hardcopies, while returning you to your initial device.
You should be careful not to include more than one del1 macro in any macro that you write yourself, as each del1 will remove a command from history and you could find commands mysteriously disappearing. Gauss evaluates a Gaussian, e. For this example to work, you have to define variables mean and sig first.
There is an example of reading variables from files and using them in macro get. This variable is then used to READ a vector, which is given the appropriate name. So if a file looks like: This is an example file alpha beta gamma delta 1 10 0. The macros hcopy and hmacro make hardcopies of, respectively, the playback buffer and a macro. Both assume that the variables device and printer are set. If all is well, the macros switch to device printer with an argument to specify which sub-printer is desired. We have so many laser printers here When the printer device is closed, hardcopy will result.
The first if present is taken to be the desired laser printer 17 , the next argument is the number of the first line that you want played back, and the third is the last line number. If you omit both line numbers you'll get the whole buffer; if you omit the second you'll just get the one line. The playback macro deals with its arguments in a similar way, and is discussed further in the examples at the end of this section. Load2 is similar, but it looks in directory macro2. The macro unload not listed here will undefine the load ed macros.
If you want to put errorbars on logarithmic plots, logerr is the macro you've been looking for. It calculates the correct length for the errorbars, and plots them de-logging and re-logging as appropriate. Redefining the arguments means that the macros don't have to define, and then delete, a couple of variables to hold the expressions.
Now that you have had your appetite whetted, we strongly recommend that you take the time to look through the other macros that are available see section The System Macro Libraries. Otherwise how would you know that there are macros to draw arrows on plots, do KS and Wilcoxon tests on vectors, and a host of other good things?
In all these examples, we'll use the del1 macro discussed above to keep commands off the history list. Let's start with a Fourier series, to demonstrate SM's ability to manipulate vectors. All keywords are capitalised for clarity. Then type the following commands: You should now have a part of a square-wave, truncated at 0. Now consider a simpler way of doing the same thing. Fortunately there is a way to change this, using the macro editor.
First define a macro consisting of all the commands on the history list: Now you could type all to run your new macro, or put it back onto the history list. Now the playback command will run all those commands, and produce a better squarewave. The trick of including a del1 in macros is pretty common, for example h is defined as del1 HELP so that it won't appear on the history list.
We discussed the possibility of just playing back a limited number of lines while talking about hcopy , just say playback n1 n2. Now that you have a set of commands which produce a Fourier plot, it would be nice to define a macro to make plots, taking the number of terms as an argument, and then free the history buffer for other things. After a playback, the macro all is defined, so let's change its name to square. Use or control-P to get to line 0 and change the number of arguments from 0 to 1, and the name of the macro from all to square the space between the name and the: Exit with control-X , clear the screen with era and type square Now how do you save your nice macro?
In fact there is a command SAVE to save everything which can be a mindless way of proceeding. A macro similar to this Fourier macro called square is in the file demos in the default macro directory and was used to produce the top left box of the cover to this manual. To try it yourself, type something like load demos square But enough of macros which fiddle with the history buffer. Here are four sets of macros which do useful things, and may give some idea of the power available. First a macro to use the values of a third vector to mark points, then one to do least-squares fits to data points, then a macro to join pairs of points, and finally some macros to handle histograms and Gaussians.
The top right box of this manual's cover was made using this macro. Nowadays you'd simple read the column that you want to label the point with as a string e. PTYPE lab , and plot the points as usual e. The least-squares macro makes heavy use of the SUM operator. It could be used to find the dimension of a vector too, but only clumsily, and DIMEN is provided anyway. It could be easily generalised to deal with weights, fits constrained to pass through the origin, quadratics Our third example connects pairs of points.
This was written to deal with a set of data points before and after a certain correction had been applied. SM allows you to plot a pair of vectors as a histogram, but what if you have only got the raw data points, not yet binned together? Fortunately, SM can do this binning for you. Consider the following macro: The macro we discussed above can now be written much more efficiently as: So you could plot it with lim xx yy box hi xx yy , and maybe it looks like a Gaussian. So what is the mean and standard deviation?
What if you don't like the way that the histogram looks? Try the macro barhist. Now, if you wanted to plot a lognormal, you'd have to write your own macro, and you could use SORT to find medians and add another macro to utils , followed by one to find Wilcoxon statistics Since this was written a wilcoxon macro was donated to stats.
This chapter is not really needed as all of its contents can be found elsewhere in this manual, but as people manage to become confused anyway, here's a summary. There are three ways in which characters can alter SM's behaviour: If you are confused, you might find a verbosity of four or five helpful. As a reasonably complex example, try to guess the output from: SM now supports python; with a modicum of effort it could be used with perl or ruby or To try this out, say with the python port python , and then import sm sm. Python Python To use SM with python, you must have the numpy package installed.
After installing SM, you'll have to add your destination library e. Keywords are reserved, so don't try to use them as macro names or whatever. You can use the lowercase forms if you explicitly ask to be allowed to overload them. The control words are: SM plotting keywords are: This has nothing to do with their use in subscripting arrays!
Glossary of Terms used in this Manual. ABORT closes the current device without producing any hardcopy. If you are writing an output file it will be removed. The difference is that AND doesn't evaluate the right-hand-side of the expression if the left-hand-side is false; See section If , for examples. It also causes points to be rotated counter-clockwise by D degrees. If D is non-zero it will force axis and other labels to be written with SM's internal fonts, and will overrule the tendency to put x-axis labels horizontal, and y-axis labels vertical.
For plotting points the full vector of values is used, with the point rotated by the value of expr. If more points are specified than the dimension of expr, the first element will be used for the excess. Apropos lists all macros whose name or introductory comments match the given pattern.
Probably the most common use for the command is simply to look for a word -- e. If your system supports it, APROPOS will also search the help files for the given pattern in this case matches may not extend over more than one line. If the pattern matches more than once each match will be printed, merged together if appropriate and separated by line of dashes otherwise.
The pattern is a slightly restricted version of a normal Unix regular expression, specifically: A - may appear as the special range Usually the aspect ratio is calculated by SM to make characters look right and to make square points square , but it is sometimes useful to override this, especially when positioning labels on graphs that will be plotted on printers of different aspect ratios.
It might be worth going through an example. Suppose that you want to make a plot that really is square when printed; how should you proceed? The available plotting area runs from on each axis. So a plot set up as location will have the same aspect ratio as the plotting device, in general rectangular. There is a problem with this; the sizes of points and labels are varied to look right with the current aspect ratio.
This means that a putlabel 5 Hello World command that looks fine on the screen of your workstation will look awful on the printer. How do you do that? There are also some special operators: It gives a result in the range -pi -- pi dealing correctly with divisions by zero. DO generates a range of values, e.
You can specify an increment, so do 5,1,-1 is 5 4 3 2 1. See, for example, the macro interp. You should not assume any precedence between logical and bitwise operators, because if you do you'll be fooled e. The two expressions give the x and y values where the image is to be sampled. Note that values on bin boundaries go into the higher bin. You could do this with a loop but?: You can turn down the verbosity, of course, or you could try sending mail us mail to see if we can't fix it but it isn't easy, or else we'd have done it already. The third form is more obscure: ILABEL is 0 for no labels, 1 for labels parallel to axis, 2 for perpendicular to axis, and 3 for neither labels nor ticks.
ANGLE determines the angle of the axis. ICLOCK is used for too many purposes; it's treated as three integers of 1, 2, and 1 bits respectively. Control the ticks orientation: Control the tick direction: Control which side of the axis the ticks appear: If you prefer not to think in terms of bitwise operators, this can be written as if ICLOCK is even the ticks are anticlockwise on the axis, if odd they are clockwise. You usually want the ticks perpendicular to the axes, and this is what you get with ICLOCK 0 or 1; if it is 2 or 3 the ticks are vertical, and if 4 or 5 they are horizontal.
The labels are on the opposite side of the axis from the ticks unless you add 8 to the numbers given above. For example, the following commands are equivalent to BOX: If you don't have a shift key and try using lower case obafgkm you'll be surprised as all the letters are not at the same level as they don't all have the same height. The easiest way to deal with this is to make them all the same height: If that leaves too much space try: If you want more control over placement and sizes of axis labels and ticks, you can force SM to draw them separately: You'll still get a box, but no ticks or labels.
This was changed in V2. To specify logarithmic axes you should now specify the logarithms, just as you do to BOX. For example, to draw a logarithmic axis running from 1 to , specify A1 as 0 and A2 as 3, rather than 1 and An ILABEL of 0 means to omit axis labels, 1 produces labels parallel to the axis, 2 perpendicular, 3 omits both labels and tickmarks, and 4 omits the axis entirely. See section Notation if you want to control the use of floating point or exponential notation, and some details on how to draw exponents.
If you want more control over your axis labels, see section Axis. It might be wise to enclose it in quotes, e. When you exit SM, you will be back where you started. If the IF clause is present, only connect those points for which expr see the section on vector arithmetic is non-zero. Only contiguous points in the input vectors will be connected, resulting in a number of line-segments.
It is not possible to produce labeled contours. If a contour line runs into a missing data point it simply stops, rather than being made to join up with some other line that also runs into a missing point. The colours are those composed of three, zero, one, or two of the primary colours red, green, and blue. When a device is opened it sets default to some device specific value e. If the expr is string-valued it specifies the names to be used for the colours that you have just defined.
Any connection between the names and colours is, of course, up to you. So another way to get white lines would be to say: You can use any names you like, you are certainly not restricted to the initial set.
American Book Review :: Best Last Lines from Novels
You can reset the colours to their default i. If you want to add a new colour you can say: This was implemented to allow the X server to talk about white as , but might prove useful to you, too. It is probably a good idea to use as few colours as possible, as they are scarce resources on most displays. If you specify more colours than are physically available, or more than the device driver thinks that you deserve, SM will interpolate your values of CTYPE for you. If you are using X11 see section Device , you will probably need to use the -cmap flag when openinig your device if you want to allocate many private colours.
You may also be able to specify a background colour as background. This is either a colour name or a set of three integers in the range specifying the red, green, and blue values. On some devices the name of the background colour may be chosen from a wider selection; for example if you are using Xwindows you may use any name from the colour database. Display the cross-hair cursor to enable you to get positions in user coordinates.
Usually successive positions overwrite each other, but if a digit is used to mark a point then the position is followed by a newline, so the next time you hit a key its position will appear on the next line. You can remember that digits lead to numerous values appearing. If the verbosity see section Verbose is one or more, a message will be printed reminding you what keys to use. Many graphics devices have things called "GIN terminators". If you have trouble check your graphics setup screen, then with your SM Guru who can look up in graphcap to see what is expected. SM provides you with a cursor, and every time that you hit a key it prints its position just as above.
The SunWindows cursor is slightly different. The cursor position is given by a pointing finger it's the best we could do , and SM won't see any characters typed at the keyboard until you hit a carriage return. Device sunwindows is obsolete anyway, you should simply switch to using the sunview driver.
Its cursor has a bug, in that it only sees every other character typed at the keyboard. If I knew why I'd fix it. Use file file as the source of data read with the READ command. The file is assumed to have numerical data in columns separated by spaces, or tabs.
If the file can't be opened for read, you will be warned. See the READ command to see how to read the data. You may need to quote the filename, e. If they must persist DATA "3. All of these varieties of DEFINE define variable name to have some value, but as variables can be defined in all sorts of ways there are a good many possibilities.
Such local variables are automatically destroyed when leaving the macro within which they were created, and may not be explicitly deleted. This is similar to the behaviour of numbered variables, except that they really are local i. It is because such loop variables are automatically destroyed that attempts to delete local variables are not reported at VERBOSE levels of 1 or less.
When possible, it is more efficient to use vectors to perform calculations on scalars, rather than putting them into variables. It is also more efficient and more obscure! As a special dispensation, the expression can be an element of a string-valued vector elements of arithmetic vectors are allowed too of course.
If name can't be found, and is capitalised, SM will look for it in the environment as a logical variable for VMS users. The current plot limits are fx1 etc. In the case of angle , expand , and ptype , if you used a vector to set e. This sort of variable changed a little with version 2. The variables that you can use have not changed, but their usage has slightly. The old value of the variable if defined is printed within , and is taken to be the default if you simply hit carriage return.
If the line begins with a the first character is simply ignored when defining variables. Choose a device to plot to. Exactly which devices are available depends on your hardware configuration and how SM was compiled. When you specify a device the previous device is closed, which may lead to some action being taken for example, sending a plot to a printer.
In some cases all the information that SM needs to plot to the device is available there for example xterm or postscript ; such devices are referred to as stdgraph devices. Otherwise the graphcap entry will contain the name of the real device driver, for example x Anything else on the line is passed to the device driver. In particular, for the stdgraph devices an argument that is not specifically processed by the device is taken to be the name of a file to save the plot in.
Thus device postscript foo. It is used to support metafiles, which allow you to save a plot as you display it, and finally send it to a different device. Especially for hardcopy devices, you may have to specify which one you want, e. Because this depends on how your local graphcap was configured, you'll have to see your Guru for guidance; see section The Stdgraph Graphics Kernel.
The device driver may or may not choose to honour a background entry as well. These colours may be specified either as names see CTYPE , or the background colour may be given as a set of three numbers, which are interpreted as the red, green, and blue intensities in the range 0 - Some devices may allow you a wider selection of background names; for example the Xwindows driver allows any name from the colour database. If you want to use some foreground colour that CTYPE doesn't usually understand you must define it before opening the device.
Different ways of plotting to the same device e. It is useful because it is always available; it's the current device when SM is started. Because SM submits plots only when the current device is closed, and because opening nodevice closes the current device, it is also used by the hardcopy command in fact hardcopy is a macro that expands to DEVICE nodevice. He gets all the credit for the PC version of SM, but of course he is not responsible for any remaining bugs some of which we almost certainly created while merging the PC and regular versions.
The first, devtype , is the type of hardware that you are running. The second argument, mode , determines how SM switches between screen and graphics modes. Your options are none , swap the default , or switch ; experiment to see which works better for you. This is very dependent on the details of your graphics card, and we see no general way to prevent its appearance. Two optional arguments are currently supported: This will significantly increase the drawing speed, but the contents of the graphics window will not be redrawn when portions of the window are uncovered or when the window is resized.
Here is a program to show examples of variables:. A variable in Python can store any type of data - in this example we stored some strings e. Note the difference between strings and variable names. Strings are marked with quotation marks, which tells the computer "don't try to understand, just take this text as it is":.
Variable names are written without any quotation marks and instruct the computer "use the value I've previously stored under this name":. Okay, so we have these boxes called variables and also data that can go into the variable. Even if it is the same variable on both sides the computer still reads it as "First find out the data to store and then find out where the data goes".
The second half of the program uses type which tells what a variable is. Numbers are of type int or float , which are short for integer and floating point mostly used for decimal numbers , respectively. Text strings are of type str , short for string. Integers and floats can be worked on by mathematical functions, strings cannot. Notice how when python multiplies a number by an integer the expected thing happens.
However when a string is multiplied by an integer the result is that multiple copies of the string are produced i. The operations with strings do different things than operations with numbers. Here are some interactive mode examples to show that some more. Write a program that gets 2 string variables and 2 integer variables from the user, concatenates joins them together with no spaces and displays the strings, then multiplies the two numbers on a new line.
Here we present our first control structure. Ordinarily, the computer starts with the first line and then goes down from there. Here's the source for a program that uses the while control structure:. And you thought it couldn't get any worse after turning your computer into a five dollar calculator? So what does the program do? The first time the computer sees this while statement, a is equal to zero, which means a is less than 10, so the computer proceeds to run the succeeding indented, or tabbed in, statements.
In other words, as long as a is less than ten, the computer will run the tabbed in statements. Reaching that point, the program will not run the indented lines any longer. The while statement only affects the lines that are indented with whitespace. Now that we have while loops, it is possible to have programs that run forever. An easy way to do this is to write a program like this:. This program will output Help, I'm stuck in a loop. The way to stop it is to hit the Control or Ctrl button and C the letter at the same time.
This will kill the program. Note the output on a single line by use of a comma at the end of the print statement. Write a program that asks the user for a Login Name and password. Then when they type "lock", they need to type in their name and password to unlock the program. You will have to indent the rest of the program when you add this at the top of the code, but don't worry, you don't have to do it manually for each line! Just highlight everything you want to indent and click on "Indent" under "Format" in the top bar of the python window.
Note that you can use empty strings like this: Notice the or in while name! You can probably figure out how it works. This method, although a bit more crude also works. Notice it uses the as of yet un-introduced if function. As always I believe I should start each chapter with a warm-up typing exercise, so here is a short program to compute the absolute value of a number:. So what does the computer do when it sees this piece of code? If n is less than zero Python runs the line " print 'The absolute value of', int n , 'is: Otherwise it runs the line " print 'The absolute value of', int n , 'is: An if statement is followed by an indented block of statements that are run when the expression is true.
Optionally after the if statement is an else statement and another indented block of statements. This second block of statements is run if the expression is false. There are a number of different tests that an expression can have. Here is a table of all of them:. Another feature of the if command is the elif statement. It stands for else if and means if the original if statement is false but the elif part is true, then do the elif part.
And if neither the if or elif expressions are true, then do what's in the else block. There can be more than one elif expression, allowing multiple tests to be done in a single if statement. Modify the higher or lower program from this section to keep track of how many times the user has entered the wrong number. If it is more than 3 times, print "That must have been complicated. Write a program that asks for two numbers. If the sum of the numbers is greater than , print "That is a big number.
By now if you have been messing around with the programs you have probably found that sometimes the program does something you didn't want it to do. This is fairly common. Debugging is the process of figuring out what the computer is doing and then getting it to do what you want it to do. This can be tricky.
I once spent nearly a week tracking down and fixing a bug that was caused by someone putting an x where a y should have been. The first thing to do this sounds obvious is to figure out what the program should be doing if it is running correctly. Come up with some test cases and see what happens. For example, let's say I have a program to compute the perimeter of a rectangle the sum of the length of all the edges.
I have the following test cases:. I now run my program on all of the test cases and see if the program does what I expect it to do. If it doesn't then I need to find out what the computer is doing. More commonly some of the test cases will work and some will not. If that is the case you should try and figure out what the working ones have in common. For example here is the output for a perimeter program you get to see the code in a minute:.
Notice that it didn't work for the first two inputs, it worked for the next two and it didn't work on the last one. Try and figure out what is in common with the working ones. Once you have some idea what the problem is finding the cause is easier. With your own programs you should try more test cases if you need them. The next thing to do is to look at the source code. One of the most important things to do while programming is reading source code.
The primary way to do this is code walkthroughs. A code walkthrough starts at the first line, and works its way down until the program is done. While loops and if statements mean that some lines may never be run and some lines are run many times. At each line you figure out what Python has done. Lets start with the simple perimeter program. Don't type it in, you are going to read it, not run it. The source code is:. The next program we will do a code walkthrough for is a program that is supposed to print out 5 dots on the screen. However, this is what the program is outputting:. This program will be more complex to walkthrough since it now has indented portions or control structures.
You need to figure out what the program is doing. You need to figure out what the program should do. Figure out what the difference between the two is. Debugging is a skill that has to be practiced to be learned. If you can't figure it out after an hour, take a break, talk to someone about the problem or contemplate the lint in your navel.
Come back in a while and you will probably have new ideas about the problem. To start off this chapter I am going to give you an example of what you could do but shouldn't so don't type it in:. The program seems a little repetitive. Programmers hate to repeat things -- that's what computers are for, after all! Note also that finding the absolute value changed the value of the variable, which is why it is printing out 23, and not in the output. Fortunately Python allows you to create functions to remove duplication.
Here is the rewritten example:. The key feature of this program is the def statement. The def keyword short for "define" starts a function definition. Next, comes the single function parameter named, " n ". A parameter holds a value passed into the function from the program that "calls" the function. Parameters of a function in the def statement, must be enclosed within a parenthesis. The value that is passed to a function parameter is called an argument.
So for now, a parameter and argument points to the same thing. The block of indented statements after the ": The statements within the function continue to be run until either the indented statements end, or a " return " statement is encountered. The return statement returns a value back to the place where the function was called in the calling program.
Notice how the values of a and b are not changed. Functions can be used to repeat tasks that don't return values. Here are some examples:. That example shows some more stuff that you can do with functions. Notice that you can use one or more parameters, or none at all. Notice also that a function doesn't necessarily need to "return" a value, so a return statement is optional.
When eliminating repeated code, you often notice that variables are repeated in the code. In Python, these are dealt with in a special way. So far, all variables we have seen are global variables. Functions work with a special type of variables called local variables. These variables only exist within the function and only while the function is running. When a local variable has the same name as another variable such as a global variable , the local variable hides the other.
Well, these next examples which are a bit contrived should help clear things up. Variable assignments inside a function do not override global variables, they exist only inside the function. After the function finishes running and the value of an a variable is printed again, we see the value assigned to the global a variable being printed. Another thing to notice is the NameError that happens at the end. All the local variables are deleted when the function exits. If you want to get something back from a function, then you will have to use return statement within the function.
When a global variable is accessed inside a function, the function uses only value of the global variable but it cannot change the value assigned to the global variable outside the function. Functions allow local variables that exist only inside the function and can hide other variables that are outside the function. This program should include a menu interface. Some people find this section useful, and some find it confusing. If you find it confusing you can skip it or just look at the examples.
Now we will do a walk through for the following program:. Basically this program creates a positive integer multiplication function that is far slower than the built in multiplication function and then demonstrates this function with a use of the function. This program demonstrates the use of recursion, that is a form of iteration repetition in which there is a function that repeatedly calls itself until an exit condition is satisfied. It uses repeated additions to give the same result as mutiplication: Should you still have problems with this example, look at the process backwards.
What is the last step that happens? We can easily make out that the result of mult 3, 0 is 0. Since b is 0 , the function mult 3, 0 will return 0 and stop. So what does the previous step do? So the next lines are executed: So now the variable rest is set to 0. The next line adds the value of rest to a , and since a is 3 and rest is 0 , the result is 3.
Now we know that the function mult 3, 1 returns 3. But we want to know the result of mult 3,2. Therefore, we need to jump back to the start of the program and execute it one more round: We know from the last round that this result is 3. The point of this example is that the function mult a, b starts itself inside itself. It does this until b reaches 0 and then calculates the result as explained above. Programming constructs of this kind are called recursive and probably the most intuitive definition of recursion is:.
These last two sections were recently written. I have been known in the past to make simple things incomprehensible. If the rest of the tutorial has made sense, but this section didn't, it is probably my fault and I would like to know.
You have already seen ordinary variables that store a single value. However other variable types can hold more than one value. The simplest type is called a list.
- Edition 2.4.16 (or later if we didn't update this page);
- Non-Programmer's Tutorial for Python 2.6/Print version;
- Song Tune in C Major, II.
- NATO Adaptation: Society, Institutions, Military (U.S. Mission Lectures: Building the U.S.-Led NATO Architecture of Values & Security Book 3);
Here is an example of a list being used:. In this example the months is a list. The [ and ] start and end the list with commas , separating the list items. A list consists of items that are numbered starting at 0. In other words if you wanted January you would use months. Give a list a number and it will return the value that is stored at that location. Lists can be thought of as a series of boxes. Each box has a different value. Each box is referenced by its number so the statement demolist would get 'life' , demolist would get 42 and so on up to demolist getting 9.
The next example is just to show a lot of other stuff lists can do for once I don't expect you to type it in, but you should probably play around with lists until you are comfortable with them. This example uses a whole bunch of new functions. Notice that you can just print a whole list. Next the append function is used to add a new item to the end of the list. The valid indexes as in numbers that can be used inside of the  of a list range from 0 to len - 1.
The index function tells where the first location of an item is located in a list. The line Next we will loop through the list is a just a reminder to the programmer also called a comment. Python will ignore any lines that start with a. Meanwhile the print statement prints out each element of the list. The del command can be used to remove a given element in a list. The next few lines use the in operator to test if an element is in or is not in a list. The sort function sorts the list. This is useful if you need a list in order from smallest number to largest or alphabetical. Note that this rearranges the list.
In summary, for a list, the following operations occur:. That was a long program. Let's take a look at the source code. This line starts a loop that allows the menu system for this program. The next few lines display a menu and decide which part of the program to run. If len returns 0 , then the list is empty. Then, a few lines later, the statement namelist. It uses the append function to add an item to the end of the list. Jump down another two lines, and notice this section of code:.
Here the index function is used to find the index value that will be used later to remove the item. Congratulations, with lists under your belt, you now know enough of the language that you could do any computations that a computer can do this is technically known as Turing-Completeness. Of course, there are still many features that are used to make your life easier. The values True and False point to 1 and 0, respectively. They are often used in sanity checks, loop conditions etc.
You will learn more about this a little bit later chapter Boolean Expressions. Also, add a new question to ask, "What noise does a truly advanced machine make? The output looks awfully familiar but the program code looks different. The first line uses the range function.
The range function uses two arguments like this range start, finish. Note that this program could have been done in a shorter way:. The next line for count in onetoten: A for control structure looks like for variable in list: As for goes through each element in a list it puts each into variable. That allows variable to be used in each successive time the for loop is run through. Here is another example you don't have to type this to demonstrate:. Notice how the for loop goes through and sets item to each element in the list.
Notice how if you don't want print to go to the next line add a comma at the end of the statement i. So, what is for good for? The first use is to go through all the elements of a list and do something with each of them. Here's a quick way to add up all the elements:. Or you could write a program to find out if there are any duplicates in a list like this program does:. Okay, so how does it work? Here is a special debugging version to help you understand you don't need to type this in:.
The reason I put so many print statements in the code was so that you can see what is happening in each line. By the way, if you can't figure out why a program is not working, try putting in lots of print statements so you can see what is happening. First the program starts with a boring old list. Next the program sorts the list. This is so that any duplicates get put next to each other.
The program then initializes a prev ious variable. Next the first element of the list is deleted so that the first item is not incorrectly thought to be a duplicate. Next a for loop is gone into. Each item of the list is checked to see if it is the same as the previous. If it is a duplicate was found. The value of prev is then changed so that the next time the for loop is run through prev is the previous item to the current. Sure enough, the 7 is found to be a duplicate. The other way to use for loops is to do something a certain number of times. Here is some code to print out the first 9 numbers of the Fibonacci series:.
Everything that can be done with for loops can also be done with while loops but for loops give an easy way to go through all the elements in a list or to do something a certain number of times. What is going on? The program consists of a bunch of funny looking print statements. Each print statement prints a number and an expression. The number is to help keep track of which statement I am dealing with.
Notice how each expression ends up being either False or True. In Python, false can also be written as 0 and true as 1. The operator and means if both the statement before and the statement after are true then the whole expression is true otherwise the whole expression is false. The behavior of and can be summarized as follows:. Notice that if the first expression is false Python does not check the second expression since it knows the whole expression is false.
The expression could be rewritten as print 5, a! Here is the table:. The or operator returns true if the first expression is true, or if the second expression is true or both are true. If neither are true it returns false. Notice that if the first expression is true Python doesn't check the second expression since it knows the whole expression is true.
This works since or is true if at least one half of the expression is true. The first part is true so the second part could be either false or true, but the whole expression is still true. Notice that the parentheses changed the expression from false to true. When either count is greater than the last index of copy or a match has been found the and is no longer true so the loop exits. The if simply checks to make sure that the while exited because a match was found. The other "trick" of and is used in this example.
If you look at the table for and notice that the third entry is "false and won't check". This is because Python knows that if the first is false then they can't both be true. This is known as a short circuit and is useful if the second half of the and will cause an error if something is wrong. A common mistake for people new to programming is a misunderstanding of the way that boolean operators works, which stems from the way the python interpreter reads these expressions.
This is not so. To see what I'm talking about, start an interactive session with the interpreter and enter the following expressions:. At this point, the and and or operators seem to be broken. It doesn't make sense that, for the first two expressions, 'a' is equivalent to 'a' or 'b' while 'b' is not. Furthermore, it doesn't make any sense that 'b' is equivalent to 'a' and 'b'. After examining what the interpreter does with boolean operators, these results do in fact exactly what you are asking of them, it's just not the same as what you think you are asking.
When the Python interpreter looks at an or expression, it takes the first statement and checks to see if it is true. If the first statement is true, then Python returns that object's value without checking the second statement. This is because for an or expression, the whole thing is true if one of the values is true; the program does not need to bother with the second statement. On the other hand, if the first value is evaluated as false Python checks the second half and returns that value. That second half determines the truth value of the whole expression since the first half was false.
This "laziness" on the part of the interpreter is called "short circuiting" and is a common way of evaluating boolean expressions in many programming languages. Similarly, for an and expression, Python uses a short circuit technique to speed truth value evaluation. If the first statement is false then the whole thing must be false, so it returns that value. Otherwise if the first value is true it checks the second and returns that value. One thing to note at this point is that the boolean expression returns a value indicating True or False , but that Python considers a number of different things to have a truth value assigned to them.
To check the truth value of any given object x , you can use the function bool x to see its truth value. Below is a table with examples of the truth values of various objects:. Now it is possible to understand the perplexing results we were getting when we tested those boolean expressions before. Let's take a look at what the interpreter "sees" as it goes through that code:. So Python was really doing its job when it gave those apparently bogus results. As mentioned previously, the important thing is to recognize what value your boolean expression will return when it is evaluated, because it isn't always obvious.
Going back to those initial expressions, this is how you would write them out so they behaved in a way that you want:. When these comparisons are evaluated they return truth values in terms of True or False, not strings, so we get the proper results. Write a program that has a user guess your name, but they only get 3 chances to do so until the program quits. This chapter is about dictionaries. If you open a dictionary, you should notice every entry consists of two parts, a word and the word's definition.
The word is the key to finding out what a word means, and what the word means is considered the value for that key. In Python, dictionaries have keys and values. Keys are used to find values. Here is an example of a dictionary in use:. This program is similar to the name list from the earlier chapter on lists note that lists use indexes and dictionaries don't. Here's how the program works:. Dictionaries have keys and values.
Keys can be strings or numbers. Keys point to values. Values can be any type of variable including lists or even dictionaries those dictionaries or lists of course can contain dictionaries or lists themselves scary right? Here is an example of using a list in a dictionary:.
Here's how the program works. Basically the variable students is a dictionary with the keys being the name of the students and the values being their grades. The first two lines just create two lists. Next the keys are sorted in the line keys. The later lines of the program implement the various options of the menu. The remove student entry just deletes a student similar to the telephone book example. The record grades choice is a little more complex. The reason for the missing statement is that grades is actually another name for students[name] and so changing grades changes student[name].
Dictionaries provide a easy way to link keys to values. This can be used to easily keep track of data that is attached to various keys. Here's this chapter's typing exercise name it cal. If the file is named calendar. I skipped some of the output, but I think you get the idea. The first line import calendar uses a new command import. The command import loads a module in this case the calendar module. To see the commands available in the standard modules either look in the library reference for python if you downloaded it or go to http: If you look at the documentation for the calendar module, it lists a function called prcal that prints a calendar for a year.
Another way to write the program is:. This version imports a specific function from a module. Here is another program that uses the Python Library name it something like clock. The program just does a infinite loop True is always true, so while True: Notice how multiple names after the import statement are used in the line from time import time, ctime. The Python Library contains many useful functions. These functions give your programs more abilities and many of them can simplify programming in Python.
Use the Python documentation to find an appropriate module and function to do this. We have already seen lists and how they can be used. Now that you have some more background I will go into more detail about lists. First we will look at more ways to get at the elements in a list and then we will talk about copying them. All those examples should look familiar to you.
NOMINATED BEST LAST LINES FROM NOVELS
If you want the first item in the list just look at index 0. The second item is index 1 and so on through the list. However what if you want the last item in the list? This way works since the len function always returns the last index plus one. There is an easier way to do this. In Python the last item is always index The second to the last is index -2 and so on. Here are some more examples:.
Another useful way to get into parts of lists is using slicing. Here is another example to give you an idea what they can be used for:. Slicing is used to return part of a list. You can use both types of indexing:. Another trick with slicing is the unspecified index. If the first index is not specified the beginning of the list is assumed. If the last index is not specified the whole rest of the list is assumed.
This probably looks surprising since a modification to b resulted in a being changed as well. This means that b can be thought of as another name for a. Hence any modification to b changes a as well. However some assignments don't create two names for one list:. All assignment operations create a reference. When you pass a list as an argument to a function you create a reference as well. Most of the time you don't have to worry about creating references rather than copies. However when you need to make modifications to one list without changing another name of the list you have to make sure that you have actually created a copy.
There are several ways to make a copy of a list. The simplest that works most of the time is the slice operator since it always makes a new list even if it is a slice of a whole list:. Taking the slice [: However it only copies the outer list. Any sublist inside is still a references to the sublist in the original list. Therefore, when the list contains lists, the inner lists have to be copied as well. You could do that manually but Python already contains a module to do it. You use the deepcopy function of the copy module:.
First of all notice that a is a list of lists. This happens because the inner arrays are still references when the slice operator is used. However with deepcopy c was fully copied. The good news is that you only have to worry about references when using dictionaries and lists. Numbers and strings create references when assigned but every operation on numbers and strings that modifies them creates a new copy so you can never modify them unexpectedly.
You do have to think about references when you are modifying a list or a dictionary. By now you are probably wondering why are references used at all? The basic reason is speed. It is much faster to make a reference to a thousand element list than to copy all the elements. The other reason is that it allows you to have a function to modify the inputed list or dictionary. Just remember about references if you ever have some weird problem with data being changed when it shouldn't be.
What these programs demonstrate is that strings are similar to lists in several ways. The shout function shows that for loops can be used with strings just as they can be used with lists. The middle procedure shows that that strings can also use the len function and array indexes and slices. Most list features work on strings as well. This works because the computer represents the characters of a string as numbers from 0 to Python has a function called ord short for ordinal that returns a character as a number. There is also a corresponding function called chr that converts a number into a character.
With this in mind the program should start to be clear. The first detail is the line: If it is then the next lines are used. This value is converted back to a character that is now upper case. If you haven't guessed already the function repr can convert a integer to a string and the function int can convert a string to an integer. The function float can convert a string to a float. The repr function returns a printable representation of something. Here are some examples of this:. The int function tries to convert a string or a float into a integer.
There is also a similar function called float that will convert a integer or a string into a float.
Related After The Farewell 2: ~ The bars on the window divide the sky into long rectangles.
Copyright 2019 - All Right Reserved