\documentclass[11pt]{cselabheader}

\newcommand{\thelabnumber}{1}
\newcommand{\thetitle}{Programming with Python}
\newcommand{\theauthor}{CSE/IT 107L}

% Write title and author
\title{{\large And Now For Something Completely Different} \\ \thetitle}
\author{\theauthor}
\date{NMT Department of Computer Science and Engineering}

\fancyhead[R]{Lab \thelabnumber: \thetitle}
\fancyhead[L]{\theauthor}

\makehyperref
\makeindex[title={Index of New Commands, Functions, and Methods}, intoc]

\begin{document}

\pagenumbering{roman}

\maketitle
\hrule

% Quotes and comics
\begin{quotation}
  ``A beginning is the time for taking the most delicate care that the
  balances are correct.''
\end{quotation}

\begin{flushright}
    --- Frank Herbert (\textit{Dune})
\end{flushright}

\begin{quotation}
  ``I choose to believe what I was programmed to believe.''
  \end{quotation}

\begin{flushright}
    --- Robot Villager \#2 (\textit{Futurama})
  \end{flushright}

\vspace{1em}

\hrule

\begin{figure}[H]
  \centering
  \includegraphics[width=0.65\textwidth]{img/xkcd_759.png}
  \caption{\url{http://xkcd.com/759}}
\end{figure}

\hrule

\section*{Introduction}
Computer programs are written using programming languages. Python is a
relatively simple and frequently used programming language. It powers
several popular applications, but we will use it to learn the
fundamentals of writing computer programs.  This lab will help you
learn the basics of reading, writing and running Python programs.

You will learn how to use Python to compute arithmetic expressions,
assign the results to variables, debug your programs with the
help of Python's error messages, draw pictures using the Turtle
module, and run statements multiple times using for loops --- the most
important lesson in this lab.

\tableofcontents

\newpage
\pagenumbering{arabic}

\section{Starting Python}

To start the Python interactive shell, type the command
\bashindex{python3} in your terminal.  It is important that you not
use \texttt{python}, but \texttt{python3}. The output of this command
should resemble this sample:

\begin{bashcode}
$ python3
Python 3.0.0 (default, Jun 2 2004)
[GCC 2.0.0 20041212] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
\end{bashcode}%$

Note the first line of output on line 2: \texttt{Python 3.0.0}.
Make sure you have \textsl{Python 3} or higher.
In these labs, sample text from sessions in the Python interactive shell
are surrounded in a box and have \bashinline{>>>} before text
that you are suppose to type. The \texttt{\$ python3} and the version
output are not shown.
Here's an example:

\begin{pyconcode}
>>> # Text that appears in console font within a framed box and is preceded by
>>> # three greater-than signs contains code and results from a Python
>>> # interactive shell.
>>> print('this is some example output')
this is some example output
>>> exit()

\end{pyconcode}

Type \pythoninline{exit()} then press enter, or type the key combination
Ctrl+D to exit the Python interactive shell and go back to the terminal.

\section{Arithmetic, Variables, and Values}

\subsection{Python As A Calculator}

\subsubsection{Addition With \pythoninline{+}}

At the Python prompt \pyconinline{>>>} you can type in Python statements and
immediately see the result. For instance, to add 2 + 3, simply type \texttt{2 +
3}:

\begin{pyconcode}
>>> 2 + 3
5

\end{pyconcode}

Notice that after a statement is executed, you are given a prompt to
enter another statement. The \texttt{+}\index{operator +, addition} is
called the addition operator.

\subsubsection{Subtraction With \pythoninline{-}}

\begin{pyconcode}
>>> 2 - 3
-1

\end{pyconcode}

\subsubsection{Multiplication With \pythoninline{*}}

\begin{pyconcode}
>>> 2 * 3
6

\end{pyconcode}

\subsubsection{Division With \pythoninline{/} and \pythoninline{//}}

\texttt{/}\index{operator /, division} divides the left hand operand
by the right hand operand, while \texttt{//}\index{operator //, floor
division} does the division and cuts off the decimals.

\begin{pyconcode}
>>> 2 / 3
0.6666666666666666
>>> 2 // 3
0
>>> 2 / 3.0
0.6666666666666666
>>> 2 // 3.0
0.0
>>> 2. / 3.
0.6666666666666666
>>> 2 / float(3)
0.6666666666666666

\end{pyconcode}

If you wish to drop the decimal portion, you must use \texttt{//}. If
the result of a division drops decimal portion of the answer then that
type of division is called integer division (since your answer will
always be an integer) or floor division (since it will always round
down).

This is an example of a major difference between Python 2 and Python 3. If
you are using Python 2 some of these calculations will give different
results.

\subsubsection{Modulus With \texttt{\%}}

\texttt{\%}\index{operator \%, modulus} divides the
left hand operand by the right hand operand and gives you the
remainder.

\begin{pyconcode}
>>> 5 % 3
2
>>> 3 % 5
3
>>> 7 % 3
1

\end{pyconcode}

If you divide 7 by 3, 3 goes into 7
twice with a remainder of one. The modulus of two numbers can play an important
role in many computations, and in later labs.

Modulus can, for example, tell you whether an integer is even or odd:

\begin{pyconcode}
>>> 5 % 2
1
>>> 6 % 2
0

\end{pyconcode}

For even integers, division by two will yield a remainder of zero.
For odds, it's a remainder of one.

\subsubsection{Exponentiation With \pythoninline{**}}

\texttt{**}\index{operator **, exponentiation}
performs an exponential (power) calculation.  \texttt{a ** b} means a
raised to b. Do not confuse this symbol with the caret (\texttt{\^}),
which performs an entirely different calculation.

\begin{pyconcode}
>>> 2 ** 2
4
>>> 2 ** 3
8
>>> 10 ** 5
100000
>>> 5 ** 10
9765625
>>> 9 ** 0.5
3.0
>>> 5.5 ** 6.8
108259.56770464421

\end{pyconcode}

\subsubsection{Negation and parentheses}

\texttt{-}\index{unary operator -, negation}
can be used to negate a number and
parentheses\index{parentheses} can be used to control the order of
operations.

\begin{pyconcode}
>>> -5
-5
>>> -(55 * 10 + 1000)
-1550
>>> -55 * 10 + 1000
450

\end{pyconcode}

Python can handle very large numbers. Try raising 10 to the 100th power
(this number is called googol.)

\begin{pyconcode}
>>> 10 ** 100
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

\end{pyconcode}

These operators can be combined to form more complicated
calculations. They follow typical precedence rules, with \texttt{**}
having higher precedence than \texttt{*}, \texttt{/}, \texttt{\%}, and
\texttt{//}, which have higher precedence than \texttt{+} and
\texttt{-}. If operators have equal precedence they execute left to
right. You can always use parentheses to change the precedence.

\begin{pyconcode}
>>> 6 * 5 % 4
2
>>> 6 * (5 % 4)
6
>>> 6 * 5 % 4 - 6 ** 7 + 80 / 3 # $((6 \times 5) % 4) - 6^7 + \frac{80}{3}$
-279907.3333333333

\end{pyconcode}

The \texttt{\#} indicates the start of an inline comment\index{inline
comments}.  Use them to remind yourself and others about the behavior
of or rationale behind the code.

\subsection{First Error}

What happens if you try to divide a number by zero?

\begin{pyconcode}
>>> 100.0 / 0.0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    100 / arbitrary
ZeroDivisionError: float division by zero

\end{pyconcode}

Python \textsl{raises} a \pythonindex{ZeroDivisionError} and gives
you the message \texttt{float division by zero}. In later labs, we
will learn how to use code to detect some Python errors.

\subsection{Integers and Floating Point Numbers}
There are two types of numbers in Python, integers\index{number,
integer} and floating point numbers\index{number, floating point}, also
called \texttt{int}s and \texttt{float}s.  Integers do not have a
decimal point and can represent any number without a decimal point
(as long as the machine has enough memory),
while floats can represent numbers with decimal points but have
limited range (approximately between the enormous numbers $-10^{308}$
and $10^{308}$).

Here are some examples of integers:

\pythoninline{0, 1, 134, -3, -10000}

Floats can be written using scientific notation: \pythoninline{5.6E14}.
The number \texttt{mEx} is interpreted as $m \cdot 10^x$.

\pythoninline{0.0, 1.0, -2.0, 4.5, -7.41412, 5.6E14, -2.333333E-9}

\subsection{Saving Values in Variables}
Ints and floats are examples of Python values\index{values}.
Python values are the \textsl{result} of computations such as \pythoninline{2 + 2};
they are also literal numbers like \pythoninline{2} or \pythoninline{3.1415}.
Think of values as the final results of calculations.
We will learn about many more types of values as the course progresses.

Variables\index{variable} let you store values and use them in later parts
of the program. They are an indispensable feature of Python.
The assignment operator (\texttt{=})\index{assignment, =} is for
assigning a value to a \textsl{variable}. A variable can have any name
consisting of letters, numbers, and underscores. A variable name cannot start
with a number. Once a variable has
been assigned, it can be used in future computations as though it were a
value. Variables can be reassigned, they can also refer to their previous
value. For example, to increment a variable \pythoninline{x} this code
should assign it its previous value plus one: \pythoninline{x = x + 1}.

\begin{pyconcode}
>>> x = 7
>>> y = 5 + x
>>> y
12
>>> x
7
>>> x = x + 1
>>> x
8

\end{pyconcode}

In general, you should try to give your variables descriptive names so that it is
clear what they are meant to store; for example:

\begin{pyconcode}
>>> food_price = 4.50
>>> drink_price = 1.00
>>> subtotal = food_price + drink_price
>>> tax = subtotal * 0.07
>>> total = subtotal + tax
>>> total
5.885

\end{pyconcode}

\begin{pyconcode}
>>> arbitrary = 10.0
>>> 100 / arbitrary
10.0
>>> arbitrary = 0.0
>>> 100 / arbitrary
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    100 / arbitrary
ZeroDivisionError: float division by zero

\end{pyconcode}

It is important for you to know the difference between values and
variables.  Values that we currently know are integers and floating
point numbers like \pythoninline{5} or \pythoninline{3.1415}.
Variables store copies of values. Can you predict the final values of
\pythoninline{x} and \pythoninline{y} in the following code?

\begin{pyconcode}
>>> x = 4
>>> y = x
>>> x = x + 1

\end{pyconcode}

Here, \pythoninline{x} was assigned to the value 4.
Then, the assignment \pythoninline{y = x} copied the value
stored in \pythoninline{x} to \pythoninline{y}.
In the third line, \pythoninline{x} was assigned to the previous value
of \pythoninline{x} plus one.
In the end, \pythoninline{x} contains 5 and \pythoninline{y} contains 4.

Notice that variables can be reassigned\index{reassignment}.
This is because the second \pythoninline{x} in \pythoninline{x = x + 1}
refers to the previous value.
A useful trick for reading assignment statements is to read them
right-to-left. For example, \pythoninline{x = x + 1} can be read
as ``the previous value of x plus one should be the new value of x.''

\subsubsection{Visualize Python Code as it Runs}

To see this relationship between values and variables more
clearly, you may use \url{pythontutor.com} to visualize
your Python code as it runs. Ensure you are using the Python 3
visualizer. See the following images for an example session.

\begin{figure}[H]
  \includegraphics[width=0.5\textwidth]{img/pythontutor_editing.png}
  \caption{Editing code in the Python Tutor visualization tool. Please ensure
    you have select a version of Python 3 before typing or copying+pasting
    your code. After you finish entering Python code, you will have to
    press a button that says ``Visualize Execution.''}
\end{figure}

\begin{figure}[H]
  \includegraphics[width=\textwidth]{img/pythontutor_vis.png}
  \caption{Watching code run in the Python Tutor visualization tool.
    Final values are presented on the right under the label ``Global frame.''
    Use the buttons ``First,'' ``Back,'' ``Forward,'' and ``Last'' to
    visualize each step of your program.}
\end{figure}


\section{Writing Python Files}

So far, you have been using Python through the interactive shell.
This lets you test ideas quickly and easily.
However, it is important to know how to save your code to a file
and to run it later as a program.
Python code that you save to a Python file works almost identically to what
you type when using the Python interpreter.

In every lab document, any code that belongs in a Python file
will be formatted like this:

\begin{python3code}
# Text that appears in console font within a framed box is sample Python code.
for, while, with, ==, in, as, if, and, or, not
\end{python3code}

To run this type of Python code, you must save it to a file with extension \texttt{.py}.
The \texttt{py} extension indicates it is a Python file.
We can run it as a program by using the command \texttt{python3 filename.py}.

% Indicate that output must be made explicit using print(), unlike REPL.
% example without print()
How can we run the previous examples as Python files?  Try to type one
of the previous examples in a Python file.  Open a file and name it
\pythoninline{arithmetic.py} (or any other name that ends with
\texttt{.py}.  Type the following:

\begin{python3code}
x = 7
y = 5 + x
x
y
\end{python3code}

This code is similar to a previous example.
To run this file, use the command \pythoninline{python3 arithmetic.py}.

\begin{bashcode}
$ python3 arithmetic.py
\end{bashcode}%$

Unlike most Linux commands that you've seen, this command should
produce no output.
We will fix that in the next section.

\subsection{\texorpdfstring%
  {Show Results by Using the \pythoninline{print()} Function}
  {Show Results by Using the print() Function}}

The Python interactive shell automatically prints values,
but we must use a Python function called \pythonindex{print()}
to achieve the same result when running a Python file.
To display the value of \pythoninline{x}, write \pythoninline{print(x)}.
Let's fix \texttt{arithmetic.py}. Change the file so it has the
following contents:

\begin{python3code}
x = 7
y = 5 + x
print(y)
print(x)
x = x + 1
print(x)
\end{python3code}

\begin{bashcode}
$ python3 arithmetic.py
12
7
8
\end{bashcode}%$

What if you want to print something other than numbers?
We can print another type of value called a string\index{strings}.
These are written like this: \pythoninline{'Hello world'},
or equivalently, \pythoninline{"Hello world"}.
They are sequences of letters, numbers, and white-space.
We'll learn more about strings in later labs.
Remember that \pythoninline{x = '5'} and \pythoninline{x = 5} denote different things.
Open a text editor and type the following Python code:

\begin{python3code}
print("Hello, world!")
\end{python3code}

Save your file as \texttt{hello.py} and type the command
\texttt{python3 hello.py} to run it.

\begin{bashcode}
$ python3 hello.py
Hello, world!
\end{bashcode}%$

\pythoninline{print} is a function with the specific task of printing
the value of whatever is within its parentheses.  It is important to
note that \pythoninline{print("Hello, world!")} is the same as
\pythoninline{print('Hello World!')}.
The special string \pythoninline{'\n'}\index{newline \textbackslash n} represents a newline. This means
that the text after the \texttt{\textbackslash n} will start on a
new line. Test this with the following example:

\begin{python3code}
print('Hello, world!\nHow are you?')
\end{python3code}

\subsection{About Functions}

A function is a self-contained command that performs one specific task.
Like a function in math, you can give it one or more parameters. A function may
also pass a value back to the user. How many parameters are appropriate and what
value is passed back depends on the specific function, though.
Let's look at some examples.

\subsubsection{Parameters are Input}

Note that functions are used (or called\index{function calls}) by putting its
name followed by parentheses and some parameters\index{function parameters}
(sometimes also called arguments\index{function arguments}) to the function. A
function may have none, one, or multiple parameters (the parentheses
always have to be there, though). For example:

\begin{python3code}
function_name()
function_name(parameter)
function_name(parameter1, parameter2)
\end{python3code}

\subsubsection{Returned Values are Output}

If a function produces any output, it is
\textsl{returning}\index{function return value} its output.  You can save the output of a
function by assigning it:

\begin{python3code}
x = function1()
y = function2(parameter)
z = function3(parameter1, parameter2)
\end{python3code}

We can infer some important lessons from this sample.
Some functions, such as \pythoninline{function1} only produce output
and accept no input.
The other functions can take one or more parameters and return output.
You will learn how to make your own functions in later labs. Using and
creating functions is a fundamental part of writing computer programs.

Think of a function as a machine that takes parameters,
processes them, and gives back the return value, which may be
saved by assigning it to a variable.

\subsection{\texorpdfstring%
  {Read User Input Using the \pythoninline{input()} Function}
  {Read User Input Using the input() Function}}
% Introduce input(), int(), and float().

So far, the only person in the world that can modify how your program
behaves is you, by changing the program itself.  But what if we want
the Python file to work more like other programs, which accept input
from their users (such as the person typing the command
\bashinline{python3 pythonfile.py}) and change their behavior?
The function \pythonindex{input()} will display whatever string you
write enclosed in parentheses after it, just like
\pythonindex{print()} does; but it also pauses the program and
returns whatever the user types. We can assign this to a variable
and then modify our program's behavior based on what the user typed.
For example, type this in a file called \texttt{input.py}:

\begin{python3code}
user_input = input('Type something, then press enter: ')
print(user_input)
\end{python3code}

What will this Python file print when we run it and type
``hello program! <ENTER>''?

\begin{bashcode}
$ python3 input.py
Type something, then press enter: hello program!
hello program!
\end{bashcode}%$

As promised, the function \pythoninline{input()} prints
\pythoninline{'Type something, then press enter: '}.
Then the program pauses and reads user input.
At this point, the variable \pythoninline{user_input} should contain the
value \pythoninline{"hello program!"}.
It finishes by printing the value of this variable.

\subsection{\texorpdfstring%
  {Convert User Input Into Numbers by Using the \pythoninline{int()} and \pythoninline{float()} Functions}
  {Convert User Input Into Numbers by Using the int() and float() Functions}}

What if we want to interpret the user's input as a number instead of
as a string?  Let's try using \pythoninline{input()}'s return value as
a number in the Python interactive shell:

\begin{pyconcode}
>>> user_input = input('Write a number: ')
Write a number: 55
>>> print(user_input)
55
>>> user_input + 10
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    user_input + 10
TypeError: Can't convert 'int' object to str implicitly

\end{pyconcode}

This error message lets us know that we cannot use the user's input as
a number because it is a string.  It must be converted into an integer
or into a floating point number by using the functions
\pythonindex{int()} or \pythonindex{float()}.  For example, let's
write a program that will read the user's input and try to convert it
into an integer. Then it should multiply the input by 10 and print the
result.  Save it to a file called \texttt{multiplyby10.py}:

\begin{python3code}
user_input = input('Please enter an integer: ')
user_input = int(user_input)
print('The result is:')
print(user_input * 10)
\end{python3code}

Try to run the program three times with inputs:
``55,'', ``55.0,'' and ``not numeric.''

\begin{bashcode}
$ python3 multiplyby10.py
Please enter an integer: 55
The result is: 550

$ python3 multiplyby10.py
Please enter an integer: 55.0
The result is:
Traceback (most recent call last):
  File "multiplyby10.py", line 2, in <module>
    user_input = int(user_input)
ValueError: invalid literal for int() with base 10: '55.0'

$ python3 multiplyby10.py
Please enter an integer: not numeric
The result is:
Traceback (most recent call last):
  File "multiplyby10.py", line 2, in <module>
    user_input = int(user_input)
ValueError: invalid literal for int() with base 10: 'not numeric'
\end{bashcode}%$

This demonstrates one successful run and two failures.  If the user
does not enter a string that can be converted to an integer, such as a
floating point number such as \pythoninline{55.0} or
\pythoninline{'not a number'}, the Python program will throw a
\pythonindex{ValueError} with messages \texttt{invalid literal for
int() with base 10}, and exit. These errors are caused by the
\pythoninline{int()} function.  We will learn how to control for bad
input in later labs.

Try to make and test a new program that uses the conversion function
\pythoninline{float()} instead of \pythoninline{int()}.
\textbf{Try to give every program that you write invalid or
extreme inputs}, or consider what would happen if a program
using external information (return values from \pythoninline{input()})
received something unusual.

\subsection{Debugging Programs}
A bug\index{bug} is an error in computer code that causes unexpected behavior.
``Operators traced an error in the 1946 Mark II computer to a moth
trapped in a relay, coining the term bug. This bug was carefully
removed and taped to the log book'' (\url{http://ei.cs.vt.edu/~history/Hopper.Danis.html}.)
There is no definite method of fixing or preventing unintended behavior,
but modern programming languages offer many features for helping you
find errors in your code.

Python will try to pinpoint which part of your code produced an error.
This feedback can include the file name (\texttt{multiplyby10.py}), line number (2),
and a part of the code (\pythoninline{user_input = int(user_input)}).
Pay attention to any error messages that Python prints.

\section{\texorpdfstring%
  {Repetition with \pythoninline{for} Loops}
  {Repetition with For Loops}}
What if we wanted to print every number from 0 to 2?
Here's a simple, but repetitive solution:

\begin{python3code}
print(0)
print(1)
print(2)
\end{python3code}

What if we wanted to print all numbers from 0 to 100?
Or 0 to a different number, dependent on user input?
We can use Python's \pythonindex{for} loops to repeat sections of code multiple times.
For example, here is another way to print all numbers from 0 to 5:

\begin{python3code}
for i in range(3):
    print(i)
\end{python3code}

Note \pythoninline{for i in range(N)} takes the variable
\pythoninline{i} and assigns it the values 0, then 1, and up to
\pythoninline{N - 1}.  This approach is equivalent to this code:

\begin{python3code}
i = 0
print(i)
i = 1
print(i)
i = 2
print(i)
\end{python3code}

Now it becomes easy to print the numbers from 0 to 100; simply replace the 3 with 101.

\begin{python3code}
for index in range(100):
    print(i)
\end{python3code}

Note you can use Python variables, and anything else that results in an
integer value, as the range limit. For example:
\pythoninline{for i in range(n * 3 + 5)} and \pythoninline{for count in range(33 * 4)}.
You may refer to variables that are defined outside of the \pythoninline{for} loop
and modify them repeatedly. This example adds all numbers from 0 to 9
then prints the result:

\begin{python3code}
x = 0
for i in range(10):
    x = x + i
print(x)
\end{python3code}

\subsection{Nested For Loops}

For-loops don't have to contain simple statements, any Python code can be
repeated many times; even for-loops!
What do you suppose the following code sample does?

\begin{python3code}
n = 3
for row in range(n):
    for column in range(n):
        print(row * column)
\end{python3code}

It assigns 0 to \pythoninline{row},
then sets \pythoninline{column} to 0, then 1, then 2.
The program prints 0 three times.
Then it assigns 1 to \pythoninline{row},
then sets \pythoninline{column} to 0, then 1, then 2.
Now 0, 1, then 2 are printed.
The last iteration assigns 2 to \pythoninline{row},
and again sets \pythoninline{column} to 0, then 1, then 2.
Finally, the program prints 0, 2, and 4.

\subsection{For Loops Dependent on User Input}
What if we do not know the number of iterations a for-loop must
execute when we're writing the Python program?  One way to do this is
to use an integer that was read using
\pythoninline{input()} and converted using
\pythoninline{int()} as the range limit.
This sample program prompts the user for a positive number, then it
prints all numbers from 1 to the user's input:

\begin{python3code}
user_input = input('Please enter a positive number: ')
user_input = int(user_input)
for i in range(user_input):
    print(i)
\end{python3code}

This program prints the sum of all numbers from 1 to the user's input:

\begin{python3code}
user_input = input('Please enter a positive number: ')
user_input = int(user_input)
x = 0
for i in range(user_input):
    x = x + i
print(x)
\end{python3code}

What happens if the user's input is negative?
Remember, for-loops integrate perfectly with many other Python features,
can you think of any other ways to use for-loops?


\section{Drawing Pictures With the Turtle Module}

We will use Python's Turtle module\index{Turtle module} to draw on the
screen.  A module can be accessed by importing it\index{importing
modules}; to do this, you may type \pythoninline{import turtle} in
Python.

\subsection{Drawing Functions}
Once the module is imported, you have access to
a group of functions for controlling the ``turtle'', an arrow
that moves around at your command, drawing a line where it goes.

\begin{description}
\item[\pythonindex{turtle.forward(x)}  ] Move the turtle forward \pythoninline!x! pixels.
\item[\pythonindex{turtle.backward(x)} ] Move the turtle backward \pythoninline!x! pixels.
\item[\pythonindex{turtle.left(x)}     ] Turn the turtle left \pythoninline!x! degrees.
\item[\pythonindex{turtle.right(x)}    ] Turn the turtle right \pythoninline!x! degrees.
\item[\pythonindex{turtle.pendown()}   ] Draw the turtle's path.
\item[\pythonindex{turtle.penup()}     ] Stop drawing.
\end{description}


Combining these commands will let you draw more complicated shapes.
This code will draw a hexagon with side length 100.
Because tracing mode is off, the turtle finishes almost instantly.
Usually, turtle programs close the moment they are done drawing. The function
\pythonindex{turtle.done()} keeps the picture open.

\begin{python3code}
import turtle

turtle.tracer(False)
length = 100
for i in range(6):
    turtle.forward(length)
    turtle.left(60)
turtle.update()
turtle.done()
\end{python3code}

\subsection{Control Drawing Speed}
You will find it convenient to change the speed at which
these drawings are made. Use the \pythonindex{turtle.speed('fastest')}
function to change the speed of the turtle.
You may also call \pythonindex{turtle.tracer(False)}
to turn off tracing and then call \pythonindex{turtle.update()}
when you want to show the results.

\newpage
\section{Sample Program}

Inline comments are parts of a Python program used to convey
the meaning and purpose of a section of Python code.
They are not read by Python, only by programmers.
Use them to explain \emph{why} you are doing something, not to
repeat the tedious details. They look like:

\begin{python3code}
# This is a comment.
print(2 * 2)
\end{python3code}

Read the following program. Make sure you understand how it works.

It uses some new functions from the turtle module:
\begin{description}
\item
  [\protect\pythonindex{turtle.bgcolor()}] Used to change background color. White by default.
\item
  [\protect\pythonindex{turtle.color()}] Change color of the turtle icon.
\item
  [\protect\pythonindex{turtle.window\_width()}, \protect\pythonindex{turtle.window\_height()}]
  Get width and height of the turtle's window or drawing area.
\item
  [\protect\pythonindex{turtle.goto()}] Place turtle at specific coordinates on the screen.
\item
  [\protect\pythonindex{turtle.dot(diameter, color)}] Draw a dot of specified diameter and color.
\end{description}

\pythoninput{lab1/solarsystem.py}

Try to run it. Can you think of any modifications?  We will see a more
complete and concise version in lab 4, when a new type of value ---
the Python list --- is introduced.

\newpage

\section{Exercises}\label{exercises}

\begin{warningbox}{Read Before Starting}
Make sure you understand the sample program and all of the sections about
Python syntax and functions before starting these exercises.

Information on submitting the assignment is on the last page.
\end{warningbox}

\begin{ex}[conversion.py]
  Write a program that reads a floating point number using the
\pythoninline{input()} function. Assume this number is in meters and
convert it to feet, yards, and miles. Then print each of these three
results.

  For reference, 1 meter equals $3.281$ feet, $1.094$ yards, and $6.214 * 10^{-4} = 0.0006214$ miles.

  Here is a sample that demonstrates the functionality of the finished program:

  \begin{bashcode}
$ python3 conversion.py
Please type a measurement in meters: 1
The measurement in feet is:
3.281
In yards:
1.094
In miles:
0.0006214
  \end{bashcode}%$
\end{ex}

\begin{ex}[mean.py]
  Write a program that accepts 10 floating point numbers from the user
  and prints the running average after each number is entered.

  Here is pseudo-code (not valid Python code) for calculating the
  running average:

  \begin{verbatimcode}
sum = 0
count = 0
running_average = 0
get user_input 10 times and:
    count = count + 1
    sum = user_input + sum
    running_average = sum / count
  \end{verbatimcode}

  This is how this program should behave in case the user types
  ``1 <ENTER> 2 <ENTER> 3 <ENTER> 4 <ENTER> 5'':

  \begin{bashcode}
$ python3 mean.py
Please enter an integer: 1
1.0
Please enter an integer: 2
1.5
Please enter an integer: 3
2.0
Please enter an integer: 4
2.5
Please enter an integer: 5
3.0
  \end{bashcode}

  And in case of 2.1, 4.7, 10.3, -4, 77:

  \begin{bashcode}
$ python3 mean.py
Please enter an integer: 2.1
2.1
Please enter an integer: 4.7
3.4000000000000004
Please enter an integer: 10.3
5.7
Please enter an integer: -4
3.2750000000000004
  \end{bashcode}

\end{ex}

\begin{ex}[polygons1.py]
  Ask the user to enter a positive integer.  Then consecutively draw shapes  
with 3, 4, 5, 6, and 7 sides where the side length of each is
the user's input.  For example, if the user enters 100, your program's
output should resemble:

\begin{center}
\includegraphics[width=0.8\textwidth]{img/exercise_polygons1.png}
\end{center}

Distance between shapes does not matter, as long as they do not overlap.
\end{ex}

\begin{ex}[spiral.py]
Write a script that asks the user to enter an angle.
Then use turtle to draw 128 lines, each line is separated by the given angle
and each line is slightly bigger than the last.

For example, if the angle is $60^\circ$ then your code should draw a spiral
that's made up of hexagons, as shown in the sample pictures.

\begin{multicols}{2}
\begin{center}
$44^\circ$
\includegraphics[width=0.9\linewidth]{img/spiral_angle_44.png}

$60^\circ$
\includegraphics[width=0.9\linewidth]{img/spiral_angle_60.png}

$77^\circ$
\includegraphics[width=0.9\linewidth]{img/spiral_angle_77.png}

$90^\circ$
\includegraphics[width=0.9\linewidth]{img/spiral_angle_90.png}
\end{center}
\end{multicols}

Each image has 128 lines. The length and size of each component of your drawing
does not have to be identical to that of the sample pictures.
\end{ex}

% Describes files to submit
\newpage
\printindex
\vfill
Review Lab 0 if you do not know how to compress your files into
a \texttt{.tar.gz} file.
\input{submitting}
\end{document}
