CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py (cs124-env)...

50
CS 124 Python Tutorial January 14, 2019 Krishna Patel [email protected]

Transcript of CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py (cs124-env)...

Page 1: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

CS 124 Python TutorialJanuary 14, 2019

Krishna Patel [email protected]

Page 2: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

www.tinyurl.com/cs124python

Page 3: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Running Python

Page 4: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

(cs124-env) kpatel$

Interactive Interpreter

You can write Python code right here!

Python 3.5.2 (default, Nov 12 2018, 13:43:14) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>>

python3

Based on a slide by Sam Redmond

Page 5: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

(cs124-env) kpatel$ python3 my_script.py <output from the script>

(cs124-env) kpatel$ python3 hello.py What is your name? Krishna Hey Krishna, I'm Python!

Running Python Scripts

Supply the filename of the Python script to run after the python3 command

Based on a slide by Sam Redmond

Page 6: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Python Basics

Page 7: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

# Single line comments start with a '#'

""" Multiline comments can be written between three "s and are often used as function and module comments. """

Comments

Based on a slide by Sam Redmond

Page 8: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

3 # => 3 (int) 3.0 # => 3.0 (float)

1 + 1 # => 2 8 - 1 # => 7 10 * 2 # => 20 5 / 2 # => 2.5 9 / 3 # => 3.0 7 / 1.4 # => 5.0

7 // 3 # => 2 (integer division) 7 % 3 # => 1 (integer modulus) 2 ** 4 # => 16 (exponentiation)

Numbers and Math

Python has two numeric types int and float

Based on a slide by Sam Redmond

Page 9: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

# Unicode by default greeting = 'Hello' group = "wørld"

# Concatenate combo = greeting + ' ' + group + "!"

combo == "Hello wørld!" # => True

Strings

No char in Python! Both ' and " make string literals

Based on a slide by Sam Redmond

Page 10: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

True # => True False # => False

not True # => False True and False # => False True or False # => True (short-circuits)

1 == 1 # => True 2 * 3 == 5 # => False 1 != 1 # => False 2 * 3 != 5 # => True

1 < 10 # => True 2 >= 0 # => True 1 < 2 < 3 # => True (1 < 2 and 2 < 3) 1 < 2 >= 3 # => False (1 < 2 and 2 >= 3)

Booleansbool is a subtype of int, where True == 1 and False == 0

Based on a slide by Sam Redmond

Page 11: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Similar to null in other languages

not None # => True bool(None) vv # => False

None

None has an inherent value of “False”

Page 12: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

if the_world_is_flat: print("Don't fall off!")

If Statements

No parentheses needed Colon

No curly braces!

Use 1 tab or 4 spaces for indentation — be

consistent Based on a slide by Sam Redmond

Page 13: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Exercise 1

Page 14: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

elif and else

zero or more elifs

else is optional

Python has no switch statement, opting for if/elif/else chains

if name == "jurafsky": print("dan is lecturing") elif name == "kpatel": print("krishna is lecturing") else: print("someone else is lecturing")

Based on a slide by Sam Redmond

Page 15: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

my_integer = 10 # => create an integer my_string = ‘hello!’ v# => create a string

my_integer = my_string # => set my_integer to my_string print(my_integer) # => prints ‘hello!’

Variables

There are no types in Python!

Page 16: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

For Loops

Strings, lists, etc.

No loop counter!

for item in iterable: process(item)

Based on a slide by Sam Redmond

Page 17: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Looping over Collections# Loop over words in a list. for color in ["red", "green", "blue", "yellow"]: print(color)

# => "red" # => "green" # => "blue" # => "yellow"

Based on a slide by Sam Redmond

Page 18: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Looping with an Index

for idx in range(3): print(idx)

# => 0 # => 1 # => 2

for idx in range(3, 6): print(idx)

# => 3 # => 4 # => 5

Page 19: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Exercise 2

Page 20: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

While Loops

while condition: # do something

Page 21: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

break and continuei = 0 while True: print(i) if i == 2: break i += 1

# => 0 # => 1 # => 2

i = 0 while i <= 3: i += 1 if i == 1: continue print(i)

# => 2 # => 3 # => 4

Page 22: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Writing FunctionsThe def keyword defines a function Parameters have no explicit types

return is optional if either return or its value are omitted,

implicitly returns None

def fn_name(param1, param2): ... return value_1, value_2

You can return multiple values

Based on a slide by Sam Redmond

Page 23: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Data Structures

Page 24: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

List

Square brackets delimit lists

Commas separate elements

easy_as = [1,2,3]

Based on a slide by Sam Redmond

Page 25: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Inspecting List Elementsempty = [] also_empty = list() letters = ['a', 'b', 'c', 'd'] numbers = [2, 3, 5, 7, 11]

# Access elements at a particular index numbers[0] # => 2 numbers[-1] # => 11

# You can also slice lists - the same rules apply letters[:3] # => ['a', 'b', 'c'] numbers[2:-1] # => [5, 7]

Based on a slide by Sam Redmond

Page 26: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Exercises 3, 4

Page 27: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Useful List Functions

# Add to end of list lst.append(2) # => [2] lst.append(50) # => [2, 50]

# Insert at position lst.insert(0, ‘hi’) # => ['hi', 2, 50]

# Remove from position lst.pop(1) # => [‘hi’, 50]

Find more functions here: https://docs.python.org/3/tutorial/datastructures.html

Page 28: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Length

numbers = [2, 3, 5, 7, 11] hello = “hi!”

# find the length len(numbers) # => 5 len(hello) # => 3

Page 29: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Counting vs. Indexing

0 1 2 3 letters = ['a', 'b', 'c', ‘d’] len(letters) # => 4

Index

Page 30: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Setsempty = set() letters = ['a', ‘b', ‘a’] letters_set = set(letters) # => set(‘a’, ‘b’)

# Add to a set letters_set.add(‘c’) # => set(‘a’, ‘b’, ‘c’) letters_set.add(‘b’) # => set(‘a’, ‘b’, ‘c’)

# Membership ‘b’ in letters_set # => True ‘c’ in letters # => False

Page 31: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Dictionariesempty = {} also_empty = dict() d = {‘one’: 1, ‘two’: 2, ‘three’:3}

# Getting d[‘one’] # => 1 d[‘four’] # => Raises KeyError

# Setting d[‘one’] = 3 # => {‘one’: 3, ‘two’: 2, ‘three’:3} d[‘six’] = 4 # => {‘one’: 3, ‘two’: 2, ‘three’:3,‘six’:4}

# Membership (looks at keys) ‘one’ in d # => True 2 in d # => False

Keys must be unique

Page 32: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Exercise 5

Page 33: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Tuplesletters = ['a', 'b', 'c', 'd']

# Creating Tuples letter_tup = tuple(letters) # => (‘a’, ‘b’, ‘c’, ‘d’) num_tup = (1, 2)

# Indexing letter_tup[0] # => ’a’

# Cannot change contents once created letter_tup[0] = 4 # => Raises Error

# Membership ‘a’ in letter_tup # => True

tuples are immutable

Page 34: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Numpy

Page 35: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

import numpy as np

Page 36: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Arrays

# Array filled with zeros zeros = np.zeros(4) # => array([0., 0., 0., 0.])

# Array filled with ones ones = np.ones((2, 1)) # => array([[1.],

[1.]])

# Python List to Numpy Array arr = np.array([1, 3, 4]) # => array([1., 3., 4.])

Page 37: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Axis

np.ones((1, 2, 3)) # array([[[1., 1., 1.], [1., 1., 1.]]])

axis 0 (rows)

axis 1 (columns)

axis 2 (depth)

Page 38: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Arraysones = np.ones((2, 1)) # => array([[1.],

[1.]]) arr = np.array([1, 3, 4]) # => array([1., 3., 4.]) cat = np.array([3, 2]) # => array([3., 2.])

# Useful Tricks arr[1] = 9 # => array([1., 9., 4.]) len(ones) # => 2 ones.shape # => (2, 1) ones.reshape(2) # => array([[1., 1.]]) np.concatenate((arr, cat)) => array([1, 3, 4, 3, 2])

Page 39: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Useful Math# Natural log np.log(10) # => 2.302

# Squareroot np.sqrt(4) # => 2

# Dot Product a = np.array([1, 0]) b = np.array([2, 3]) a.dot(b) # => 2

# L2 Norm / Euclidian Distance np.linalg.norm(a) # => 1.0

Page 40: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Broadcastingrange = np.arange(4) # => array([0, 1, 2, 3])

# Vector and a Scalar range * 2 # => array([0, 2, 4, 6])

# Vector and a Vector range / range # => array([nan, 1., 1., 1.])

# Vector and a Matrix matrix = np.ones((3, 4)) range + matrix # => array([[ 1., 2., 3., 4.],

[ 1., 2., 3., 4.], [ 1., 2., 3., 4.]]) When you think of broadcasting, think of element-wise operations

Page 41: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Exercise 6

Page 42: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Documentation

The best resource!

https://docs.scipy.org/doc/numpy/reference/routines.html

Page 43: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Regular Expressions

Page 44: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

re — Regular expression operations# Search for pattern match anywhere in string; return None if not found m = re.search(r"(\w+) (\w+)", "Isaac Newton, Physicist") m.group(0) # "Isaac Newton" - the entire match

m.group(1) # "Isaac" - first parenthesized subgroup m.group(2) # "Newton" - second parenthesized subgroup

# Match pattern against start of string; return None if not found

m = re.match(r"(?P<fname>\w+) (?P<lname>\w+)", "Malcolm Reynolds") m.group('fname') # => 'Malcolm' m.group('lname') # => 'Reynolds'

Based on a slide by Sam Redmond

Page 45: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

# Substitute occurrences of one pattern with another re.sub(r'@\w+\.com', '@stanford.edu', '[email protected] [email protected]')

# => [email protected] [email protected]

pattern = re.compile(r'[a-z]+[0-9]{3}') # compile pattern for fast ops match = re.search(pattern, '@@@abc123') # pattern is first argument

match.span() # (3, 9)

re — Regular expression operations

Based on a slide by Sam Redmond

Page 46: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Exercise 7

Page 47: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

https://www.learnpython.org/ on ChromeModules and Packages Numpy Arrays Generators List Comprehensions Regular Expressions Sets Decorators

Hello, World! Variables and Types Lists Basic Operators String Formatting Basic String Operations Conditions Loops Functions Dictionaries

Unix Videos (follow along)https://tinyurl.com/unix-videosVideos 1, 4, 6-10, 14-19

Based on a slide by Sam Redmond

Page 48: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Sklearn

Page 49: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Documentation

The best resource!

https://scikit-learn.org/stable/user_guide.html

Page 50: CS 124 Python Tutorial - Stanford University(cs124-env) kpatel$ python3 my_script.py  (cs124-env) kpatel$ python3 hello.py What is your name? Krishna

Linear Regression

from sklearn.linear_model import LinearRegression x = np.array([1, 2, 3, 4]) y = np.array([4, 5, 6, 7])

# Fit your linear regression reg = LinearRegression().fit(x, y)

# Predict reg.predict(np.array([1, 2]))