Intro to...

python

By Chris

Structure of this course:

  • What Python is
  • Basics of Python
  • Popular uses
In [2]:
import disclaimer
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-2-7b6ee5730055> in <module>()
----> 1 import disclaimer

ImportError: No module named 'disclaimer'
In [3]:
conflicts_of_interest = None

Python is a high-level interpreted programming language

Advantages: Python code is

  • flexible
  • readable
  • concise

Disadvantages:

  • Kinda slow if you're not careful
  • The Global Interpreter Lock (GIL)

(Pronounced "F$%*#ing GIL")

Basics of Python

Follow along at repl.it

Title

Table of Contents:

  • Strings
  • Arithmetic
  • Exceptions
  • Boolean logic and flow control
  • Lists and loops
  • Dictionaries
  • Functions
  • Resources

Strings

In [4]:
my_string = "Hello world!"
print(my_string)
Hello world!

Strings are indexed with square brackets

In [5]:
my_string[0]
Out[5]:
'H'
  • Use slicing to get a substring
In [6]:
my_string[0:5]
Out[6]:
'Hello'

Concatenate and Repeat with + and *

In [7]:
"Py" + "thon"
Out[7]:
'Python'
In [8]:
"Beetlejuice" * 3
Out[8]:
'BeetlejuiceBeetlejuiceBeetlejuice'
In [9]:
dir(my_string)
Out[9]:
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getnewargs__',
 '__gt__',
 '__hash__',
 '__init__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mod__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rmod__',
 '__rmul__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'capitalize',
 'casefold',
 'center',
 'count',
 'encode',
 'endswith',
 'expandtabs',
 'find',
 'format',
 'format_map',
 'index',
 'isalnum',
 'isalpha',
 'isdecimal',
 'isdigit',
 'isidentifier',
 'islower',
 'isnumeric',
 'isprintable',
 'isspace',
 'istitle',
 'isupper',
 'join',
 'ljust',
 'lower',
 'lstrip',
 'maketrans',
 'partition',
 'replace',
 'rfind',
 'rindex',
 'rjust',
 'rpartition',
 'rsplit',
 'rstrip',
 'split',
 'splitlines',
 'startswith',
 'strip',
 'swapcase',
 'title',
 'translate',
 'upper',
 'zfill']
In [10]:
print(my_string.upper())
HELLO WORLD!
In [11]:
my_string
Out[11]:
'Hello world!'
In [12]:
print(my_string.replace('o', 'i'))
Helli wirld!
In [13]:
print(my_string.split(' '))
['Hello', 'world!']

The format function: useful for debug statements

In [14]:
string_to_print = "Text of string: {text}".format(text=my_string)
print(string_to_print)
Text of string: Hello world!

Arithmetic

In [15]:
1 + 1
Out[15]:
2
In [16]:
8 + 6*2*3 - (15 - 13)
Out[16]:
42
Expression Operation
+ addition
- subtraction
* multiplication
/ division
** Exponentiation
% Modulus
// Floor division
In [17]:
# Modulus
5 % 2
Out[17]:
1
In [18]:
# Floor division
5 // 2
Out[18]:
2

Calculating tip

In [20]:
meal_price = 200.00
tip_percent = 10
tip_to_add = meal_price * tip_percent / 100
In [21]:
print("For a meal of ${price} we should tip ${tip}.".format(price=meal_price, tip=tip_to_add))
For a meal of $200.0 we should tip $20.0.

Use the math module

In [22]:
import math
print("Sine of pi: ", math.sin(math.pi))
print("Square root of two: ", math.sqrt(2))
Sine of pi:  1.2246467991473532e-16
Square root of two:  1.4142135623730951

Python is Exceptional

In [23]:
# type some gibberish
asdf + lkjqpoij
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-23-9d542d1e0044> in <module>()
      1 # type some gibberish
----> 2 asdf + lkjqpoij

NameError: name 'asdf' is not defined
In [24]:
print(meal
  File "<ipython-input-24-2466b6dfa6e1>", line 1
    print(meal
              ^
SyntaxError: unexpected EOF while parsing
In [25]:
the being of being is not itself a being
  File "<ipython-input-25-d3fdaacd7aa0>", line 1
    the being of being is not itself a being
            ^
SyntaxError: invalid syntax
In [26]:
100 / 0
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-26-a187b7beb4f1> in <module>()
----> 1 100 / 0

ZeroDivisionError: division by zero
In [ ]:
2**100000000

Title

Use try-except idiom liberally

In [27]:
while True:
    try:
        x = int(input("Please enter a number: "))
        break
    except ValueError:
        print("Oops!  That was no valid number.  Try again...")
Please enter a number: eight
Oops!  That was no valid number.  Try again...
Please enter a number: 8

Booleans and Flow Control

In [28]:
starts_with_H = my_string.startswith('H')
print(starts_with_H)
True
In [29]:
if my_string.startswith('H'):
    print("IT STARTS WITH H")
else:
    print("It does not.")
IT STARTS WITH H
In [30]:
print(True == True)
print(True == False)
print(False == False)
True
False
True

A Quick note about Indentation

In [ ]:
/* Bogus C Code */
if (foo)
    if (bar)
        baz(foo, bar);
else
    qux();

Python will cast some things to boolean without asking

In [31]:
if my_string:
    print("It's not empty")
It's not empty
In [32]:
empty_str = str()
if empty_str:
    print("It's not empty")
else:
    print("It is empty")
print("This gets printed no matter what.")
It is empty
This gets printed no matter what.
In [33]:
number = 24
divisor = 5
if number % divisor > 0:
    print("{} is not evenly divisible by {}".format(number, divisor))
24 is not evenly divisible by 5

You can use and to combine boolean statements

In [34]:
boolean_literal = True
number = 18
string_literal = "I like to count sheep before bed."

if (number > 10) and (boolean_literal) and ("sheep" in string_literal):
    print("Success!")
else:
    print("Try again!")
Success!

Lists and Loops

In [35]:
favorite_things = ["dogs", "coffee", "python"]
print(favorite_things[0])
dogs
In [36]:
for thing in favorite_things:
    print("Chris likes {}".format(thing))
Chris likes dogs
Chris likes coffee
Chris likes python
In [37]:
favorite_things.append("burgers")
favorite_things
Out[37]:
['dogs', 'coffee', 'python', 'burgers']
In [38]:
print(favorite_things.reverse())
None
In [39]:
favorite_things
Out[39]:
['burgers', 'python', 'coffee', 'dogs']
In [40]:
for i in range(0,4):
    print(i**2)
0
1
4
9
In [41]:
for index, item in enumerate(favorite_things):
    print("Item {} is {}".format(index, item))
Item 0 is burgers
Item 1 is python
Item 2 is coffee
Item 3 is dogs
In [42]:
i = 0
threshold = 5
while i < threshold:
    print("Still in the loop, i = {}".format(i))
    i = i + 1
else:
    print("Iteration is complete!")
Still in the loop, i = 0
Still in the loop, i = 1
Still in the loop, i = 2
Still in the loop, i = 3
Still in the loop, i = 4
Iteration is complete!

The dict container maps keys to values

In [43]:
favorite_colors = {"chris": "blue",
                   "dave": "mauve",
                   "gina": "aubergine"}
print("Dave's fave is {}".format(favorite_colors["dave"]))
Dave's fave is mauve
In [44]:
# You can iterate over them too
for person, color in favorite_colors.items():
    print("{} likes the color {}".format(person, color))
chris likes the color blue
dave likes the color mauve
gina likes the color aubergine

A dict of two lists.

In [45]:
employees = ['jim', 'frank', 'lisa', 'cameron']
root_passwords = ['hunter2', 'a', 'b33lzeBud', 'aspectreishauntingeurope']
#Let's make a dict out of them quickly
employee_password_dict = dict(zip(employees, root_passwords))
print(employee_password_dict)
{'frank': 'a', 'jim': 'hunter2', 'lisa': 'b33lzeBud', 'cameron': 'aspectreishauntingeurope'}

A Quick Intro to Functions

In [ ]:
# Not real code
def function_name(ParameterList):
    statements, i.e. the function body
In [46]:
# Real code
def fahrenheit(T_in_celsius):
    """ returns the temperature in degrees Fahrenheit """
    return (T_in_celsius * 9 / 5) + 32
In [47]:
for temp in (22.6, 25.8, 27.3, 29.8):
    print(temp, ": ", fahrenheit(temp))
22.6 :  72.68
25.8 :  78.44
27.3 :  81.14
29.8 :  85.64

Web Development

Plotting

Matplotlib

In [1]:
from IPython.display import HTML
HTML('<iframe src="http://matplotlib.org/gallery.html" width=600 height=400></iframe>')
Out[1]:

Seaborn

In [48]:
HTML('<iframe src="https://stanford.edu/~mwaskom/software/seaborn/examples/" width=600 height=400></iframe>')
Out[48]:

IPython

In [49]:
HTML('<iframe src="https://ipython.org/" width=600 height=400></iframe>')
Out[49]:

Thanks!

Chris Mullins

crmullins.com

github.com/chrismullins

Email: christopher.r.mullins at gmail.com

MUSC: mullinch at musc.edu

PGP Fingerprint: 467F D965 9542 BD7D B61D A40C 17C4 76FE FD90 6A49