Lab 01: Linux Terminal & Python

Credits

The lab content is the result of collective work of CSCI 204 instructors. The Terminus game used in this lab was first introduced by Professor Dancy.

Lab objectives

Introduction

We will exercise two subjects in this lab. One is to learn a few more Linux commands, the other is to learn a few new Python commands and refresh what you already know.

First we learn a few more Linux commands.

Linux and the Shell/Terminal

Although Linux uses a window manager to give it a GUI interface similar to Windows, a lot of functionality is best available via a shell window with a command line, where one can direct actions using a text command. This way of communication is much more efficient and effective. Imagine how many clicks you'd have to use to get to a file that is, say, 5 levels below a directory structure. Using shell command, you can do it in one shot.

You will need to use shell commands for this course and many future computer science courses you take.

If you have learned it elsewhere then you may know this material already. You still need to do the lab and turn in the answers. You may also want to help others who are new to the command line environment.

Part 1: Learning terminal through a game

We are going to use the Terminus game to learn some shell commands. Here is the initial screen of the game which you will load to learn and practice Linux commands.

Terminus home image

The game environment will limit us somewhat in that we won't be able to run the full gambit of shell commands. (At least within the scope of what you're required to do for this lab)
Below are a few additional commands that you will not be able to use in the game, but are nonetheless very handy for command line work, especially for manipulating files & directories:

  1. Creating the hand-in file

    • Begin editing a hand-in file for today’s lab using gedit by opening a terminal and typing gedit lab01.txt& (the & is important here, it will allow you to continue to typing commands into the terminal) at your prompt and hitting the Enter key. The above command means to create a text file named lab01.txt using the gedit text editor. Put your real name (not your user id), the lab number (Lab01), and your lab section (e.g., CSCI 204L61) at the top of the file. The following is a sample text and the screen shot of the above action.

    gedit should be open with the terminal ready to accept another command
    • Number the problems you will answer in this file using the following format:
      • Problem 1 answers: here goes my answer to the problem ...
  2. Throughout the exercises, feel free to use the copy-and-paste feature that is available at the Linux command prompt.

  3. Opening a terminal game, you will answer questions in lab01.txt by playing the game and reporting what happens. The problems are numbered and marked with bold face in the following sections.

    • We are going to play a game called terminus. (Credits: This was first introduced by Prof. Dancy for CSCI 204.)
    • Open a web browser and navigate to the Bucknell hosted version of the Terminus game : https://eg.bucknell.edu/~csci204/common-files/labs-common/Terminus/
    • Read the welcome message at the top of the screen and use the noted commands to explore your environment.
    • Hint - You may want to read something before you actually move to a new location.

Problem 1: What does the pwd command do? What is the output when you run the pwd command (without running any other command from the beginning of terminus)?

  1. Advancing throughout the game
    • Time to move a bit through the game!
    • If you haven't entered any commands in yet, let's start by looking at our "surroundings" using the following command.

> ls

Problem 2: (a) What is the command you used to enter the WesternForest? (answer in the form of command-name args); (b) What is the message you see on the screen after navigating to the WesternForest?



Welcome to the WesternForest!



Problem 3: What happens when you enter the command cd ~? (What location do you end up in?)





Problem 4: (a) How do you talk to the HurryingStudent? (answer in the form of commandname args); (b) What happens after you speak to the student? (You can just copy+paste for your answer here)



Welcome to the WesternForest!



Problem 5: (a) What new spell did you learn from the professor? (b) What does it do?



Problem 6: What command did you have to run to complete the last step (moving the PracticeDummy2 object to the Box? (answer in the form of commandname args)


Though moving objects is a bit more magical in the terminus environment, the limitation of what you can move (and where you can move that object) is dependent upon several things, perhaps most importantly the permissions of the object & the directory to which you are moving that object. You can see the permissions of files/directories in a directory using the the -l option for the ls command, that is ls -l. This will work in a normal shell, but not in the terminus environment.



Problem 7: How would we look in the Box? (answer in the form of commandname args)

This can be a nice command, it allows you to save the trouble of moving to directories...you can just see what's inside another directory without leaving your current directory

I'm a Pony!

Problem 8: How do we get to the Portal after inspecting the Boulder? (give all the commands you must run with each command in the form of commandname args)



Ok, we've learned a few simple things about moving about in a shell-like environment. We're going to stop here for this part of the lab. Nonetheless, the Terminus world has much more to offer. Feel free to keep on going in the game and exploring :-). Why not see what happens when you enter the Portal?

Welcome to the Town Square!

Part 2: Python warm-up

In this part of the lab, you refresh your knowledge of Python and learn some new useful commands. The Python Manual should prove useful (many times more so than Google) for looking-up information on various concepts.

Lists

Python has a built-in list data type. A Python list is a mutable object with fields for length, capacity, and an array (a contiguous set of memory). It allows a special quick and easy access using [] (brackets, very common in programming languages). Mutable means it can be revised. Try the following commands for lists and try to figure what they are doing. Note that some of the following exercises are just asking you to try out. Others with a problem number will ask you try out and write answers to your lab01.txt. You may use whatever Python tools you feel comfortable to accomplish the tasks.

a)

list = [1, 2, 3, 4, 5, 6, 7, 8, 9] print(len(list))

b)

list = [2, 4, 6, 8] list2 = [10, 12, 14] list3 = list + list2

c)

list = [1,2,3,4,5,6,7,8,9] slice = list[2:5]

d)

list = [1,2,3] list.append(4)

e)

list1 = [1,2,3] list2 = [4,5,6] list1.extend(list2)

f)

list = [1,2,3] list.insert(2,50)

g)

list = [1,2,3] list.pop(1)



Problem 9: What would be returned by pop with no parameter?



Problem 10: In one or two lines explain the difference between the append and extend functions for lists



Strings

Strings allow [] access similar to lists for reading but strings are immutable, which means they cannot be changed (we can however create a new string when we want changes).

Try the following commands for strings and figure what they are doing:

a)

"hi" + "ya" "hi"*3 len("hihihi")

b)

word = "Hello, world!" word[0:3]

c)

word.capitalize() word.lower() word.upper()

d)

word.isalpha() word.isdigit()

e)

sentence = "hi there, she said." sentence.count("hi") sentence.find("hi") sentence.split()



Problem 11: What would be returned by find with no parameter (for example, word.find())?



Problem 12: In one or two lines, explain what the string methods isalpha and isdigit will return and under what conditions.



Dictionary

Python has a built-in list dictionary type. In the same way that a Python List associates indices with values, a Python dictionary associates names with values. The names are referred to as keys. It also allows quick and easy access using []. Like a Python List, it is mutable (i.e., it can be edited).

Try the following dictionary commands and try to figure what they are doing:

a)

ages = {"Alice":20, "Bob":18, "Cecil":19} print(ages) # look at the order of names

b)

favoriteColors = {} favoriteColors["Alice"] = "red" color = favoriteColors["Alice"] ages["Alice"] = ages["Alice"] + 1 ages["Dan"] = 20

c)

for person in ages: print(ages[person])

d)

if ("alice" in ages): print("Found Alice")

e)

len(ages)

f)

del (ages["Alice"])

g)

del (ages)



Problem 13: What is the difference between del when a key is specified, and del when no key is specified (see f and g above)?



Problem 14: Is the variable person in for person in ages assigned the keys or their associated values for the entries in the ages dictionary (see a and c above)?



Problem 15: Is the variable person in the following code assigned the indices or the values of the entries in the ages list?

ages = [20, 18, 19] for person in ages: print(person)

Multi-dimensional Lists

Python allows multi-dimensional lists. A two-dimensional list might be used to hold image data. A three-dimensional list could hold multiple images and form a movie. This can be expanded to any number of dimensions. Here is how to store the value True into an element in a nine-dimensional list (you have to have to have created such a list first).

nineD[3][5][2][7][1][8][3][9][4] = True

As mentioned, you need to create such a list before being able to assign a value to a specific index within the 9D list. Try the following commands for lists and try to figure what they are doing:

a)

two_d = [] for a in range(4): two_d.append([]) for b in range(5): two_d[a].append(0)

b)

two_d[2][3] = 5

c)

for a in two_d: print(a)



Problem 16: Does this 2D list have 4 rows or 4 columns?



Problem 17: In two_d[2][3] is the 2 the column or the row?



Problem 18: In the for loop in example c), are the values iterating over columns or rows?



Python Functions

Tasks are best completed in units of work. That is, we want to divide a big task into a number of small ones and tackle these small ones one at a time. For example, given a file containing a massive set of numbers in random order, your tasks are a) to count the numbers; b) to sort the numbers in ascending order; c) to find maximum and minimum; and finally d) to compute the average. While you can solve this problem in many different ways, it probably makes sense to divide the task into a few smaller ones such as reading the file, sorting the numbers, and computing the average while finding the maximum and minimum at the same time. Each of the small tasks should be defined as a function.

In addition, many computing tasks are repeatedly used by programmers, for example, finding the index of a particular symbol in a string. It makes sense to have a function does this task, rather than everyone write their own code to solve this problem.

For these two reasons, functions are an important element in any programming language, including Python. Try out the following code and answer the questions that follow.

a)

def compute(a, b): '''both a and b are non-negative integers''' x = 1 for i in range(b): x *= a return x print(compute(3, 4))

b)

def fun(a): '''a is a non-negative integer''' if a > 10: return fun(a - 2) + 1 elif a <= 0: return 2 else: return fun(a - 1) * 2 + 1 print(fun(12)) print(fun(8))

Problem 19: Briefly describe what the function in a) does. What is printed on the screen after the program in a) is executed?



Problem 20: What would we call this type of function in b) that calls itself within the body of the function? What are printed on the screen after the program in b) is executed?



Part 3: Handing in your lab

Submit your lab!

Submit a copy of lab01.txt on Moodle.