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

Worksheet 1

MCS 275 Spring 2021 - David Dumas

Instructions:

  • Future worksheets will focus exclusively on coding problems that give you practice with recent lecture material.
  • This first worksheet is a bit different, because it also guides you through some basic setup tasks (software installation etc.) you'll need to finish in order to work on course material.
  • You've already completed a course that involves Python programming, but for some of you it may have been a while ago, or it may have even used Python 2 (an older language we don't discuss in this course). For this reason, we assume nothing about your setup and lay out every aspect of the setup you may need to do. You may have already done most or all of this, especially if you took MCS 260 in Fall 2020. But read through everything closely, because you should know what we assume you can do from now on.
  • The second part of this worksheet contains coding exercises to get your existing Python skills warmed up. We'll start learning new stuff in week 2.

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.

Almost any computer with a web browser can access an on-campus Windows 10 computer that has all the necessary software installed, through UIC Technology Solutions' Virtual Computer Lab service.

However, 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.)

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

1. Install Python

You'll need Python 3, version 3.6 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-38/9mssztt1n39l )
  • MacOS: In the latest version of MacOS, Python 3 will be pre-installed; check by running the command python3 in a terminal. If it is not already installed, we recommend installing using homebrew; here are sample instructions: https://wsvincent.com/install-python3-mac/
  • Linux: Use your distribution package manager to find and install the latest version of Python 3, and confirm that it is version 3.6 or newer.

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, and 10.
  • 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

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.6 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 has a button that can run a Python program. We don't recommend using it at all in this course, as it is essential for you to learn how to navigate directories and how to launch Python scripts in the terminal. 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.

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.

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 coding standards document on the course web page. These rules enforce good coding practices and ensure your programs are readable to both humans and computers.

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.)

# 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)

L = list(range(5))
LL = [ x+5 for x in L ]
L3 = [ 10*x for x in LL ]

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

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. Chess board text file

Write a program board.py that expects two command line arguments. The first, sys.argv[1], will be the the output filename. The second will be a positive integer which we'll call N.

The program should open the output file for writing, and then write lines of text to that file that create an 8x8 chess board. The white squares should be represented by NxN blocks of the character #, and the black squares should be filled with spaces.

So, for example, the command

python board.py board1.txt 1

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

# # # # 
 # # # #
# # # # 
 # # # #
# # # # 
 # # # #
# # # # 
 # # # #

while the command

python board.py board2.txt 2

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

##  ##  ##  ##  
##  ##  ##  ##  
  ##  ##  ##  ##
  ##  ##  ##  ##
##  ##  ##  ##  
##  ##  ##  ##  
  ##  ##  ##  ##
  ##  ##  ##  ##
##  ##  ##  ##  
##  ##  ##  ##  
  ##  ##  ##  ##
  ##  ##  ##  ##
##  ##  ##  ##  
##  ##  ##  ##  
  ##  ##  ##  ##
  ##  ##  ##  ##

Recommended structure of your program:

There are only two different lines of text that appear in the file, but each appears many times.

First, generate both of the lines of text you'll need, then use a loop to print them the right number of times and in the right order.

To generate the line, 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".

Put the part of the program that writes the chess board to 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 board.

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).