Week 1: Introduction

Class Recordings

To access recordings, sign in to YouTube with your @swarthmore.edu account.

Monday Wednesday Friday

Monday

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. Andrew Danner, Prof. Kevin Webb, Jeff Knerr

  • Scout Sinclair, Charlie Kazer

  • Lauri Courtenay

  • Ninjas: Rebecca Lin, Sam Yan

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 or Prof. Lila Fontes to take the CS Placement exam to see if CS21 is the proper fit.

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.

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.

What is Computer Science?

Computer science focuses on two primary questions; what can be computed, and how efficiently can computers solve problems? The answers are more nuanced than "everything", and "really fast". At the core of the discipline is algorithms. Algorithms are concise descriptions of how to solve a problem computationally. Algorithms can be implemented in a programming language and interpreted by computer hardware to automate computation. Programming is NOT the core of computer science. Programming is a way to automate and test the creative thought process that resulted in an algorithm. Programming is one tool at the disposal of computer scientists, but it is not the only tool. This course will teach you how to discover, develop, and write clear computational solutions to, often times non-computationally themed, problems. To check your thinking, you will also learn programming, debugging, and testing skills.

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

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.

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.

Writing a full Python program

If update21 worked for you, it should have created an empty welcome.py file in your ~/cs21/inclass/w01-intro directory. Let’s practice some basic Linux commands to:

  1. navigate to the correct folder using cd

  2. list the contents of a folder using ls

  3. open a file for editing using atom

  4. writing, saving, and running our first Python program.

cheese[~]$ cd

cheese[~]$ ls
Desktop/  Documents/   cs21/

cheese[~]$ cd cs21

cheese[cs21]$ ls
inclass/  labs/

cheese[cs21]$ cd inclass/

cheese[inclass]$ ls
w01-intro/

cheese[inclass]$ cd w01-intro/

cheese[w01-intro]$ ls
welcome.py

cheese[w01-intro]$ atom ./

Inside the atom editor, click on the welcome.py to open it for editing. Type in the following content as your first Python program. Use your name instead of K. Webb to take credit for your work.

"""
 My first Python program
 K. Webb
 September 2019
"""

def main():
    print("Welcome to cs21.")

main()

Save the file by pressing CTRL-S, and run the program by typing python3 welcome.py in the terminal. Did it work? If not, what errors did you observe?

Wednesday

Today’s Topics

  • Python syntax and semantics

  • variables and types

  • Basic built-in functions

  • print()

  • input()

  • int(), float(), and str()

  • Intro program design

Elements of a first program

At the end of class on Monday, we wrote our first full python program using the atom editor. You can use any editor you want to modify the file, but to simplify the course discussion, we will be using atom throughout the course. Let’s look at a few of the components of our first program and explore python syntax and semantics. A programming language’s syntax describes the rules for valid placement of symbols and overall program structure. Semantics describes the meaning of the overall program as it relates to the syntax.

"""
 My first python program
 K. Webb
 September 2019
"""

def main():
    print("Welcome to cs21.")

main()

At the top of our program, we see a comment in triple block quotes

"""
text in here is ignored by python
but could be helpful to a human
reading the code
"""

Next we see the definition of our main function. For the first few weeks of the semester, our programs will always have this def main(): syntax. Later in the semester, around week 4, we will write other functions of our own besides main. A function is a reusable piece of code that can potentially accept some input data and produce some output. For now, we simply place what we want our program to do inside the body of the main function by indenting. So far, we only have a single print (print() is a built-in function), but we will soon add more.

The function definition is merely that: a definition. It does not actually run the code inside immediately. To see the output, we need to call the function by specifying the function’s name (without the def or the trailing :) and including any required input in between the parentheses. main does not require any input, so a simple main() as our last line will suffice. Note that this line is not indented or inside the function definition.

Quick practice

  • Try adding a second print() statement inside the main function.

  • Call main() twice by repeating the main() line twice at the end of the program.

  • remember to run your program using python3 welcome.py

  • use cd and ls to navigate to your cs21/inclass/w01-intro folder

Variables and types

We use computer programs to process data, but a program must have a way of storing information and referring to it later. Our primary way of doing this is through the use of variables. A variable is a named container that stores a value of a particular type. In the example below, place is a variable that stores the name of a place. The data type currently stored in place is a string containing a sequence of characters between quotes.

place = "Paris"

The syntax

<var> = <value>

assigns the variable name on the left hand side the value of the expression on the right hand side. It is illegal, or a syntax error to have a constant value on the left and a variable name on the right.

Friday

Variable Types

In addition to the string type (str) , we will initially focus on the integer (int) data type for whole numbers, e.g.,

numStudents = 35
year = 2019
diff = -6

and the floating point (float) data type for decimal data, e.g,

tempF = 34.1
gravity = 9.8

I encourage you to read Chapter 2 of the online text book for a longer discussion on topics regarding

  • what are valid variable names?

  • what are valid operations between strings, ints, and floats?

  • can you use an operator with values of different types, e.g., a float plus a int? What about a string plus a float?

Another good way to experiment is just to open a python shell and try a few one liners.

$ 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.
>>>
>>> 3+2
5
>>> "hello"-7
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unsupported operand type(s) for -: 'str' and 'int'
>>> "hello"+"there"
'hellothere'
>>> 7.16-4
3.16
>>> x=4
>>> y=3
>>> x+y
7
>>> x=y
>>> y=7
>>> x
3
>>> y
7
>>>

Converting between types.

Sometimes you may find it helpful or necessary to change a value of one type to another type. For example the value "7" is a string because it enclosed in quotes. But the contents of the string, the character 7 is also a valid integer. You can convert a value to an integer using the int() built in function. Try these examples in the python shell.

int("7")
int(3.2)
int("3.2")
int(5.7)
int("puppy")
ans="12"
int(ans)

Similarly, you can use float() to convert a value to a float, or str() to convert a value to a string.

Getting input from the user.

One of the most helpful built in functions in the first few weeks of the course will be the input() function. When provided a string prompt as input argument, this function prints the prompt to the screen and waits for a user to type something. When the user presses the Enter key, their response is returned as a value by the input() function as a string. A sample usage might be

"""
A simple greeting program
your name here
September 2019
"""

def main():
  name = input("What is your name?: ")
  print(name)

main()

The program above is pretty terse. Can you modify it so it prints "Hello" followed by the entered name on the same line?

Designing a full program

Suppose we are given the following problem: Have the user enter the current year as a number and the year he or she plans to graduate and print how many more college years he/she has left. We want to design an algorithm that can solve this problem (this one is a bit easy) and then implement and test our solution in python.

Here are some steps a computer scientist might use to solve the problem:

  1. First think about how you would solve the problem. no keyboards, mice, or even writing utensils. Just think.

  2. Write or sketch a solution on paper. Discuss you solution with a friend or neighbor. This solution does not have to be in python. pseudocode is fine.

  3. Write your solution in python using your editor (atom).

  4. save, run, and test your solution. Go back and make changes if needed

The real innovation is in steps 1 and 2. Steps 3 and 4 are sometimes skipped, argued logically/mathematically, or handed off to new hires, grad students, or little brothers. Always do step 4 if you do step 3.

cd
cd cs21/inclass/w01-intro
atom ./
python3 grad.py
Enter the current year: 2019
Enter your graduation year: 2022
You have 3 year(s) until graduation

Python math operators

Mathematical calculations are one of the most common uses of computer programming. Below is a quick summary of python3 math syntax and semantics. I encourage you to try examples in the python interpreter and ask questions about strange cases.

  • +, -, *, and / represent addition, subtraction, multiplication, and division. When you add, subtract, or multiply two integers, you get an integer. When you add, subtract, or multiply two floats, you get a float. Any addition, subtraction, multiplication, or division that involves one float and one integer results in a float answer.

  • Division using '/' in python3 always results in a float, regardless of the input types. Perhaps this makes sense to you. Why wouldn’t 3/2 be 1.5? If this is the case, python3 agrees with you, but in many other programming languages, including C and C++ used in CS31 and C35, the rules for division are a bit different.

  • Sometimes, you might want to divide an integer by another and get an integer instead of a decimal number. The // operator rounds the value down returning an integer, e.g. 3//2 returns 1.

  • Exponents. To raise a number to a power, use the exponential operator **.

  • mod. Python also supports division with remainder using the "mod" operator %. We’ll explain this more when we need it.

    You can also combine many operators in one statement e.g. `2*x+10`, but note you must explicitly include the `*` to multiply. The algebra form `2x+3` is a syntax error.

Quick practice

Take a minute or two, open up a python interpreter window, and play around with math operators. Do they do anything unexpected? Try to combine them in larger expressions. What happens?

$ 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.
>>>
>>> 5+2
7
>>> 5-2
3
>>> 5*2
10
>>> 5/2
2.5
>>> 5//2
2
>>> 25
32
>>> 232
4294967296
>>> 19/5
3.8
>>> 19//5
3
>>> 19%5
4
>>> 3*5 + 4
19
>>> quit()

String Operators

Some math operators can be used with strings:

  • Use + for string concatenation.

  • You can use <str>*<int> to repeat a string multiple times

>>> hw = "hello" + "world!"
>>> print(hw)
helloworld!
>>> "hello"*3
`hellohellohello`

Some other math operators can also be used with strings, but in somewhat more complicated ways. We will explore these operators a little later in the semester. Stay tuned!