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):
-
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
-
Copy over the week 2 files into your
w02-loops
subdirectory (check that they were successfully copied by runningls
:$ 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
, andc
. -
\(x = \frac{-b \pm \sqrt{b^2-4ac}}{2a}\)
-
-
loops.py
: example for loops, looping over different sequences, using therange
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