This tutorial is written for those who have background knowledge of object oriented programming languages such as C++ and Java. This tutorial focuses on introducing the subset of Python used in the Repy (Restricted Python) language supported by the Seattle testbed. After reading this tutorial, you should walk through the [RepyTutorial].
NOTE WINDOWS USERS: You must have Python2.5 or Python2.6 installed on your computer. Follow the instructions [InstallPythonOnWindows] to check if Python2.5 or Python2.6 is currently installed on your system and to get directions on how to install Python2.6 if it is not installed.
ALL USERS: You have to install Repy before starting the tutorial. You can download Repy here.
TOC(inline)
Python is an interpreted language, which in a nutshell means that you do not need to compile python code in order to execute it. Here's an example of a program that prints ‘Hello World’.
To execute this program, you can place the above source code into a file, say ‘test.py’, and then run the program by executing the following statement on the command line:
This is the normal way to execute python code. However, since this tutorial is written for those who use Repy, we need to explain the different way to run Repy programs.
There are two ways to execute programs. You can run your programs on your local computer or on a remote VM that you control. Although our final goal is to run programs on the VMs, we explain the way to run programs on a local computer here because it's simple.
You can learn how to execute in the VMs in the [RepyTutorial].
You need to add more files as arguments to run the program above in your computer.
We need to make sure that you have the files named repy.py and restrictions.test in your current directory before executing the program like above. If you don't have the restrictions.test, Here is the [raw-attachment:restrictions.test].
Output is following
"Terminated" indicates that the program was terminated successfully. (This may not be displayed on all operating systems, and other operating systems may have different messages.)
"Hello World" is printed twice because of repys' architecture, which calls test.py twice.
If you want to print "Hello World" only once, you can change the code to the following:
You need to insert an if block to execute your code one time in initialize status.
Repy programs are called once upon program initialization and once upon normal program exit. The callfunc variable is set to initialize or exit depending on what the circumstance is. There is more detail about this in [PythonVsRepy].
From now on, we suppose all code below is in the if callfunc == 'initialize' block.
Instead of executing this program from the command line in batch mode, you could enter and run the code in interactive mode.
Because Repy doesn't have the interactive mode, and uses different function names from regular python, you can test only simple function operations in the interactive mode.
While in interactive mode, you can test your simple code before executing and look up the command history by using the arrow keys. To exit interactive mode, hit ctrl-d on Unix or ctrl-z on Windows.
Type is not declared in Python. However, the Python interpreter keeps track of the type of all objects. Thus Python variables don’t have types, but their values do.
Result
Python contains many high level operations.
Here is a simple example that prints the number of words in ‘Hello World”
Result:
The method split() is a member of the string class. It splits a string into a list of words and len() returns the number of elements in a list.
In C++ and Java, we use curly braces({}) as a block definition, but in Python, it has a different syntax.
The first line should end with a colon(:) and from the next line on, lines should be indented until you've reached the end of the block.
In the example code, the range() function returns a list of consecutive integers. This will result in 10 iterations of the loop, 0 through 9.
Perhaps the most well-known statement type is the if statement. For example:
Result
There can be zero or more elif parts, and the else part is optional. The keyword ‘elif‘ is short for ‘else if’, and is useful to avoid excessive indentation. An if ... elif ... elif ... sequence is a substitute for the switch or case statements found in other languages.
Just like in most languages, there is a while statement that loops until the condition is false.
The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. For example (no pun intended):
Result
The break statement, like in C, breaks out of the smallest enclosing for or while loop. The continue statement, also borrowed from C, continues with the next iteration of the loop. Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.
This is exemplified by the following loop, which searches for prime numbers:
Result
The keyword def is used to define a function. Note once again that the colon and indenting are used to define a block which serves as the function body. A function can return a value, using the return statement. However, the function does not have a type even if it does return something, and the object returned could be anything—an integer, a list, or whatever.
Functions can also have arguments that have default values. The argument vales do not need to be specified by the caller. The following function call is the same as .
If you have some functions with many parameters, and you want to specify only some of them, then you can give values for such parameters by naming them - this is called keyword arguments. We use the name (keyword) instead of the position (which we have been using all along) to specify the arguments to the function.
There are two advantages - one, using the function is easier since we do not need to worry about the order of the arguments. Two, we can give values to only those parameters which we want, provided that the other parameters have default argument values.
Output
Finally, the least frequently used option is to specify that a function can be called with an arbitrary number of arguments. These arguments will be wrapped up in a tuple (see Tuples in Sequences). Before the variable number of arguments, zero or more normal arguments may occur.
open() returns a file object, and is most commonly used with two arguments: open(filename, mode).
The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used. mode can be ’r’ when the file will only be read, ’w’ for only writing (an existing file with the same name will be erased), and ’a’ opens the file for appending. Any data written to the file is automatically added to the end. ’r+’ opens the file for both reading and writing. The mode argument is optional; ’r’ will be assumed if it’s omitted.
When you’re done with a file, call f.close() to close it and free up any system resources taken up by the open file. After calling f.close(), attempts to use the file object will automatically fail.
Sequences are array-like but with some differences.
Lists are denoted by brackets and commas.
There are some useful list operations.
Python array has not only the same indexing structure as other languages but also backward indexing(negative indexing).
In the example above,
|| Value || 1 || 2 || 3 || || Positive Index || 0 || 1 || 2 || || Negative Index || -3 || -2 || -1 ||
Tuples are like lists, but are immutable. They are enclosed by parentheses or nothing at all, rather than brackets. The parentheses are mandatory if there is an ambiguity without them, e.g., in function arguments. A comma must be used in the case of an empty or single tuple, e.g., (,) and (5,).
The same operations can be used, except those which would change the tuple. So for example
Strings are essentially tuples of character elements. But they are quoted instead of surrounded by parentheses, and have more flexibility than tuples of character elements would have.
Dictionaries are associative arrays. The statement
sets x to what amounts to a 2-element array with x[’abc’] being 12 and x[’sailing’] equal to ’away’. We say that ’abc’ and ’sailing’ are keys, and 12 and ’away’ are values. Keys can be strings or any immutable object, e.g., numbers and tuples. Use of tuples as keys is quite common in Python applications, and you should keep in mind that this valuable tool is available.
Internal storage is organized as a hash table. This is why Perl’s analog of Python’s dictionary concept is actually called a hash.
Here are examples of usage of some of the member functions of the dictionary class:
The keyword ‘self’ is analogous to this in C++ and Java. Static variables in Python is ‘class name.variable name’. The constructor for a class is !__init!__.
superclass.!__init!__(self)
If a class b is the subclass of a class a, we need to write it like this:
Python functions usually don't have C-style error return code to check to see whether they succeeded. Instead, you use Python’s try/except exception-handling mechanism:
Here’s another example:
But the Python idiom also uses this for code which is not acting in an exception context. Say for example we want to find the index of the number 8 in the list x. If there is no such number in x, then we will append x to the list and return its index. We could do it this way:
The try statement has another optional clause which is intended to define clean-up actions that must be executed under all circumstances. A finally clause is always executed before leaving the try statement, whether an exception has occurred or not. For example:
Results are following
As you can see, the finally clause is executed in any event.
Note that an uncaught exception will cause the script to terminate.