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

MCS 275 Spring 2023 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 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.

If you plan to use your own computer to complete MCS 275 work, you need to make sure some things are installed. If you plan to use UIC lab computers to do all of your work, the necessary software should already be installed there (but these steps will verify that).

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://apps.microsoft.com/store/detail/python-310/9PJPW5LDXLZ5)
  • 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: It is probably pre-installed. If not, yse 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 terminals we support for MCS 275 are Windows Terminal (available for free from the Microsoft Store) and Windows Powershell (already installed if you have windows 7+).
  • 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:

python3
python

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 looked like in virtual lab last year:

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. The currently-installed version might be newer.

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. That is, any time you see python or python3 appearing in a command that a worksheet suggests you run, you will need to replace it with your interpreter name.

4. Install Microsoft VS 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:

print("Hello world!")
x = 2**2023
print("2 raised to the power 2023 is equal to",x)

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 VS 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 that button. 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, on my Windows computer, the command to change directory is

cd C:\Users\ddumas\Desktop

while on my Linux laptop it is instead

cd /home/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:

python3 hello.py
python hello.py

If this works, you should see output similar to

Hello world!
2 raised to the power 2023 is equal to 963121833542317369601573845406471251262548645428284526828835768327851746644612875378048462019053502788803516653832734212104068969204751285764221918179043624419894139984279754512017898273159626328827668380262481220865017731267802600915375183179264380651165421367773563947903391466768557089792263481734108493385146063258300495764165365295546337808852673629710735621386935094923561594142327134318905856137785813985574356271679918694447015294481691849341917432346559501502683303082591585074576786963085039546446281095048723669230856548339087909922753762884060607659880382812905450025751549153093939827557015748608

7. Download and run the "python checkup" script

Now that you have your development environment set up, let's run a script that checks to make sure your Python version is as expected (3.8+) and that your process of running scripts in the terminal works. Download this Python script and save it somewhere that you can find in the terminal:

Now, open a terminal, cd to the directory containing checkup.py, and then run that script. After you've changed directory, the command will probably be one of these:

python3 checkup.py
python checkup.py

The script will print a bunch of messages to the terminal, and may give WARNING: or ERROR: messages if something looks wrong. It will also try to display some emoji, shaded rectangles, and colored text, to check if your terminal supports these. Here's what the output looks like on my linux computer: output of checkup.py

If the script shows any warnings or errors, try to fix the issues using the suggestions printed to the terminal

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.

8. 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, and the items in this list are strings. So sys.argv[1] would be a string containing the first word or number on the command line after the name of the script.

Thus, for example, if you run the modified script as

python3 squares.py 3

then it would be expected to produce the output

1
4
9

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

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

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

10. Thinking inside the box

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. The solutions to the worksheet won't include solutions for the bonus problem, but it's still good practice!

11. Digits to word lengths

Consider this process: Start with a positive integer like

2781

Write out each digit as an english word:

two, seven, eight, one

Then replace each word with its number of letters (e.g. "two" has 3 letters, "seven" as 5, etc.):

3 5 5 3

Use these numbers as digits of a new integer

3553

Finally, take the average of the new integer and the old one, and if the result is not an integer, round it down to the nearest integer:

(2781 + 3553) / 2 = 3167 (no rounding needed)

Write a Python function dwl(n) that takes an integer n and returns the integer that results from this process. So, for example we have:

In [3]:
dwl(2781)
Out[3]:
3167

Now, consider what happens when you apply this function over and over again, e.g. start with n, compute dwl(n), then dwl(dwl(n)), then dwl(dwl(dwl(n))), etc., to get a sequence. For 2781 this sequence looks like:

2781, 3167, 4251, 4297, 4321, 4427, 4431, 4442, 4442, 4442, 4442, ...

It continues with 4442 repeating forever.

That's what happened when starting with 2781, but what happens when you do the same thing but start with a different value of n? Does it always seem to end up repeating some number over and over again?