Week 2: Numbers, Strings, for loops

Get Week 2 In-class Code

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

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

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

    $ cp ~admin21/public/w02-loops/* ./
    $ ls
    avg.py circle.py factorial.py loop.py root.py stars.py strings.py string_accum.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 2 Code

  • circle.py: practice with numeric types and math library

    • The area \(A\) of a circle with radius \(r\) is \(A=\pi r^2\)

    • The circumference \(C\) of a circle with radius \(r\) is \(C = 2 \pi r\)

  • root.py: another example you can try out

    • Find the two roots/solutions of \(ax^2 + bx + c = 0\) given a, b, and c.

    • \(x = \frac{-b \pm \sqrt{b^2-4ac}}{2a}\)

  • loops.py : example for loops, looping over different sequences, using the range function

  • avg.py, factorial.py: for loops and accumulator pattern with numbers

  • strings.py: using the string type and string operators

  • stars.py: strings and for loops

  • string_accum.py: string accumulator pattern