Lab 1: Introduction of Python programming environment and first programming exercises

This lab has two parts:

  • Part A is intended to help you setup and familiarise yourself with the programming environment which you will be using throughout the course in the computer labs.

  • Part B introduces the first set of programming exercises you should complete.

If something unexpected happens, or if you get stuck, you can ask your tutors for help at any moment.

Both Part A and Part B should be completed during semester week 2. In general, it is not expected that you finish all the programming exercises during the scheduled 2 hour lab session. The normal workload for a 6-unit course is a bit over 10 hours per week. That means students in this course are expected to spend at least 5-6 hours per week practicing programming in addition to the scheduled lecture and lab times. We recommend reading through and attempting at least some of the exercises before your lab, since this will allow you to come to the lab prepared with questions to ask the tutors, and therefore to make better use of the lab time.

Part A - Labs operation, getting a working python environment and getting used to it#

Labs operation and environment setup#

Before you can start coding, you need an appropriate python programming environment. There are several possible environments. We will walk you through some of these, so that you can choose the one you are more comfortable with. To get started, please read the information on the main labs page here.

From now on we will assume you are sitting in front of one of the computers in the lab, so that we will be discussing the different options available there. Please note that the final exam will be carried out in the labs using the lab computers, NOT with your own device. The first step today is to get familiarized with the computers in the lab. To this end, read through the page accessible through the following link:

Lab computers guide

In any case, as you will also have to solve programming problems out-of-class, it is also strongly recommended that you install the software required in your own computer. To this end, follow the instructions in the page accessible through the following link when you are out-of-class (if you did not yet):

Installing python on your own computer

Note on organising your files and directories#

How you organise your files on your personal computer is up to you. However, please be aware than if you want to import module stored in python files (such as, e.g., robot.py), they will need to be in the same directory the python interpreter is running from. We recommend creating a directory called “comp1730” and then putting a separate directory for each lab inside it, so a “lab1” directory, a “lab2” directory, etc. Aside from helping you organise your work, this will also assist you in making sure that python can find the files you are trying to work with.

The python shell (and its more interactive variant ipython)#

The python shell (or interpreter), also known as REPL (from Read-Print-Eval-Loop), is a program that reads and executes “python programs”, or more specifically: text files with the extension .py which store sequences of python programming instructions. However, it also supports interactive commands (this is one of the hallmarks of python as a programming language for beginners, namely, interactivity). The python interpreter comes into two different flavours: (1) the standard, plain python shell; and (2) its more interactive variant ipython shell. The latter looks different to the former, but under the hood they are mostly the same.

As any other program in a computer, the python and ipython shells have to be executed before you can start using them. The “crude” way of executing a program in Linux is through the so-called Linux command-line terminal. You can open a command-line terminal by clicking on the Terminal icon at the bottom bar of the Desktop. At this point:

  • If you know how to open a Linux command-line terminal, open it, type the anaconda3 command and press the Enter key. This should trigger the anaconda shell. Then, from the anaconda shell you can trigger either the python or ipythoncommands to run the python and ipython shells, respectively.

  • If you do not know how to open a Linux command-line terminal, do not worry, you can either ask your tutor on how to do it or just continue reading. For most of you it will be likely more convenient to run the python interpreter through an IDE (Integrated Development Environment), such as Spyder or VSCode (covered below).

When you start the ipython shell you should see a message like this:

u1134396@n109lt08:~$ anaconda3
u1134396@anaconda:~$ ipython
Python 3.8.17 (default, Jul  5 2023, 20:41:08)
Type 'copyright', 'credits' or 'license' for more information
IPython 8.12.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: 

The Python version number may be different in different environments. The important thing is that it is python 3.

The prompt In [1]: indicates that the interpreter is waiting for you to type in a command or expression. (The number in brackets is a running counter of inputs and outputs.) If you start a standard python shell, the prompt will instead look like this:

>>>

Examples on these lab pages will be written using the ipython shell prompt. There are a few other differences between the two shells: ipython gives you some shortcuts to make typing in commands interactively easier, and prefixes the values that results from evaluating an expression with Out. When you use certain types of graphics (such as function plots), the ipython shell will show them inline in the shell window, while the python shell will show them in a separate window.

IDEs#

An Integrated Development Environment, or IDE, for python combines a text editor (for writing programs) with a python shell (interpreter), and some helpful functions to integrate the two (e.g., a debugger to help you out finding programming errors).

There are a variety of IDEs available in both the CSIT labs/InfoCommons computers and for download online. You will need to learn how to use one of them, and only one of them. If you do not have a strong preference, and/or you are starting to learn how to program, we highly encourage students to use either the Spyder or VSCode IDEs (instructions covered below).

IMPORTANT NOTE: we reiterate that you only need one and only one IDE. Spyder or VSCode are the two alternative IDEs that we recommend for those starting to learn how to program. If you have zero experience with programming, and/or limited computing literacy, then perhaps Spyder is the best option for you. If you find yourself confident enough, you might also try VSCode. You may also talk to your tutor in regards to this choice. Again, if you want to use any other IDE you feel comfortable with, we are also fine with it. However, we will only provide technical support for the recommended ones.

The Spyder IDE#

Spyder is the IDE that comes with Anaconda. It is available in both the CSIT lab environment and on the InfoCommons computers. You can find Spyder in the start menu of CSIT lab computers, and in the Windows start menu on the InfoCommons computers. If you do not know how to run Spyder in the computer labs, go to Lab computers guide.

The Spyder IDE provides you with an editor (to the left in the image below), a python interpreter (below on the right). There is also an area (top right, bounded by the violet box in the image below) which can have the variable explorer, show help, plots or act as a file explorer:

Spyder IDE

If the above image is too small on your browser, right click on it and open in a new tab to see it full-size.

To run a program that you’re editing or writing in Spyder, click the “Run” icon (green right-pointing triangle), or F5 (Fn-F5 on Macs) button. The first time you run a file this may bring up a dialog with some options: just click “Run” to accept the defaults.

First run dialog

You can see the current working directory for the python shell in the right side of the top bar. To change the working directory, click the “directory button” beside it. Don’t get confused by the path shown in the left side of the top bar - that is the location of the currently open file.

The VSCode IDE#

Visual Studio Code (or VSCode) is a lightweight yet powerful source code editor which aims to provide just the tools a developer needs for a quick code-run-debug cycle. Just like Spyder, it is also available for Windows, macOS and Linux.

The setup of the VSCode IDE in the computer labs is a little bit more involved than Spyder. Fortunately, we only need to perform this setup once and it will persist for the rest of the course. The instructions are available in the page accessible through the following link:

Setup instructions for VSCode IDE in the computer labs

Recall that you can also install VSCode on your own computer. See the instructions accessible through this link for more details.

Different ways of interacting with python#

There are two different ways of interacting with python. It is important that you understand the differences between them.

The first way to interact with python is to write code in the shell. You can tell you are working in the shell by the:

In [1]:

or

>>>

prompts at the beginning of each line. There are some differences depending on the development environment you are using (Spyder, VSCode, etc), but they all have some standard features:

  • When you write a line of code, python (usually) executes it immediately.
  • Python prints the return values of any expressions you evaluate in the shell, whether you ask it to or not.
  • If you want to run something twice, you have to type it in twice (or use the up/down arrows to find it in your input history).
  • You cannot keep anything between sessions (in other words, when you close the shell, the state of your program is lost).
  • Python will let you write functions in the shell, but if you want to change them later, you will have to re-type the entire function. This means that if you want to write any code that you want to test several times (such as, for example, a homework solution) then you should not do it in the shell.

The second way to interact with python is to write your code in a file, and then ask the python interpreter to execute all the code in the file in one go. This behaviour is more consistent between different development environments. It has the following features:

  • Nothing gets executed until you actually run the code file.
  • No output is printed unless you tell python to print it (or you trigger an error message).
  • If you want to run the code a second time, you just hit the run button again.
  • Python programs can be saved and stored just like any other file, and can be re-opened if you want to edit or use them again later.

What this means in practice is that while the shell is very useful for quickly checking or testing something, it isn’t so good for larger, more complex programs or anything you want to keep around and use again later.

In the labs, we will often start off doing some testing in the shell so you can see how things work. However, further on in each lab there will be some larger problems that you should write in files so you can edit and change them (and re-run them). As the course goes on, less and less time will be spent in the shell, since it is a bit too limited for what we will be doing. However, don’t forget that it’s there if you need to quickly check something.

The Python help system#

Python has a built-in help function, which gives you access to documentation in the python shell. Try it out on the math module (please note that you have to import the math module beforehand):

In [6]: help(math)
...

Part B - Exercises & problems#

Exercise 1: Using your IDE and simple debugging#

Download and save this small python program in your “lab1” directory: print_brick_wall_1.py.

Open the file print_brick_wall_1.py that you saved earlier in your IDE and attempt to run it. The program has several syntax errors, so it will not run. (Depending on which IDE you are using, you may even see some errors highlighted before you try to run the program.)

Identify and correct the syntax errors so that the program runs. The aim of this simple program is to print a “brick wall” pattern on the screen, like this:

--+-----+---
  |     |
-----+-----+
     |     |
--+-----+---
  |     |
-----+-----+
     |     |
--+-----+---
  |     |
-----+-----+
     |     |

If you cannot find or fix the errors, ask your tutor or another student for help. In case you get stuck, a “cheat sheet” is provided here.

However, even after the syntax errors have been corrected, the program may not print what it should (i.e., exactly the output that is shown above). Modify the program so that you get the correct output. Do not write a whole new program! You should understand how this program works, and fix it so that it does the right thing.

Exercise 2: Exercise 1 revisited with CodeBench#

Now login to CodeBench using your ANU uid and password and select the Lab 1 exercise set. Try the lab1_print_brick_wall exercise. Make sure you SUBMIT your program before you close CodeBench. Ask your tutor for help if you struggle with CodeBench.

Exercise 3: First steps with the robot simulator#

Download a copy of the robot.py module and save it in your lab1 directory.

Before you can do any robot programming, you have to make sure that you can import this module. Remember that python will look for the module in the current working directory (“cwd”). In Spyder, you can change the working directory in the top-right corner of the IDE. (see the introduction to Spyder from earlier if you forgot or don’t know how to do this.) In VSCode, you have to select “File->Open Folder” from the top menu, and then open the lab1 directory. This will automatically set the current working directory to the directory which you just opened.

When you run a python program, the cwd is the directory that the program is in. Thus, an easy way to make import work is to create a new program. A program is stored in a plain text file. Call it first_test.py, and save that too in the lab1 directory.

Note: All your python programs must be saved with a name that ends in .py.

Your program should contain the single statement

import robot

Run the program. After this, you should be able to run robot simulator commands in the shell. Remember that you must start by initialising the simulation:

In [1]: robot.init()

After this, you can test driving the robot around:

In [2]: robot.drive_right()
In [3]: robot.lift_up()
In [4]: robot.gripper_to_open()
In [5]: robot.lift_down()

If you want to see the real robot in action, here is a short video demonstrating it.

Note: The robot simulator may sometimes appear to be frozen (with the window showing “Not responding” or similar). The simulator is not actually frozen in these cases and will continue to respond to commands you execute in the shell. Do not attempt to close it, otherwise it may become actually frozen. When you actually want to close it, if it does not close, simply kill the kernel by pressing the little cross of your shell (see labelled Spyder interface from before).

If you don’t manage to import and initialise the robot simulator, make sure you consult your tutor about it. You will need to be able to do so to be able to attempt homework 1.

Exercise 4: Robot simulator programming problems#

  1. The default simulator setup (what you get when you start the simulator with just robot.init()) has three boxes on the shelf. It also has a limit of one on the height that the robot can reach. (Height zero is on the table; height one is one step above.)

    Write procedures (functions) to make each pair of the boxes swap places, i.e., one to swap the left and middle box, one to swap the middle and right box, and one to swap the left and right boxes (ending with the middle box in the middle). Recall that a function definition is done like this:

    def swap_left_and_middle():
        ...function suite..._
    

    The function suite is a sequence of statements. The extent of the suite is defined by indentation (whitespace before the statement): all statements in the suite must have the same amount of indentation. The standard is 4 spaces or 1 tab.

    Remember to identify the assumptions of your function. Do you assume that the robot is standing in front of the left box or the middle one at the beginning? What is the assumed state of the lift and gripper? Document your assumptions in code comments.

    You will likely find that defining functions in the shell is quite frustrating. Put your function definitions in the file named first_test.py which you created earlier. Then, after you have written each function definition statement, run first_test.py, the same way you ran print_brick_wall_1.py. You should now be able to call the new function from the shell.

  2. Can you identify some manoeuvres that are common to all three problems? Split those off into separate functions. Your code should become more compact and easier to read.

  3. The simulator allows the robot to lift a stack of boxes, not just a single box. However, if we try to do this with the real robot, chances are the stack will fall over. Try to write your functions so that the robot accomplishes each swap without ever lifting more than one box at a time.

Exercise 5: using Python as a calculator. How much an initial amount of money growths in a bank fixed term deposit?#

We place an initial amount of \(A\) dollars in a bank account which offers an interest rate denoted with \(p\), measured in percent per year. After \(n\) years, the final amount to which \(A\) has grown is given by the formula (think why):

\[A\left(1+\frac{p}{100} \right)^n\]

Write a program that computes how much 1000 dollars have grown to after three years with 5 percent interest rate. Use variables to store \(A\), \(p\), and \(n\). Use the CodeBench lab1_Python_as_a_calculator exercise to test your program. Note the result must be stored in a variable named final_amount.

bars search times arrow-up