## Monday

### Some Logistics for the remote week:

#### Adding the course, switching sections

If you are looking to add this course and are not on the waitlit, or to switch to a different section, email Lauri Courtenay before 1pm 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, we will record your attendence thiw week in lab and lecture.

#### Remote Lab Meetings

For remote lab meetings this week, connect to your lab instructor’s zoom meeting during your scheduled lab meeting time (links were emailed to you and are also posted to EdStem).

In addition to zoom, this week we will use the CS21 lab google doc for lab Q&A during the lab sessions.

• You can post short questions here (note the different categories), that we will anwer. Look for responses to similar questions first.

• You can also add yourself to the Help Wait Queue for longer questions and individual help from a CS21 staff member of ninja. Adding yourself to the waitqueue is also a way to signal to us that you need to be added to a zoom breakout session.

Once we are back in-person, weekly lab sections and ninja sessions will be held in a CS lab. We will use a similar Help Wait Queue model on the board.

#### Remote Ninja Sessions

• For remote ninja sessions this week, Lauri will email out instructions.

### A Synchronous Re-introduction to CS21

Last week you read through the syllabus (CS21 webpage) to learn about CS21, and some of the course structure and design and, and you worked on Lab 0 to learn some of the tools that you will use this semester.

Today, we are going to revisit some the course content, resources, talk about what CS21 is about (and what it is not about) and start writing our first Python program!

#### Course Webpage

• A living syllabus: all course policies, all reading and lab assignments, announcements, staff info, class meeting info.

• Resources

• Tips for succeeding in CS21

• CS21 Ninjas and ninja sessions

• Office hours

• EdStem

• Review a few policies:

• Late Work.

• Lab Attendance.

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

### What is this course is really about?

• YES: Algorithmic Problem Solving

• ALSO: Programming in Python

• NO: `vim`, `Unix`, `ssh`, `update21`, etc. However, it is important to learn these tools so that you can use them to do course work. If these seem confusing right now, that is expected. You will become more proficient at unix and vim and other tools as you use them over the course of the semester.

#### 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 an Algorithm?

First consider what a computer can do, and what it is good at vs. what a human can do and is good at:

• A computer isn’t very smart, it can only do a very small set of very simple things (mostly one at a time). For example it can add 6 and 13 together. It cannot view things holistically, infer meaning, or solve problems given a description. However, a computer can perform its set of very simple things very fast (e.g., it can add two number in 1 nanosecond (10-9 seconds)). A computer also never gets bored performing this small set of things it can do over and over, and it does not make errors performing these tasks (unless the data values are bad in some way).

• A human is smart (way way smarter than a computer). Among other things, humans can perform a large set of complex tasks, can learn and invent new ones, can solve problems, and can see things holistically and at different levels of detail. However, humans perform most tasks much much slower than a computer (not all though!) and get bored with tedious tasks like computing the average of a set of 1,000 values, and are also likely to make some arithmetic mistakes along the way.

It would be nice if we could just tell the computer to do something complex for us, like simulate global climate, and have it figure out how to do it, and then perform the task quickly, and without error or complaint.

Instead, in order to get a computer to perform a useful task, we have to first come up with an algorithm for how to solve the task.

An algorithm is a set of sequence of steps that solve a larger problem. These steps of an algorithm can be expressed in a programming language to create a program that a computer can than run to solve the larger problem.

#### What is Python?

Python is the programming language we will use to implement and test our algorithms. Python is a high-level language, meaning it is readable and understandable by a human. Java and C++ are other examples of programming languages you may have heard of. Computers understand a binary language (expressed in sequences of 0’s and 1’s), that is pretty horrible for a human to read and understand. Python code is run by the python interpreter, which translates the human readable Python code to a form the the computer can execute.

We use Python in CS21 because it is a relatively easy programming language to learn compared to some others, which means we can focus on algorithmic problem solving earlier and do some fun and interesting things right away!

### Writing our first full Python program

First ssh into a CS lab machine (use your username in place of `tnas`):

``````homemachine> ssh tnas@cslab.cs.swarthmore.edu

cheese[~]$ls`````` Then run `update21`. If `update21` worked for you, it should have created an empty `welcome.py` file in your `~/cs21/inclass/w02-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 `vim` 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 w02-intro/ cheese[inclass]$ cd w02-intro/

cheese[w02-intro]$ls welcome.py cheese[w02-intro]$ vim welcome.py``````

Inside the vim editor, we are going to implement our first Python program. Type in the following content (make sure you are in insert mode), and use your name instead of A. Student to take credit for your work.

``````"""
My first Python program
A. Student
January 2022
"""

def main():
print("Welcome to CS21!")

main()``````

Save the file and exit vim by entering vim ESC mode, and then typing `:wq`.

You should be back at the command prompt and you can run the program by typing the following in the terminal:

`cheese[~]$python3 welcome.py` 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 `vim` editor. 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 A. Student January 2022 """ 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’ll 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/w02-intro` folder ### Variables and types We use computer programs to process data, so 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 refers to value of a particular type. In the example below, `place` is a variable that refers to the value of the name of a place. The value that the variable `place` refers to is string containing a sequence of characters between double quotes (`"Paris"`). ``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. ### Variable Types In addition to the string type (str), we will initially focus on the integer (int) data type for whole numbers, for example: ``````numStudents = 35 year = 2021 diff = -6`````` and the floating point (float) data type for decimal data, for example: ``````tempF = 34.1 gravity = 9.8`````` Let’s try out a program that assigns some variable of different types and using the `print()` function to print out their values. First let’s open in `vim` to see that the program does: `$ vim variables.py`

Then let’s run it using the `python3` interpreter:

`$python3 variables.py` You can also try modifying the program code by changing the values assigned to variables, or by using the `+` operator to assign variables the values of some simple arithmetic expressions. Then, save your changes in `vim` and re-run in `python3` and see what happens. You can combine two numeric values with `+` and also two strings with `+`. Try out some examples like this and see what happens (remember to save your changes to your file in vim with `:wq` before running): ```x = 6 + 7 print(x) y = 14.3 + 2.6 print(y) name = "Grace " + "Hopper" print(name)```  We recommend having two terminal windows open (ssh’ed into a CS lab machine from each one). In one terminal window you can run `vim` to view (and edit) the program code, while in the other can run the program and see what happens. We also 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? ## Friday Today • Reveiw of variables and type • The input() function • Converting between types • Design a full program • Preview: more expressions, operators, variables and type ### 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 January 2022 """ def main(): name = input("What is your name?: ") print(name) main()`````` The program above is pretty terse. How could you modify it so it prints "Hello" followed by the entered name on the same line? ### 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 out some examples in the `types.py` program. First open in vim: ``$ vim types.py``

Try out some of these and see what happens:

``````x = int("7")
print(x)
y = 3.2
print(y)
x = int(y)
print(x)
ans="12"
x = int(ans)
print(x)``````

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

### Designing a full program

Suppose we are given the following problem: Have the user enter the current year as a number and the year they plan to graduate and print how many more college years they have left. We want to design an algorithm that can solve this problem 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. This solution does not have to be in python. Pseudocode is fine.

3. Write your solution in python using your editor (`vim`).

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 younger siblings. Always do step 4 if you do step 3.

```$cd$ cd cs21/inclass/w02-intro

$vim grad.py$ python3 grad.py
Enter the current 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 using the `operators.py` program after the quick summary, 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` produces a syntax error.

### Quick practice

Take a minute or two, look at the example `operators.py` program in vim, and try running it. Then play aournd with modifying the program with other operators (remember to save your changes to the file, `:w` in vim). Do they do anything unexpected? Try to combine them in larger expressions. What happens?

```$vim operators.py$ python3 operators.py```

### 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)
hw = "hello"*3
print(hw)``````

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!