cs/coe 1520

48
CS/COE 1520 www.cs.pitt.edu/~nlf4/cs1520/ Python

Upload: others

Post on 05-Dec-2021

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CS/COE 1520

CS/COE 1520www.cs.pitt.edu/~nlf4/cs1520/

Python

Page 2: CS/COE 1520

Python

2

● Guido van Rossum started development on Python in 1989 as a project to keep him busy over the holiday break when his office was closed○ van Rossum was Python's

"Benevolent Dictator for Life"○ Worked for Google from

2005-2012, and worked at Dropbox from 2013-2019■ Both employers had him

spend 50% of his time working on Python

Guido van Rossum

Page 3: CS/COE 1520

● An interpreted language● Version 2.0 was released in Oct. 2000● Version 3.0 was released in Dec. 2008

○ 3.0 was a backwards-incompatible release■ Because of this Python 2.7 was actively used for many

years after the launch of 3.0■ 3.7 was released in 2018 Python

● This is the minimum version I will expect you to be using for the course

■ Be aware of the difference when checking online resources and running Python code on your computer!● You may need to use the command python3 if the default

python command is version 2.x○ You can check with:

■ $ python --version

Python

3

Page 4: CS/COE 1520

print("Hello World!")

Hello World

4

Page 5: CS/COE 1520

import random

# basic syntax overview exampler = random.randint(0, 100)while r < 85:

if r > 70:print(r, ": so close!", sep="")

elif r > 45: # yes, the else if syntax is odd...print(r, end="")print(": Getting there...")

else:print(f"{r}: Still so far away!")

r = random.randint(0, 100)print("OUT!")

Basic syntax

5

Page 6: CS/COE 1520

● Like JavaScript, Python is dynamically typed

● However, unlike JavaScript, Python is considered to be

strongly typed

○ 1 + "1" will raise an error

■ 1 + int("1") is fine, as is str(1) + "1"

○ 1 == "1" will evaluate to False

■ Not the same value, one is a string, one an int

■ Python does not have a === operator

Typing

6

Page 7: CS/COE 1520

● int

● float

○ 7 / 2

■ == 3.5

○ 7 // 2

■ == 3

○ 7.0 / 2.0

■ == 3.5

○ 7.0 // 2.0

■ == 3.0

Numerical types

7

Page 8: CS/COE 1520

● Generally the same as C

○ +, -, *, % all work as expected

○ No ++ or -- operators

○ Augmented assignments available, though (e.g., +=)

● Python-specific operators:

○ //

■ Integer division

○ **

■ Exponentiation

Numerical operators

8

Page 9: CS/COE 1520

● True

● False

● Comparison operators:

○ and

○ or

○ not

■ (True and False) or (not False) == True

Booleans

9

Page 10: CS/COE 1520

● Can be "double quoted"

● or 'single quoted'

● or """TRIPLE

QUOTED"""

○ '''triple singles also work'''

● Plenty of string methods available

○ Note specifically that they can be indexed and sliced

● No char type

Strings

10

Page 11: CS/COE 1520

String slicing

11

s = "slicing is fun!!"

print(s[0])print(s[2:7])print(s[-5])print(s[-5:-2])print(s[11:])print(s[:7])print(s[-5:])

Page 12: CS/COE 1520

def say_hi():print("Hi")

def shout(message="Hi"):print(message, "!", sep="")

shout()

shout("I love python")

shout(message="And keyword arguments")

Functions

12

Page 13: CS/COE 1520

● function foo(x, y=4) {

return x + y;

}

f(3) == 7 // true

Default parameters

13

Page 14: CS/COE 1520

Consider the following:

14

Python functions have no required type annotation

def quacker(an_animal):

an_animal.quack()

So how can we ensure that an_animal has a .quack() method?

● We can't!

● This is an example of duck typing

○ "If it walks like a duck and it quacks like a duck, then it must

be a duck"

● What happens if it does not have a .quack() method?

Page 15: CS/COE 1520

● Immutable sequences

○ t = ("CS", 1520, "Farnan")

○ t[2] = "Garrison" # ERROR!

Tuples

15

Page 16: CS/COE 1520

● How do you create an empty tuple?

● How about a tuple with only 1 item in it?

Special cases with tuples

16

Page 17: CS/COE 1520

● Note that the () can be omitted in tuple definition:

○ s = "CS", 1520, "Farnan"

○ t == s # True

● Further tuples can be "unpacked":

○ a, b, c = t

■ a == "CS"

■ b == 1520

■ c == "Farnan"

Tuple packing and unpacking

17

Page 18: CS/COE 1520

● Tuples can be used to make it seem like a function returns

multiple values:

def mult_ret():

return "one", "two", "three"

a, b, c = mult_ret()

Returning tuples

18

Page 19: CS/COE 1520

● Mutable sequences

○ l = [1, 2, 5]

l[0] = 0

l.append(3)

○ if 3 in l:

print(3, "is in", l)

Lists

19

Page 20: CS/COE 1520

● Key/value stores

○ d = {"Farnan":1520, "Garrison":8}

d["Ramirez"] = 1501

d["Garrison"] = "0008"

○ is "0008" in d ?

○ is "Garrison" in d ?

Dictionaries

20

Page 21: CS/COE 1520

● Unordered collections with no duplicate elements

○ s = {1, 2, 2, 3, 3, 3}

○ print(s)

Sets

21

Page 22: CS/COE 1520

● Already saw a while example…

● Only one type of for loop:

○ crazy_list = ["a", 1, 1.0, "d"]

for item in crazy_list:

print(item)

Looping

22

Page 23: CS/COE 1520

● We can use the range() function:

○ for i in range(10):

print(i)

● Generates a range object to lazily produce values

○ for i in range(1000000000):

print(i)

● Can be called with 1, 2, or 3 arguments:

○ range(end)

○ range(start, end)

○ range(start, end, step)

What about generating a sequence of numbers?

23

Page 24: CS/COE 1520

● crazy_dict = {1:"one", 2:"two", 3:"three"}

● for k in crazy_dict:

print(k, crazy_dict[k])

● for k, v in crazy_dict.items():

print(k, v)

Can loop over dictionaries as well:

24

Page 25: CS/COE 1520

● Succinct way to initialize lists:

○ squares = [x**2 for x in range(10)]

○ names = ["NICK", "FARNAN"]

low = [n.lower() for n in names if n == "NICK"]

List comprehensions

25

Page 26: CS/COE 1520

● Lists, range objects, etc. are iterable

○ Meaning that an iterator can be created for either type

■ Iterators must implement the method __next__()

● Successive calls to __next__() will iterate through the items

in the collection

● When no more items remain in the collection, all future calls

to __next__() should raise a StopIteration exception

■ Can be created via the iter() function

Iterators

26

Page 27: CS/COE 1520

● try:result = x / y

except ZeroDivisionError:print("division by zero!")

else:print("result is", result)

finally:print("executing finally clause")

● try:raise Exception("foo", "bar")

except Exception as e:print(e)print(type(e))print(e.args)

Exceptions and try statements

27

Page 28: CS/COE 1520

● This:○ crazy_list = ["a", 1, 1.0, "d"]

for item in crazy_list:

print(item)

● Is essentially:○ temp_iter = iter(crazy_list)

while True:

try:

item = temp_iter.__next__()

except StopIteration:

break

print(item)

Breakdown of a for loop

28

Page 29: CS/COE 1520

● len()

● sorted()

● min(), max()

● int(), str(), bool(), float()

● repr()

● type()

● help()

● …

Handy built-in functions:

29

Page 30: CS/COE 1520

● set()

○ Produces an empty set, printed as "set()" to avoid ambiguity

with an empty dict

● set([1, 2, 2, 3, 3, 3])

○ Produces {1, 2, 3}

● list(range(10))

○ Produces [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

● dict([("k1", "v1"), ("k2", "v2"), ("k3", "v3")])

○ Produces {'k1':'v1', 'k2':'v2', 'k3':'v3'}

Collection function examples

30

Page 31: CS/COE 1520

● Anonymous functions, similar to arrow functions in JS:

○ lambda params: expression

○ lambda x: x ** 2

○ lambda x, y: x + y

● E.g., sorting a dictionary by its values:

○ a_dict = {1:"one", 2:"two", 3:"three"}

list_of_tups = sorted(a_dict.items(), key=lambda t: t[1])

Lambda expressions

31

Page 32: CS/COE 1520

● Functions that use the yield keyword to return values in order to create iterators○ State is maintained between function calls to the generator

○ def enum(seq):n = 0for i in seq:

yield n, in += 1

○ def fibonacci():i = j = 1while True:

r, i, j = i, j, i + jyield r

Generators

32

Page 33: CS/COE 1520

● function* fib() {

let p = 0, c = 1;

while (true) {

yield c;

let temp = p;

p = c;

c = p + temp;

}

}

Generators

33

Page 34: CS/COE 1520

@plus_onedef add(x, y):

return x + y

Decorators

34

def plus_one(original_function):def new_function(x, y):

return original_function(x, y) + 1return new_function

Page 35: CS/COE 1520

● outf = open("example.txt", "w")for i in range(10):

outf.write(str(i) + "\n")outf.close()

● inf = open("example.txt")for line in inf:

print(line.strip())inf.close()

Basic File I/O

35

Page 36: CS/COE 1520

with open("example.txt") as inf:for line in inf:

print(line.strip())

Contexts and the with statement

36

Page 37: CS/COE 1520

Defining your own contexts

37

from contextlib import contextmanager

@contextmanagerdef tag(name):

print(f"<{name}>")yieldprint(f"</{name}>")

with tag("h1"):print("foo")

Page 38: CS/COE 1520

class Person:def __init__(self, name, age):

self.name = nameself.age = age

def display(self):print("Name:", self.name)print("Age:", self.age)print()

Basic OO

38

Page 39: CS/COE 1520

class Student(Person):def __init__(self, name, age):

super().__init__(name, age)

self.classes = []

def add_class(self, new):self.classes.append(new)

def display(self):super().display()print("Classes:", self.classes)print()

Basic Inheritance

39

Page 40: CS/COE 1520

class Dog:

tricks = []

def __init__(self, name):

self.name = name

def add_trick(self, trick):

self.tricks.append(trick)

f = Dog("Fido")

b = Dog("Buddy")

f.add_trick("roll over")

b.add_trick("play dead")

print(f.tricks)

Class variables

40

Page 41: CS/COE 1520

class Dog:

def __init__(self, name):

self.tricks = []

self.name = name

def add_trick(self, trick):

self.tricks.append(trick)

wow such instance variables

41

Page 42: CS/COE 1520

● Any Python file is a module that can be imported into other Python modules with import

● Let a.py contain:○ def print_n():

for i in range(10):print(i)

def print_l():for l in ["a", "b", "c"]:

print(l)

● Can then (in other files):○ import a

a.print_n()○ from a import print_l

print_l()

Modules

42

Page 43: CS/COE 1520

● Consider:

○ Running python a.py from the command line

○ Having import a in another Python file

● How can we have the former produce output while still being

able to use the latter to pull in definitions??

○ Both will evaluate each line of a.py

○ However, python a.py will have __name__ set to "__main__"

○ Hence, we can choose what to do if run as a script:

■ At the end of a.py, have:

● if __name__ == "__main__":

print("Producing output!")

Writing Python files

43

Page 44: CS/COE 1520

● So far we've only discussed built-ins and the standard library

○ I.e., modules that any Python install should have available

● When we start using Python to build web apps, we'll need

libraries that aren't available by default

○ Meaning they'll need to be specifically installed

● To ease management of other libraries, Python has the

Python Package Index (PyPI)

○ Similar to npm, ruby gems, or crates.io for NodeJS, Ruby, and

Rust, respectively

Additional Python libraries

44

Page 45: CS/COE 1520

● Library code will change over time

○ If you build your app to work on the current version of the

library, what if functionality that it depends on is broken in a

future version?

○ What if you want to maintain two different apps built on

different versions of the same library?

● Solution:

○ Virtual environments

■ Essentially per-application installs of Python packages

Dealing with different library versions

45

Page 46: CS/COE 1520

● Create a new environment:○ $ python -m venv virtual_env_name

■ If your default python is python2, then:● $ python3 -m venv virtual_env_name

■ Creates a folder named virtual_env_name containing:● A copy of the Python interpreter● A copy of the Python standard library● Copies of Python packages

● Start the virtual environment:○ $ source virtual_env_name/bin/activate

■ For bash/zsh, see other options in bin/ for fish/csh

● Leaving the virtual environment○ The command deactivate is available while in the venv:

■ $ deactivate

venv

46

Page 47: CS/COE 1520

● Once inside the virtual environment, you can install packages

from PyPI into the virtual environment using pip

● You can install packages using pip:

○ $ pip install pkg_name

● You can store the list of/versions of installed packages:

○ $ pip freeze > requirements.txt

● requirements.txt can then be used to recreated the virtual

environment on another machine:

○ $ pip install -r requirements.txt

pip

47

Page 48: CS/COE 1520

● This is only a brief introduction to Python● There are many topics that we neared by did not touch

upon○ E.g.,

■ Multiple inheritance■ Packages■ Protocols

● E.g., ○ Containers○ Iterators○ Context Managers

■ …

To wrap up…

48