Week 1: Introduction

Getting Setup

Introduction to CS21

Welcome to CS21. This course is designed to have a mix of lecture and hands on in class lab exercises. This page will review some of the tools we will use during the labs and help you get set up with the system in the CS department.

Staff Introductions

  • Prof. Lisa Meedan, Prof. Aline Normoyle (me), Jeff Knerr

  • Lab instructors: Scout Sinclair, Charlie Kazer, me

  • Coordinator: Lauri Courtenay

  • Class Ninjas: Riley Thompson and Otis Peterson

Who should take this course?

This course is designed for students with little or no programming experience. If you have taken a computer science course previously or taught yourself basic programming skill in any language, even if it wasn’t python, you may find this course too slow. Students with prior programming experience are encouraged to contact Prof. Andrew Danner to take the CS Placement exam to see if CS21 is the proper fit.

Creating accounts

The CS machines in the Sci 256, Sci 240, the overflow lab (Sci 238) and Clothier Lab are on a separate network than the machines managed by ITS. You need a separate account with a separate password to access these machines. If you do not have an account, please see Jeff Knerr to get a user agreement form.

The first time you login, you will likely want to change your randomly assigned password. Open a terminal window by clicking the terminal icon terminal on the bottom toolbar. At the $ prompt, type passwd, press enter and follow the instructions. Note that when you are typing your old or new password, nothing will be displayed to the screen (no `*’s and certainly not your password). The program will not allow you to pick a password that it thinks is too short or too easy to guess. If you ever forget your password, you can reset it by going to CS password reset page.

Your student ID has an RFID tag that can allow you access to the building and the labs after hours. This year, you should have automatically have access to the lab space by enrolling in the course. If you are having trouble with the card readers, please let me know.

Adding the course, switching sections

If you are looking to add this course or switch to a different section, please talk to Lauri Courtenay before you leave class today. Lauri manages the waitlist for all sections. We will try to provide you an answer to your registration related questions as soon as possible. If you are already on the waitlist, please sign in on form provided in class.

Course Webpage

The Course Website is updated regularly and contains recent course announcements, links to inclass exercises, lab assignments, quiz topics, and other less dynamic course information including office hours, ninja sessions, and python tips. Bookmark the website in firefox or chrome and refer to it regularly. All sections have the same quiz dates and lab assignments.

Piazza

This semester, we are using Piazza to manage course discussions and announcements. If you are registered for the course, you should get an email soon about registering for Piazza. You are encouraged to ask questions on the Piazza forums instead of sending us emails directly. Please review the Piazza guidelines on how to write a good Piazza post.

Labs

This course has a mandatory lab section. Attendance is required unless you have completed and submitted the lab for the week prior to the start of lab. Labs started Tuesday and Lab 00 is due Saturday night.

update21 and handin21

Eventually, we will be saving our python code in files. You will also be using two commands regularly through the course to get and submit files for the course: update21 and handin21. Try to run them now at the linux prompt. You should run update21 before starting each lab assignment and handin21 to turn in lab assignments. You can run them as often as you like. update21 will not clobber files you modify after running update21 and handin21 can submit the same lab multiple times. Each handin submission is stored separately, but only most recent copy submitted prior to the deadline will be graded. You may continue to submit after the deadline, but these submissions will be ignored.

If update21 or handin21 does not work for you or it says you are not allowed to run these programs, email me. It is usually my fault, not yours. I may need to add you to the class roster, change handin or change permissions on a directory.

Computer Science, algorithms, and programming

Computer science focuses on two primary questions:

  • what can be computed, and

  • how efficiently can computers solve problems?

In other words, computer science is the study of algorithms. Computer science research can be thought of in terms of two broad categories:

  • How to make computers run better (faster, less power, less memory; and

  • How to make make computers do cool things (send emails, play games, etc).

Algorithms are a sequence of steps to solve a class of problems. Real life examples of algorithms include

  • recipes

  • IKEA instructions

  • travel directions

  • sheet music

  • choreography

  • can you think of more?

The examples above work well for humans. Humans can handle ambiguity. Humans understand context. Computers unfortunately cannot. Thus, humans have developed programming languages to communicate algorithms to the computer. Programming languages must be

  • unambiguous, so the computer cannot misunderstand a command, while being

  • expressive, so the computer can perform a wide variety of tasks.

Algorithms are programming-language agnostic. In other words, the same algorithm could be implemented using many different programming languages. In this course, we will use Python3. Many languages share the same concepts for expressing ideas. We will learn the most useful and important of these concepts over the course of the semester.

UNIX command line basics

We will also be using Xubuntu linux for our operating system. This is a helpful reference

It is important that you are able to navigate between directories using the terminal. Directories are organized in a hierachy. The directories on our linux machines look like

directories

When you open a terminal, you start in your home directory. In the above picture, we show the directory structure for Harry Potter’s account. His username is hpotter1. The absolute path (aka full path) to his directory is /home/hpotter1. His cs21 directory is subdirectory of his home directory. The full path is /home/hpotter1/cs21.

  • Classwork will be located in /home/<username>/cs21/inclass

  • Lab comeworks will be located in /home/<username>/cs21/labs

  • Extra practice is located in /home/<username>/cs21/practice. Do extra practice if you finish in-class exercises early!

The example below uses cd, ls, and pwd to navigate to the inclass directory. Try to picture the directory hierachy while using the terminal!

pimento[~]$
pimento[~]$ *ls*
Assembly-CSharp.csproj  Desktop/    Library/  Packages/     anas.sln  hide/
Assets/        Documents/  Logs/     ProjectSettings/ cs21/
pimento[~]$ *pwd*
/home/anas
pimento[~]$ *cd cs21*
pimento[cs21]$ *pwd*
/home/anas/cs21
pimento[cs21]$ *ls*
inclass/  labs/  practice/
pimento[cs21]$ *cd inclass/*
pimento[inclass]$ *pwd*
/home/anas/cs21/inclass
pimento[inclass]$ *ls*
w01/
pimento[inclass]$ *cd w01*
pimento[w01]$ *ls*
add.py   market.py  program.py  types.py
pimento[w01]$ *cd ..*
pimento[inclass]$ *ls*
w01/
pimento[inclass]$ *cd ..*
pimento[cs21]$ *ls*
inclass/  labs/  practice/
pimento[cs21]$ *cd ~*
pimento[~]$ *cd cs21*
pimento[cs21]$ *cd*
pimento[~]$ *pwd*
/home/anas

Important directory nicknames

  • . current directory

  • .. parent directory

  • ~ home directory

What is python?

Python is the programming language we will use to implement and test our algorithms. It is relatively easy to learn, even for people not in computer science or related fields. It is free to download and it runs on many platforms including linux, Mac OSX, and Windows. It’s pretty fun to learn and we can get started right away!

Python shell vs linux shell

  • We run UNIX commands using the linux shell

  • We execute Python3 statements using the Python3 shell

  • We run Python3 programs (stored in files with the .py extension) using the linux shell

In this course (and many other CS courses) we will be using the terminal window frequently. You can open a terminal window by clicking the terminal icon terminal on the toolbar on the bottom of the screen. The terminal window is sometimes called the console window, an xterm, a shell, a command shell, or my personal favorite, the black screen (if you adjust the preferences, your black screen may be a different color). These are all names for pretty much the same thing. Typing certain commands in the terminal tells the computer to perform certain actions. We will examine a few commands over the next few weeks, but there are literally thousands of possible commands you can run from the terminal. We will not cover all of them.

By default, the terminal starts in a linux shell with a prompt that looks (by default), something like

cumin[~]$

The name cumin is the hostname or name of the computer, and is likely different for each student. This linux prompt indicates that the terminal is ready to accept linux commands. Lab 00 asks you to explore some of these linux commands. We’ll be practicing the commands in class and lab throughout the semester.

The python3 command tells linux to start the python shell. This program changes the terminal prompt to

>>>

and now the terminal is ready to accept python commands

cumin[~]$ python3
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print("welcome to comp. sci.")
welcome to comp. sci.

>>> 2+2
4

>>> 4*5.
20.0

>>>quit()
cumin[~]$

In this mode, python commands are interpreted one line at a time and the result is printed to the screen. Typing quit() in the python shell quits the python interpreter and returns the user to the linux shell. Learn to recognize what program is running by inspecting the prompt.

To exit Python3’s shell:

  • Type exit()

  • Type Ctrl-d

Basic programming elements

Basic data types

  • strings (str): for text, exs "hello" or 'hello'

  • floats (float): real numbersi, exs 1.75, -0.000004

  • integers (int): 45, 0, -3

Python let’s us check the type with type() command.

Basic commands

  • printing: outputs to console, exs. print("hello")

  • arithmetic: perform calculations, exs. +, , -, /, //, * (do not use the bitwise operator ^)

  • input: ask the user for data , ex. input("Type some text: ")

Demo

We can experiment with Python3 using the Python3 shell

pimento[w01]$ python3
Python 3.6.9 (default, Nov  7 2019, 10:44:02)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print("hello")
hello
>>> 12*3
36
>>> 4
4
>>> type(4)
<class 'int'>
>>> type("hello")
<class 'str'>
>>> type(3.56)
<class 'float'>
>>> 12*3.0
36.0
>>> type(12*3.0)
<class 'float'>
>>> 12/5
2.4
>>> 12//5
2
>>> type(12/5)
<class 'float'>
>>> type(12//5)
<class 'int'>
>>> 2**8
256

Watch out! The ^ is a bitwise operator. Don’t confuse it with exponentiation! You will learn about bitwise operations in future programming courses.

>>> 2^8
10

The arithmetic operators can work on both numbers and strings (with some caveats).

>>> input("Enter a value: ")
Enter a value: 3
'3'
>>> "hi"*3
'hihihi'
>>> "hi"/3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'str' and 'int'
>>> "hi"+" there"
'hi there'
>>> "hi"+3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be str, not int
>>> "hi"+"3"
'hi3'
>>> type("3")
<class 'str'>
>>> type(3)
<class 'int'>
>>> type(3.0)
<class 'float'>
>>>

Exercise

Try the following:

  • Print your name

  • Compute 10<sup>3</sup>

  • Ask the user for a phrase

pimento[w01]$ python3
Python 3.6.9 (default, Nov  7 2019, 10:44:02)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Aline N")
Aline N
>>> print("Aline N)
  File "<stdin>", line 1
    print("Aline N)
                  ^
SyntaxError: EOL while scanning string literal
>>> print("Aline N
  File "<stdin>", line 1
    print("Aline N
                 ^
SyntaxError: EOL while scanning string literal
>>> print("Aline N"
...
...
... )
Aline N
>>> 10**3
1000
>>> 10*10*10
1000
>>> input("Enter a phrase: ")
Enter a phrase: YOLO
'YOLO'
>>>
All quotes and parantheses must appear in matched pairs!

Structure of a program

Programs you write or this class should contain

  • A header comment

  • main function

program.py

When you run this program, Python3 executes each line as it reads it

$ *python3 program.py*
Hello World
  • Line 1: Python3 encounters the """. This indicates a comment. Python3 will ignore the text between the starting and ending """

  • Line 16: Python3 encounters def main():. This is a function definition. We will learn about functions in detail soon. For now, know that all the statements of our program will belong to the function main(). All statements that belong to main() have the same indent.

  • Line 24: Python3 encounters main(). This line executes the function we defined on line 16.

Variables

So far we have been working only with values and basic commands. Values are data, such as integers, floats, and strings.

  • Variables allow us to store values with a helpful name

  • You can visualize variables as containers with a label. We store values inside them.

  • Variables can also be thought of similarly to variables in matched

Examples:

height = 60 # store height in inches
greeting = "hello" # store name

We assign values to variables using the = symbol. This process is called assignment. We should try to choose variable names which help us remember what a value represents. There are restrictions to the names we can choose for a variable

  • case sensitive

  • cannot start with a number

  • cannot contain special characters, such as !@#$%^&*()

  • cannot be a reserved word, such as def, class, if

Demo

pimento[w01]$ python3
Python 3.6.9 (default, Nov  7 2019, 10:44:02)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> height = 60
>>> print(height)
60
>>> height/12
5.0
>>> greeting = "hello"
>>> print(greeting)
hello
>>> greeting = "howdy"
>>> print(greeting)
howdy
>>> oldgreeting = greeting
>>> print(oldgreeting)
howdy
>>> greeting = input("Enter a greeting: ")
Enter a greeting: hola
>>> print(greeting)
hola
>>> 1greeting = "hi"
  File "<stdin>", line 1
    1greeting = "hi"
            ^
SyntaxError: invalid syntax
>>> greeting1 = "hi"
>>> print(greeting)
hola
>>> print(greeting1)
hi
>>> greeting_message = "hi"
>>> Greet%^
  File "<stdin>", line 1
    Greet%^
          ^
SyntaxError: invalid syntax
>>> class = "cs21"
  File "<stdin>", line 1
    class = "cs21"
          ^
SyntaxError: invalid syntax
>>> type(greeting)
<class 'str'>
>>> type(height)
<class 'int'>
>>> num1 = input(
... "Enter a number: ")
Enter a number: 2
>>> num1 = input("Enter a number: ")
Enter a number: 2
>>> type(num1)
<class 'str'>
>>> num1 = int(input("Enter a number: "))
Enter a number: 2
>>> print(num1)
2
>>> type(num1)
<class 'int'>
>>>

Exercise

Write a program that asks the user for two numbers and outputs their total

Step 1: Write an algorithm in terms of basic commands

Our program needs to perform the following steps

  • Ask the user for the first number. Store the result in a variable

  • Ask the user for the second number. Store the result in a variable

  • Compute the sum of the two numbers

  • Print the result

Step 2: Translate the algorithm into Python3 code

add.py
pimento[w01]$ python3 add.py
Enter the first number: -5
Enter the second number: 5
The sum is 0
pimento[w01]$ python3 add.py
Enter the first number: 0
Enter the second number: 0
The sum is 0
pimento[w01]$ python3 add.py
Enter the first number: 1
Enter the second number: 1
The sum is 2

Different types of program errors

  • Syntax errors: Typos prevent Python3 from parsing (e..g reading) the file

  • Runtime errors: Python3 encounters an error only when it executes a command. These bugs can be found by testing your program with different inputs.

  • Semantic errors/Logical errors: Your program runs without errors but produces the wrong output. In other words, the computer is doing what you say and not what you want. These bugs can be tricky to find.

Can you fix the syntax error?

pimento[w01]$ python3 add.py
  File "add.py", line 9
    num1 = int(input("Enter the first number": ))
                                             ^
SyntaxError: invalid syntax
add.py.syntax

Can you fix the runtime error?

pimento[w01]$ python3 add.py
Enter the first number: 3.4
Traceback (most recent call last):
  File "add.py", line 19, in <module>
    main()
  File "add.py", line 9, in main
    num1 = int(input("Enter the first number: " ))
ValueError: invalid literal for int() with base 10: '3.4'
add.py

Can you fix the logical error?

pimento[w01]$ python3 add.py
Enter the first number: 5
Enter the second number: -5
The sum is 10
pimento[w01]$ python3 add.py
Enter the first number: -5
Enter the second number: 5
The sum is -10
add.py.error2

can you fix the logical error?

pimento[w01]$ python3 add.py
Enter the first number: 5
Enter the second number: 3
The sum is 53
add.py.error1

Credits

Notes written by to Prof. Andy Danner and Aline Normoyle, 2019-2020