Week 1: Introduction to CS21 and Python Programming

Week 1 Goals

  • Understand course format and policies

  • Learn about the CS network and Linux

  • Learn to use the Visual Studio Code editor (code)

  • Learn how to write and run python programs

  • Learn basic python syntax and semantics

  • Learn the string, integer, and float data types

Course Overview

Get Week 1 In-class Code

To copy over the week 1 in-class example program, do the following (If you have trouble with either of these steps, ask a Ninja or your professor for help):

  1. Create a w01-intro in your cs21/inclass subdirectory, and cd into it:

    $ cd ~/cs21/inclass
    $ mkdir w01-intro
    $ cd w01-intro
    $ pwd
    /home/yourusername/cs21/inclass/w01-intro
  2. Copy over the week 1 files into your w01-intro subdirectory (check that they copied successfully copied by running ls:

    $ cp ~admin21/public/w01-intro/* ./
    $ ls
    greeting.py  numbers.py  welcome.py

Editing and Running Python programs

To open and edit a Python source code file, in a terminal, run the code editor with the name of the file you want to edit (e.g., prog.py):

$ code prog.py

To run a Python program, in a terminal, invoke the Python interpreter (python3) followed by the name of the file with the Python program you want to run (e.g. prog.py):

$ python3 prog.py

Week 1 Code

welcome.py

The welcome.py program shows an example Python program. Let’s open it in code and look at some of the main features of a Python program:

$ code welcome.py

Now, lets run the program using the Python interpreter. In a terminal window type:

$ python3 welcome.py

greeting.py

Open greeting.py with code and try running it with python. Let’s try to modify the program to prompt the user for a different greeting.

numbers.py

  • numbers.py introduces a second data type: integer. What was the first data type we saw?

  • Modify numbers.py to cast the user input to a float. Save, run, and test your program.

  • You can also use the python shell to try small examples. Type python3 in a terminal without a file name to enter the shell. Type Ctrl-D to exit the shell. Note the >>> prompt for the python shell.

  • Try a few operations in the shell

    >>> txt = "hello"
    >>> a = 2
    >>> x = 3.5
    >>> type(txt)
    >>> type(a)
    >>> type(x)
    >>> x + a
    >>> a + txt
    >>> txt + txt
    >>> ans = "2.7"
    >>> y = float(ans)
    >>> print(y)
    >>> type(y)
    >>> b = int(y)
    >>> type(b)
    >>> print(b)
    >>> c = int(ans)