cs 124 python tutorial - stanford university · cs 124 python tutorial january 15, 2019 sam redmond...

38
CS 124 Python Tutorial January 15, 2019 Sam Redmond [email protected]

Upload: others

Post on 06-Jun-2020

13 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

CS 124 Python TutorialJanuary 15, 2019

Sam Redmond [email protected]

Page 2: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu
Page 3: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

Python BasicsData StructuresRegular ExpressionsPractice!!

Plan

Page 4: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

Intro to Python

Page 5: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

>>> import this

The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts.

Page 6: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

Programmers are moreimportant than programs

Page 7: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } }

“Hello World” in Java

Yuck

Page 8: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

#include <iostream> using namespace std;

int main() { cout << "Hello World!" << endl; }

“Hello World” in C++

Double Yuck

Page 9: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

print("Hello world!")

“Hello World” in Python

Page 10: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

Running Python

Page 11: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

(cs124-env) sredmond$

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

Page 12: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

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

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

(cs124-env) sredmond$

Running Python Scripts

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

Page 13: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

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

>>> greet("Dan") Hey Dan, I'm Python! >>>

Interactive Scripts

Page 14: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

Python Basics

Page 15: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

#Hashtag

Pound Sign

Number Sign

Sharp

Octothorpe

Page 16: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

# Single line comments start with a '#'

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

Comments

Page 17: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

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

1 + 1 # => 2 8 - 1 # => 7 10 * 2 # => 20 5 / 2 # => 2.5 13 / 4 # => 3.25 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 MathPython has two numeric types

int and float

Page 18: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

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

Page 19: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

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

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

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

StringsNo char in Python!

Both ' and " make string literals

Page 20: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

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

If Statements

No parentheses needed Colon

No curly braces!

Use 4 spaces for indentation

Page 21: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

if name == "jurafsky": print("dan is lecturing") elif name == "sredmond": print("sam is lecturing") else: print("someone else is lecturing")

elif and else

zero or more elifs

else is optional

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

Page 22: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

for item in iterable: process(item)

For Loops

Strings, lists, etc.

No loop counter!

Loop explicitly over data

Page 23: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

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

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

Looping over Collections

Page 24: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

def fn_name(param1, param2): value = do_something() return value

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

Page 25: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

Data Structures

Page 26: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

easy_as = [1,2,3]

Lists

Square brackets delimit lists

Commas separate elements

Page 27: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

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]

Inspecting List Elements

Page 28: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

# Length (len) len([]) # => 0 len("python") # => 6 len([4, 5, "seconds"]) # => 3

# Membership (in) 0 in [] # => False 'y' in "python" # => True "minutes" in [4, 5, "seconds"] # => False

General Queries

Page 29: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

empty = {} d = {"one": 1, "two": 2, "three": 3}

# Get d['one'] # => 1 d['five'] # raises KeyError

# Set d['two'] = 22 # Modify an existing key d['four'] = 4 # Add a new key

Dictionaries Mutable map from hashable keys to arbitrary objects

Page 30: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

re Regular expression operations

"regular expression" == "search pattern" for strings

Regex HOWTO A Gentler Introduction

Page 31: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

# 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'

re — Regular expression operations

Page 32: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

# 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

Page 33: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

def is_phone(num): return bool(re.match(r'\d{3} \d{3}-\d{4}', num))

def get_area_code(num): m = re.match(r'(?P<areacode>\d{3}) \d{3}-\d{4}', num) if not m: return None return m.group('areacode')

Matching Phone Pattern

Page 34: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

Virtual Environments Primer

Local, isolated Python environment for interpreter, third-party libraries, and scripts

Page 35: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

sredmond$ source ~/cs124-env/bin/activate (cs124-env) sredmond$ python3 —-version Python 3.5.2

(cs124-env) sredmond$ deactivate sredmond$

Practical Commands

Always activate your virtual environment before beginning to code!

Page 36: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

Your Turn!

Page 37: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu

Hello, World!Variables and TypesListsBasic OperatorsString FormattingBasic String OperationsConditionsLoopsFunctionsDictionaries

https://www.learnpython.org/Modules and PackagesNumpy ArraysGeneratorsList ComprehensionsRegular ExpressionsSetsDecorators

Page 38: CS 124 Python Tutorial - Stanford University · CS 124 Python Tutorial January 15, 2019 Sam Redmond sredmond@stanford.edu