% Introduction to Python
% Charles Daniels
% September 17, 2020

# Introduction

## Who Am I?

* Charles Daniels
* PhD CS student
* [HeRC research group](https://cse.sc.edu/~jbakos/group/)
* B.S.E in Computer Engineering from USC
* TA for 313, 317, 611

## Why Learn Python?

* Easy to write
  * Much less boilerplate than Java
  * No need for manual memory management like C/C++
* Popular
  * Widely used in scientific computing and industry
* Huge, mature library ecosystem
  * Numpy/Scipy
  * Matplotlib
  * PIL
  * many, many more

## How Do I Use Python?

I use Python all the time in my work as a graduate student...

* Data processing scripts
  * Convert from one format to another
  * Summarize or gather statistics
* Create figures
* Automate other programs
* Create prototypes for systems to be lowered to C/hardware later

## Python Essentials

* Interpreted, not compiled
* Duck-typed
* Object-oriented
* Garbage-collected

# The Basics

## Want to Follow Along?

* Just open a terminal and run `python3`
* Or use [repl.it](https://repl.it/)
* Or use `ipython3` if you feel fancy

## Syntax - Variables

Python syntax is different from C and Java...

```{.python .run}
# assign a new variable x
x = 7
y = 3
# print x^y
print("{} to the power of {}={}".format(x, y, x**y))
```

## Syntax -- Loops

```{.python .run}
x = 2
while x > 0:
  print("x is ", x)
  x -= 1

for y in range(0, 3):
  print("y is ", y)
```

## Syntax -- Functions

Defining a function…

```{.python .run}
def doubleit(x):
  return x * 2

# here, message has a default value
def sayit(x, message="value is: "):
  print(message, x)

print("doubleit(3)=", doubleit(3))
sayit(5)
sayit(5, "different message!")
```

## Syntax -- Classes 1

Defining a class...

```{.python .run}
class Dog:
  # __init__ is the constructor, the first argument
  # doesn't *have* to be "this", this is just a
  # convention ("self" is also popular)
  #
  # __init__ is defined like any other function, this
  # time we use default values
  def __init__(this, fleas=5, greeting="bark"):
    this.fleas = fleas
    this.greeting = greeting

  def bark(this):
    print(this.greeting)
```


## Syntax -- Classes 2

Using our class...


```{.python .run}
fido = Dog()
# single quotes are also allowed for strings
spot = Dog(3, 'woof')
doge = Dog(greeting="wow, such class, very types")

# create a list with the dogs in it
dogs = [fido, spot, doge]

# loop over it
for dog in dogs:
  dog.bark()
```

## Imports

Some functions, such as $\sin()$ are in *modules* which we must import before
we can use them. $\sin()$ lives in the `math` module.

```{.python .run}
import math

print("pi = ", math.pi)
print("sin(1.5*pi) = ", math.sin(1.5*math.pi))

# we can also import specific items from a module
from math import sin
print("sin(2.5*pi) = ", sin(2.5*math.pi))
```

## Duck Typing

```{.python .run}
class Duck:
  def quack(this):
    print("Quack quack!")

class Goose:
  def quack(this):
    print("Hong honk!")

duck = Duck()
goose = Goose()
for bird in [duck, goose]:
  bird.quack()
```

## Input -- File

```{.python .run}

# open example.txt for reading, the "with" will
# cause the file to be closed automatically when we
# reach the end of the "with" block, so we don't
# have to call f.close()
with open("example.txt", "r") as f:
  lineno = 0
  for line in f:
    print("line", lineno, "is", line)
    lineno += 1

```

## Input -- Standard In

This example shows how to loop over all the lines of standard input…

```python
import sys

lineno = 0
for line in sys.stdin:
  print("line", lineno, "is", line)
  lineno += 1

```

## Output -- File

```{.python .run}
with open("output.txt", "w") as f:
  for i in range(5):
    f.write("line #{}\n".format(i))
with open("output.txt", "r") as f:
  for line in f:
    print(line)
```

# Getting Fancy

## List Comprehensions (Map)

For a list $L$, apply a function $f$ to each item,
creating a new list $L'$ such that $L'[i]=f(L[i])
\forall i$.

```{.python .run}
numbers = [1, 2, 3, 4]
squared = [x*x for x in numbers]
print("squared=", squared)

# convert a string to a list of it's ASCII codes
s = "Hello!"
print("characters=", [ord(c) for c in s])
```

## Setting up to Plot

Code taken from
[matplotlib.org](https://matplotlib.org/3.2.1/gallery/lines_bars_and_markers/simple_plot.html).

```python
import matplotlib
import matplotlib.pyplot as plt
import numpy as np


# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
```

## Plot the Data

```python
fig, ax = plt.subplots()

ax.plot(t, s)
ax.set(xlabel='time (s)', ylabel='voltage (mV)',
       title='About as simple as it gets, folks')
ax.grid()

# un-comment to save out to a file
# fig.savefig("test.png")

# un-comment to show GUI plot window
# plt.show()
```

## The Result...

![](./plot.pdf)

## Attributes Aren't Pre-Declared

Remember our `class Dog` from earlier? This
technique is great for annotating objects you
didn't instantiate (but be careful to avoid name
collisions)

```{.python .run}
fido = Dog()
fido.name = "Fido"
fido.bark()
print(fido.name)
```

# What Next?

## Libraries

* Numerical computing
  * [NumPy](https://numpy.org/)
  * [SciPy](https://www.scipy.org/)
* Plots
  * [matplotlib](https://matplotlib.org/)
* GUIs
  * [tkinter](https://docs.python.org/3.7/library/tkinter.html)
    * [shameless plug](http://cdaniels.net/talks.html#py3_tk)
* Argument Parsing
  * [argarse](https://docs.python.org/3.7/library/argparse.html)

## How to Install Them

* `pip` will let you install Python modules from the internet.
  * Official docs on [python.org](https://packaging.python.org/tutorials/installing-packages/)

* Search packages: `pip3 search searchterm`

* Install a package `pip3 install --user packagename`
  * Don't install globally with `sudo pip install` unless you know what you are
  doing.

* Find packages on [pypi.org](https://pypi.org/).
  * Also try [awesome-python.com](https://awesome-python.com/)

## Questions?

## End.

## Thanks

* This slideshow was written using `pandoc` with
[caiofcm/filter_pandoc_run_py](https://github.com/caiofcm/filter_pandoc_run_py)
used to execute in-line Python code and embed the output.

* Thanks to Josh for copyediting.
