A document from MCS 275 Spring 2022, instructor David Dumas. You can also get the notebook file.

MCS 275 Spring 2022 Worksheet 1

  • Course instructor: David Dumas

Topics

This worksheet covers some initial setup and installation of software, followed by some coding exercises that use material from prerequisite courses.

Instructions

  • This isn't collected or graded.
  • If you took MCS 260 recently, perhaps even with me in Fall 2021, you may have some or all of the necessary tools installed already. That's fine. Be sure to test them out and read through the worksheet carefully to be sure you know what is assumed from now on.

Part I: Setting up a development enviroment

The tasks in this part of the worksheet expand on the Getting Started steps listed in the course web page.

We're starting out online, so you should complete these steps on whatever device you plan to use for writing programs while classes are online. It's best if that is also the device you use for zoom.

In case you need to attend class using a computer where you can't install things, it is possible to use UIC Technology Solutions' Virtual Computer Lab service instead. It provides a Windows 10 computer that you can control through a web browser. However, remote desktop systems like this don't feel as fast, responsive, or natural as using things installed locally. I think you will have a better experience if you can install the software necessary to develop programs on your own device. (For example, many common keyboard shortcuts don't work in the virtual lab.)

When we return to in person instruction, the computers in the labs will have the necessary software installed on them, and you can log in to those computers with your UIC netid and password. I guess that many students will still prefer to work on their own devices (e.g. by bringing a laptop to lab), and we support that.

The steps below guide you through the process of installing the necessary software on your computer. Work on them in today's lab so that the TA can offer assistance if you encounter problems.

1. Install Python

You'll need Python 3, version 3.8 or higher, installed on your computer to develop code for MCS 275. The recommended method of installation depends on your platform:

  • Windows: Install from the Microsoft Store ( https://www.microsoft.com/en-us/p/python-39/9p7qfqmjrfp7 )
  • MacOS: Most likely, Python 3 will be pre-installed; That's the case in all recent versions of MacOS. Check by running the command python3 in a terminal. If it is not already installed, we recommend installing using the packages from python.org: https://www.python.org/downloads/
  • Linux: Use your distribution package manager to find and install the latest version of Python 3, and confirm that it is version 3.8 or higher.

2. Open a terminal

We'll do almost everything in MCS 275 using a text- and keyboard-based interface to your operating system. This takes the form of a terminal. The exact name will depend on your operating system. Test that you can find and open this program on your computer:

  • Windows: The terminal we support for MCS 275 is Windows Powershell. It is installed by default in Windows 7, 8, 10, and 11.
  • MacOS: The terminal application is simply called Terminal, and is installed by default.
  • Linux: The name and method of starting a terminal application depends on the distribution. In Ubuntu, the application menu will contain an entry simply called Terminal.

Once you have a terminal open, check that you can list the files in the current directory with the command

ls

Retrieve the name of the current directory with the command

pwd

You can change to a new directory using the command

cd NEWDIRECTORY

replacing NEWDIRECTORY with the relative path or full path of the directory you want to move to. Typically, you'll want to move to the directory containing your Python programs as a first step in any work session.

If you'd like a more detailed review of how files, paths, and directories work, check out these slides from the first lab in MCS 260:

3. Determine your interpreter name

Now that you know how to start a terminal, you need to determine how to start Python 3 (version 3.8 or later), which you have installed at this point, from within the terminal.

Most likely, one of these commands can be intered into the terminal to start Python 3:

python
python3

It is possible that one of these commands might start a different programming language (Python 2), so it's important to look at what is printed when you run the command and find the one that opens Python 3. Here is what it will look like in the Virtual Lab:

PS C:\windows\system32\WindowsPowerShell\v1.0> python
Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec  7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

Note that this shows Python version 3.9.1.

At the >>> prompt that Python displays, you can type

exit()

to quit Python and go back to the terminal.

The command you use to run Python 3 is your interpreter name. Make note of it, because you'll use it a lot. Since it will be different for each student, the instructions for subsequent tasks require you to know your interpreter name.

4. Install Microsoft Visual Studio Code

You'll need a programming text editor to work on MCS 275 assignments. The one we support directly in the course, and which we ask everyone to install, is

This is a free program available for Windows, MacOS, and Linux.

Install it using the instructions at the link above.

(It is already installed in the Virtual Computer Lab.)

After installing it, figure out how to start VS code, for example by using an icon on the desktop, the start menu, or whatever method your operating system uses to launch applications.

5. Write a short program in VS code

Create a new file in VS code and paste the following text into it:

import sys
print("Hello world!")
print("This program is running under Python " + sys.version)

Save it with a filename hello.py. When you save it, make note of where it ends up. On Windows or MacOS, the default save location may be the Desktop, or the Documents folder.

After you've saved the file, you can get a definitive answer about exactly where the file is stored on your computer as follows: Right-click on the filename tab in the visual studio code window, and select "Copy path" from the menu that pops up. Now, you can paste (Control-V) the filename into another application, such as the terminal. Try this. The filename might look something like

C:\Users\ddumas\Desktop\hello.py

on Windows, or

/home/ddumas/Desktop/hello.py

on Linux. The key point is that it shows the full name of the directory (e.g. C:\Users\ddumas\Desktop\) that contains the file.

6. Run your program in the terminal

VS code may show you a button that can run a Python program; it's a green triangle in the upper right corner. Please don't use it all in this course. If you do, it will work sometimes but fail in confusing ways at other times, because VS code runs your program with the working directory set to a different directory than the one that contains the source code. We'll also write a lot of programs that deal with command line arguments, which can't be run using that button.

Open the terminal and change the working directory to the one containing the file hello.py you created in task 5. The cd command is used to do this. For example, for the instructor's Windows 10 computer, the command to change directory is

cd C:\Users\ddumas\Desktop

In general, the directory will be the initial part of the full path you get from VS code's "Copy path" menu option, all the way up to the last "/" or "\" that appears in the path.

  • Potential "gotcha": If the name of a file or directory contains spaces, you need to put the entire thing in quotation marks to use it with a command in the terminal, e.g.
    cd C:\Users\ddumas\Desktop\MCS260   # ok
    cd C:\Users\ddumas\Desktop\MCS 260  # NOT OK
    cd "C:\Users\ddumas\Desktop\MCS 260" # ok

Confirm that you're in the right directory by asking for a list of files. The terminal command for this is

ls

You should see hello.py in the output of that command.

Once you're in the right directory, run the script hello.py using a command that consists of the interpreter name followed by the filename hello.py. That means it will probably be one of these:

python hello.py
python3 hello.py

If this works, you should see output similar to

Hello world.
This program is running under Python 3.8.5 (default, Jul 28 2020, 12:59:40) 
[GCC 9.3.0]

(This output was from a linux computer, and yours may differ a bit. They key point is the Python version, which is 3.8.5 in the example above.)

Part II: Python Calisthenics

This section gives a series of exercises (of roughly increasing complexity) in which you'll write programs that are based on things you are expected to have seen in a prerequisite course. We'll talk about these in Lectures 2-3 as well, and the first quiz will cover the same kind of review material.

These start very easy and build up.

7. Squares

Create a simple program squares.py that prints the squares of the first 10 positive integers, so its output should look like

1
4
9
...
100

Then, add a feature to this program where it accepts an optional command line argument which is the largest integer whose square should be printed (while 10 remains the default if no argument is given). Recall that command line arguments appear in the list sys.argv which is accessible after you import the sys module.

Thus, for example, your modified program would print just

1
4
9

if run with the command

python squares.py 3

8. Getting to know our coding standards

Now that you've written a simple program from scratch, and have a full Python setup working, it's time to get acquainted with some code style rules.

All code you submit for credit needs to follow the rules described in the

Read that document now. Take your time, and ask the TA for help if you are unsure about any part of it.

Then, take the program below (which works!) and fix it so that it does the same thing but complies with the MCS 275 rules. (Note: The rules say you need to add a declaration stating that the program is your own work, or that it is derived solely from a template provided by the instructor. That's because all graded work in MCS 275 is done individually. Since this is a worksheet, collaboration is allowed, and in this case your declaration should instead list your collaborators.)

# I am a program that doesn't follow MCS 275 coding guidelines
# Please fix me.
def thing(x):
 return "{} is one greater than {}".format(x,x-1)

def thing2(x):
  return "{} is one less than {}".format(x,x+1)

s = str(input("Please enter your name"))
print("Hello",s,", this is a sample Python program.")

ss = list(range(5))
sss = [ x+5 for x in ss ]
ssss = [ 10*x for x in sss ]

for i in range(len(ssss)):
      sssss = 'Some things that are true:\n' + thing(ssss[i]) + "\n" + thing2(ssss[i]) + '\n\n'
      print(sssss)

8. First two digits of squares

Let's write a slightly more complex program now that uses more Python concepts.

Consider the squares of all the 4-digit positive integers (the numbers 1000, 1001, ..., 9999).

What pairs of digits can appear as the first two digits in one of these numbers? For example, since 2187*2187=4782969, we know that 47 is one of the possibilites. What are the others? Do you get all two-digit combinations this way?

Write a program that answers this question, and which also determines how many times each two-digit combination arises in the list of squares of 1000...9999.

Have it print the result in a format like this:

There are NN two-digits combinations that appear as the first two digits of squares of the integers from 1000 to 9999.  Here is a table of them, with the number of times each one occurs:

Digits  Number of times
-----------------------
10      XXX
11      YYY
...

Here is the recommended structure for your program:

  • Make a dictionary that has all the two-character strings corresponding to pairs of digits as keys, and the integer 0 as each value.

  • Use a for loop to iterate over integers from 1000 to 9999. In the body of the loop, square the integer, convert it to a string, and extract the first two characters into a string. Then use this as a key in the dictionary, and increment the associated value.

(You are welcome---even encouraged---to think about a purely theoretical solution to this problem, but I also want you to get the coding practice that will come from exhaustively enumerating the squares and checking the digits.)

9. Box in a text file

One of the nice things about Python is that strings can contain any Unicode character (as opposed to strings in some other programming languages where the set of available characters is much more limited).

Some Unicode characters are made for drawing "text graphics" boxes, like this:

╔══════════╗ 
║  Look,   ║
║  a box!  ║
╚══════════╝

The box drawing characters used above are:

  • \u2550 or
  • \u2551 or
  • \u2554 or
  • \u2557 or
  • \u255a or
  • \u255d or

Write a program box.py that prints a unicode text box of specified width and height to an output text file. It should expect three command line arguments. The first, sys.argv[1], will be the the output filename. The other arguments are integers giving the width and height of the box.

The program should open the output file for writing, and then write lines of text to that file that create the desired box.

So, for example, the command

python box.py boxtest1.txt 3 4

should result in a file boxtest1.txt being created that contains the following text, exactly:

╔═╗
║ ║
║ ║
╚═╝

(This box has a width of 3 characters and a height of 4 lines). Similarly, the command

python box.py boxtest2.txt 12 2

should result in a file boxtest2.txt being created that contains the following text, exactly:

╔══════════╗
╚══════════╝

Recommended structure of your program:

There are three different lines in the output file: The top of the box, the line that repeats some number of times to make the middle of the box, and the bottom of the box.

I suggest you generate these three lines and store them in strings, and then use a loop to print the middle-of-box line the right number of times.

To generate these strings, you can use the fact that multiplication of a string by an integer will repeat the string a certain number of times. For example, "foo"*3 evaluates to "foofoofoo".

It would be a good idea to put the part of the program that writes the boxto a file into a function which accepts a file object as its only argument. That function should expect the file to already be opened for writing.

Then, the main program would parse the command line arguments, open the output file, and call the function that saves the box.

Bonus round

Work on this more challenging exercise if you finish the rest of the worksheet before discussion ends.

10. Parse grade statements

Write a program that reads a text file specified as a command line argument which contains statements written in the following format

Student ddumas scored 1 out of 23 on CoordinationTest.
Student ncomaneci scored 23 out of 23 on CoordinationTest.
Student enoether scored 11 out of 10 on AlgebraQuiz.

That is, the lines are all of the form

Student NAME scored POINTS out of MAXPOINTS on NAME_OF_ASSESSMENT.

where the all-caps items are placeholders that in the actual lines will be replaced by an integer (for POINTS or MAXPOINTS) or a string with no spaces (for NAME or NAME_OF_ASSESSMENT).

The program should compute the percentage score for each student on each assessment and store them in a dictionary (with the name of the assessment as a key). Then, it should print the scores for each assessment in increasing order, as percentages.

For example, the input above would give output:

Scores on CoordinationTest:
ddumas 4.3%
ncomaneci 100.0%

Scores on AlgebraQuiz:
enoether 110.0%

11. Robust grade statement parser

Modify the solution to problem 10 to be tolerant of lines in the input text file that don't follow the specified format. In particular, it should be able to determine if a given line is in the correct format.

If a malformed line is found, it should print an error message and proceed.

This requires several stages of error checking; for example, required parts of the input line might be missing, or the integer point values might be invalid integer literals, or the total number of points on the assignment might be zero (preventing the computation of a percentage).