Week 1: Welcome!, data types, variables

Monday

Welcome to CS21! My name is Jeff Knerr (pronounced "nerr"). I am teaching the MWF 11:30-12:20am section. This course is our first course in Computer Science (CS), so no prior knowledge of CS is required. If you have taken AP Computer Science in high school, or have a fair amount of programming experience (understand arrays, strings, searching, sorting, recursion, and classes), please come see me the first week to make sure you are in the correct class. This class is intended for majors and non-majors, but if you have significant programming experience, we may want to move you up to one of the next courses in CS (CS31 or CS35).

For our section we have three in-class ninjas: Emma, Sydney, and Alex. If you get stuck in class or don’t understand something I am explaining, feel free to ask me or the ninjas.

My official office hours are on Fridays (12:30-2pm), but feel free to make an appointment for help or just drop by. I am happy to answer questions about class or lab work, or just review something for quizzes.

This Week

For this week, you need to do the following:

  • attend your assigned lab session, on either Tuesday or Wednesday

  • start working on Lab 0 (due Saturday night) during your lab session

  • read the class web page!

  • if you forget your password, see our password service site

Let me know if you have any questions!

Wednesday

the python3 interactive shell

Opening a terminal window results in a unix shell, with the dollar-sign prompt. At the dollar-sign prompt you can type unix commands, like cd and ls.

Typing python3 at the unix prompt starts the python interactive shell, with the ">>>" prompt. At the python prompt you can type python code, like this:

$ python3
Python 3.6.8 (default, Jan 14 2019, 11:02:34)
Type "help", "copyright", "credits" or "license" for more information.
>>> 10 + 3
13
>>> 10 * 3
30
>>> 10 - 3
7
>>> 10 / 3
3.3333333333333335
>>> 10 // 3
3
>>> 10 % 3
1
>>> 10 ** 3
1000
>>>

The above python session shows some simple math operations.

To get out of the python interactive shell, type Cntrl-d (hold the control key down and hit the "d" key).

data types

Data types are important. To the computer, 5, 5.0, and "5" are all different. Three data types we will work with are: integers (int), floats (any number with a decimal point), and strings (str). A data type is defined by the possible data values, as well as the operations you can apply to them.

For example, a string is any set of zero or more characters between quotes:

  • "A"

  • "PONY"

  • "hello, class!"

  • "1234567"

And only the + and * operators are defined in python for strings:

>>> "hello" * 4
'hellohellohellohello'
>>> "hello" + "class"
'helloclass'

For numbers (ints and floats) all of the normal math operations are possible, as well as a few others: +,-,*,/,//,%,**

>>> 5 / 10      # floating-point math
0.5
>>> 15 // 6     # integer division
2
>>> 15 % 6      # mod operator (remainder)
3
>>> 2**4        # raise to power
16
>>> 2**5
32

variables and assignment

We use variables in our programs instead of raw data values. Once we assign data to a variable, we can use the variable name throughout the rest of our program.

You can create your own variable names, as long as they don’t have any crazy characters in them (no spaces, can’t start with a number, etc).

The assignment operator (=) is used to assign data to a variable.

>>> name = "Jeff"
>>> age = 54

built-in python functions

A function is just a block of code (one or more lines), grouped together and given a name. We’ll learn how to create our own functions in a bit. Python has many built-in functions we can use, like print() and input(). You call a function using it’s name and parentheses.

Some functions just do something (like print data to the screen/terminal), and others do something and return something. For functions that return something (like input(), that returns what the user types in), you usually want to assign what they return to a variable.

Here’s an example of using input() and print() to get data from the user, assign it to a variable, and then print it back out:

>>> name = input("What is your name? ")
What is your name? Jeffrey
>>> print("Hello, ", name)
Hello,  Jeffrey

Some functions require one or more arguments (what is inside the parentheses). The input() function requires one string argument, and this is used as the prompt to the user. When input() is called, the prompt is displayed, and then the function waits for the user to type something and hit the Enter key. Once the user hits Enter, the input() function returns whatever the user typed *as a string*.

In the above example the string "Jeffrey" is returned from input() and immediately assigned to the variable name.

Why does this example fail?

>>> age = input("How old are you? ")
How old are you? 54
>>> print(age*2.0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'float'

Remember, input() always returns a string. So the above fails because python doesn’t know how to multiply a string (age) times a float (2.0).

type conversion functions

python has various type conversion functions:

  • int() — converts argument to an integer

  • float() — converts argument to a float

  • str() — converts argument to a string

Here are some examples, and one way to fix the above error:

>>> int("5")           # convert string "5" to integer
5
>>> float("5")         # convert string "5" to float
5.0
>>> str(5)
'5'
>>> int(3.14159)
3
>>> age = int(input("How old are you? "))
How old are you? 54
>>> print(age*2.0)
108.0
>>>

Note the nested function calls: int(input(…​)) in the last example. This means input() is called and returns something (the user input), which is immediately sent to the int() function to be converted into an integer. So age is assigned whatever the int() call returns.

Friday

FRIDAY file

See the FRIDAY file for extra things to try today. Each lecture I will try to make a MONDAY/WEDNESDAY/FRIDAY file with additional problems/code to write. These are also good to do when studying for the quizzes.

To get to our inclass directory:

cd cs21/inclass/w01-intro

first full program

The first full program we ran today was this silly example showing how to write the main() function:

"""
This is my first python program!!! :)

J. Knerr
Spring 2020
"""

def main():
    print("Line 1")
    print("Line 2")
    print("Line 3")

main()

We started the editor on this file with this: atom firstprog.py

Note the comment at the top, then the defined main() function (everything that is indented), and finally the call to main().

keyboard shortcuts

See the SHORTCUTS file for some handy shortcuts (cat SHORTCUTS).

first real full program

We finally have enough info to write the racepace.py program:

"""
calculate marathon time based on input

J. Knerr
Spring 2020
"""

def main():
    pace = input("What's your mile pace? ")
    pace = float(pace)          # convert str to float
    marathontime = 26.2*pace
    inhours = marathontime/60   # convert minutes to hours
    print("marathontime = ",marathontime, " in hours:", inhours)

main()

your turn!

Write a program called banner.py that asks for a title, a character, and a length, and then generates (prints to the screen) a simple banner: the title between two lines of the given character. The length should be used to print that many of the given character.

Here are two examples of the running program:

$ python3 banner.py
 title: CPSC 021
  char: =
length: 20

====================
CPSC 021
====================

$ python3 banner.py
 title: Welcome to CS21!
  char: $
length: 30

$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
Welcome to CS21!
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

First think about the algorithm! What data do we need to get from the user? What type of data should it be (str, int, float?). Then what should I do with that data?

first look at for loops

How would we write this program?

[source,subs=

$ python3 times.py

factor: 7
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
7 x 11 = 77
7 x 12 = 84

We could use 12 print statements. Is there a better way???