CS 330 - Artificial Intelligence - Python in one week I Instructor: - - PowerPoint PPT Presentation

cs 330 artificial intelligence
SMART_READER_LITE
LIVE PREVIEW

CS 330 - Artificial Intelligence - Python in one week I Instructor: - - PowerPoint PPT Presentation

1 CS 330 - Artificial Intelligence - Python in one week I Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Fall 2019 Materials adopted from Kaggle Announcement Course website login Finish course survey


slide-1
SLIDE 1

CS 330 - Artificial Intelligence

  • Python in one week I

Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Fall 2019 1

Materials adopted from Kaggle

slide-2
SLIDE 2

Announcement

  • Course website login
  • Finish course survey by today (especially your

interested topic and programming experience)

  • Read materials on course website

2

  • Python programming and industry experience of

learning new programming language in a week

  • Progress on topics for final project? Final report
  • n Archive?
slide-3
SLIDE 3
  • 10:30 am
  • Monday
  • Sept 16
  • Morken 132
slide-4
SLIDE 4

https://www.plu.edu/communication/life-under-drones/ Panel: “Horizons in Emerging Tech: Drone Innovations in Engineering, Medicine, Library Science, and the Humanities”

  • n Thursday 9.19 from 9 - 9:50 am

Extra course participation credit - Providing pictures or writing summaries on Sakai!

slide-5
SLIDE 5

Overview

  • Learning Python in a week

5

  • Python VS JAVA
slide-6
SLIDE 6

Hello World example

6

#javac HelloWorld.java #java HelloWorld #python Hello.py

slide-7
SLIDE 7

Two different kind of high-level languages

7

  • Interpreters
  • Compilers
slide-8
SLIDE 8

Python introduction

Command mode VS script mode

8

#python #print 1+1 Create hi.py, and write statement: print 1+1 #python hi.py

slide-9
SLIDE 9

Python introduction

  • syntax, variable assignment, numbers
  • functions and getting help
  • booleans and conditionals
  • lists and objects
  • loops and list comprehensions
  • strings and dictionaries
  • files and trees

9

slide-10
SLIDE 10

Python introduction

  • syntax, variable assignment, numbers
  • functions and getting help
  • booleans and conditionals
  • lists and objects
  • loops and list comprehensions
  • strings and dictionaries
  • files and trees

10

slide-11
SLIDE 11

Syntax, variable assignment, numbers

  • Python was named for the British comedy troupe Monty

Python (https://en.wikipedia.org/wiki/Monty_Python)

11

spam_amount = 0 print(spam_amount) # Ordering Spam, egg, Spam, Spam, bacon and Spam (4 more servings of Spam) spam_amount = spam_amount + 4 if spam_amount > 0: print("But I don't want ANY spam!") viking_song = "Spam " * spam_amount print(viking_song) Read the following, think and share output with your neighbors (2 mins)

slide-12
SLIDE 12

Syntax, variable assignment, numbers

12

  • spam_amount = 0

variable assignment!!!

(1 min) What is different from other languages (JAVA?). Think and share with your neighbors

  • No variable “declare”
  • No variable type
slide-13
SLIDE 13

Syntax, variable assignment, numbers

13

  • print(spam_amount)

function call!!!

  • # Ordering Spam, egg, Spam, Spam, bacon and Spam (4

more servings of Spam) spam_amount = spam_amount + 4 Re-assignment!!!

slide-14
SLIDE 14

Syntax, variable assignment, numbers

14

  • if spam_amount > 0:

print("But I don't want ANY spam!") What is the output? What is different from JAVA?

  • Colon (:)
  • Indented (4 spaces), no curly brace
slide-15
SLIDE 15

Syntax, variable assignment, numbers

15

  • viking_song = "Spam " * spam_amount
  • print(viking_song)

What is the output?

slide-16
SLIDE 16

Numbers and arithmetic in Python

16

  • spam_amount = 0

numbers and arithmetic

Try it: #python #spam_amount = 0 #type(spam_amount) Try it: #python #spam_amount = 0.0 #type(spam_amount)

slide-17
SLIDE 17

Numbers and arithmetic in Python

17

Arithmetic

slide-18
SLIDE 18

Numbers and arithmetic in Python

18

  • True division and floor division

Think about the different from JAVA?

print(5 / 2) print(6 / 2) print(5 // 2) print(6 // 2)

slide-19
SLIDE 19

Numbers and arithmetic in Python

19

  • Order of operations

PEMDAS - Parentheses, Exponents, Multiplication/Division, Addition/Subtraction

8 - 3 + 2

  • 3 + 4 * 2

s1 = 5 s2 = 11 # now I want average score aveS = s1 + s2/2 print(aveS) aveS = (s1 + s2)/2 print(aveS)

slide-20
SLIDE 20

Numbers and arithmetic in Python

20

  • Builtin functions for working with numbers

min, max, abs, int, float

print(min(1, 2, 3)) print(max(1, 2, 3)) how about more numbers? print(abs(32)) print(abs(-32)) print(float(10)) print(int(3.33)) # They can even be called on strings! print(int('807') + 1)

slide-21
SLIDE 21

Exercise

  • Try: CS330_ex1.py
slide-22
SLIDE 22

Python introduction

  • syntax, variable assignment, numbers
  • functions and getting help
  • booleans and conditionals
  • lists and objects
  • loops and list comprehensions
  • strings and dictionaries
  • files and trees

22

slide-23
SLIDE 23

Functions and getting help

functions: calling them, defining them, and looking them up using Python's built-in documentation.

23

Think: how we define function in JAVA? In JAVA, functions take a specific number of arguments, each having a particular type: public String print(String s) { System.out.println(s); } Call function: print(“hello”)

slide-24
SLIDE 24

Functions and getting help

Python functions are allowed much more flexibility

24

print("The print function takes an input and prints it to the screen.") print("Each call to print starts on a new line.") print("You'll often call print with strings, but you can pass any kind of

  • value. For example, a number:")

print(2 + 2) print("If print is called with multiple arguments...", "it joins them", "(with spaces in between)", "before printing.") print('But', 'this', 'is', 'configurable', sep='!...') print() print("^^^ print can also be called with no arguments to print a blank line.")

slide-25
SLIDE 25

Functions and getting help

If you forgot what a function is doing, what to do? For example, what abs is doing?

25

In JAVA, you could read JAVA Doc. In Python, you could use help() function: help(abs) —— not help(abs(-2)) help(print)

slide-26
SLIDE 26

Functions and getting help

How to define a function in Python?

26

def least_difference(a, b, c): diff1 = abs(a - b) diff2 = abs(b - c) diff3 = abs(a - c) return min(diff1, diff2, diff3)

slide-27
SLIDE 27

Functions and getting help

How to call function in Python?

27

least_difference(1, 10, 100) print( least_difference(1, 10, 100), least_difference(1, 10, 10), least_difference(5, 6, 7), # Python allows trailing commas in argument lists. How nice is that? )

slide-28
SLIDE 28

Functions and getting help

help(least_difference) # what do you find?

28

Docstrings: def least_difference(a, b, c): """Return the smallest difference between any two numbers among a, b and c. >>> least_difference(1, 5, -5) 4 """ diff1 = abs(a - b) diff2 = abs(b - c) diff3 = abs(a - c) return min(diff1, diff2, diff3)

slide-29
SLIDE 29

Functions and getting help

now if you type: help(least_difference), you will find:

Help on function least_difference in module __main__: least_difference(a, b, c) Return the smallest difference between any two numbers among a, b and c. >>> least_difference(1, 5, -5) 4

29

slide-30
SLIDE 30

Functions and getting help

What would happen if we didn't include the return keyword in our function?

30

def least_difference(a, b, c): """Return the smallest difference between any two numbers among a, b and c. """ diff1 = abs(a - b) diff2 = abs(b - c) diff3 = abs(a - c) min(diff1, diff2, diff3) print( least_difference(1, 10, 100), least_difference(1, 10, 10), least_difference(5, 6, 7), )

None None None The same: mystery = print() print(mystery)

slide-31
SLIDE 31

Functions and getting help

Default arguments for function in Python: When we called help(print), we saw that the print function has several optional arguments. For example, we can specify a value for sep to put some special string in between our printed arguments: print(1, 2, 3, sep=' < ‘) and print(1, 2, 3)

31

slide-32
SLIDE 32

Functions and getting help

Adding optional arguments with default values to the functions in Python: def greet(who="Colin"): print("Hello,", who) greet() greet(who="Dr. Cao") # (In this case, we don't need to specify the name of the argument, because it's unambiguous.) greet("world")

32

slide-33
SLIDE 33

Functions and getting help

Functions are objects too: def f(n): return n * 2 x = 12.5 In this case, x refers to an object of type float, and f refers to an object of type:

print( type(x), type(f), sep='\n' ) print(x) print(f)

33

slide-34
SLIDE 34

Functions and getting help

we can call the function we receive as an argument:

def f(n): return n * 2 def call(fn, arg): """Call fn on arg""" return fn(arg) def squared_call(fn, arg): """Call fn on the result of calling fn on arg""" return fn(fn(arg)) print( call(f, 1), squared_call(f, 1), sep='\n', # '\n' is the newline character - it starts a new line )

34

slide-35
SLIDE 35

Functions and getting help By default, max returns the largest of its arguments. But if we pass in a function using the optional key argument, it returns the argument x that maximizes key(x) (aka the 'argmax').

35

def mod_5(x): """Return the remainder of x after dividing by 5""" return x % 5 print( 'Which number is biggest?', max(100, 51, 14), 'Which number is the biggest modulo 5?', max(100, 51, 14, key=mod_5), sep='\n', ) Which number is biggest? 100 Which number is the biggest modulo 5? 14

slide-36
SLIDE 36

Functions and getting help Lambda functions for short throwaway function whose body fits into a single line.

36

def mod_5(x): """Return the remainder of x after dividing by 5""" return x % 5 mod_5 = lambda x: x % 5 # Lambdas can take multiple comma-separated arguments abs_diff = lambda a, b: abs(a-b) print("Absolute difference of 5 and 7 is", abs_diff(5, 7)) # Or no arguments always_32 = lambda: 32 always_32()

slide-37
SLIDE 37

Functions and getting help Some times you could use lambdas to solve complex questions in single line:


37

# Preview of lists and strings. (We'll go in depth into both soon) # - len: return the length of a sequence (such as a string or list) # - sorted: return a sorted version of the given sequence (optional key # function works similarly to max and min) # - s.lower() : return a lowercase version of string s names = ['jacques', 'Ty', 'Mia', 'pui-wa'] print("Longest name is:", max(names, key=lambda name: len(name))) # or just key=len print("Names sorted case insensitive:", sorted(names, key=lambda name: name.lower()))

slide-38
SLIDE 38

Exercise

  • Try: CS330_ex2.py
slide-39
SLIDE 39

Python introduction

  • syntax, variable assignment, numbers
  • functions and getting help
  • booleans and conditionals
  • lists and objects
  • loops and list comprehensions
  • strings and dictionaries
  • files and trees

39

slide-40
SLIDE 40

Booleans and conditionals

Python has a type bool which can take on one of two values: True and False.

40

x = True print(x) print(type(x))

slide-41
SLIDE 41

Booleans and conditionals

41

Rather than putting True or False directly in our code, we usually get boolean values from boolean operators. Yes or no questions.

slide-42
SLIDE 42

Booleans and conditionals

42

def can_run_for_president(age): """Can someone of the given age run for president in the US?""" # The US Constitution says you must "have attained to the Age of thirty-five Years" return age >= 35 print("Can a 19-year-old run for president?", can_run_for_president(19)) print("Can a 45-year-old run for president?", can_run_for_president(45))

slide-43
SLIDE 43

Booleans and conditionals

43

  • Comparisons are a little clever

3.0 == 3

  • Comparisons are not too clever

‘3’ == 3 True False

slide-44
SLIDE 44

Booleans and conditionals

Comparison operators can be combined with the arithmetic operators

44

def is_odd(n): return (n % 2) == 1 print("Is 100 odd?", is_odd(100)) print("Is -1 odd?", is_odd(-1))

slide-45
SLIDE 45

Booleans and conditionals

  • Python provides operators to combine boolean values

using the standard concepts of "and", "or", and "not". And in fact, the corresponding Python operators use just those words: and, or, and not.

45

Combining Boolean Values

def can_run_for_president(age, is_natural_born_citizen): """Can someone of the given age and citizenship status run for president in the US?""" # The US Constitution says you must be a natural born citizen *and* at least 35 years old return is_natural_born_citizen and (age >= 35) print(can_run_for_president(19, True)) print(can_run_for_president(55, False)) print(can_run_for_president(55, True))

slide-46
SLIDE 46

Booleans and conditionals

46

What should be this?

True or True and False Python has precedence rules that determine the order in which operations get evaluated in expressions like above. For example, and has a higher precedence than or, which is why the first expression above is True.

slide-47
SLIDE 47

Booleans and conditionals

47

Bug code: prepared_for_weather = have_umbrella or rain_level < 5 and have_hood or not rain_level > 0 and is_workday Good code: prepared_for_weather = have_umbrella or (rain_level < 5 and have_hood)

  • r not (rain_level > 0 and is_workday)

Alternative way: prepared_for_weather = ( have_umbrella

  • r ((rain_level < 5) and have_hood)
  • r (not (rain_level > 0 and is_workday))

)

slide-48
SLIDE 48

Booleans and conditionals

booleans really start to shine when combined with conditional statements, using the keywords if, elif, and else.

48

def inspect(x): if x == 0: print(x, "is zero") elif x > 0: print(x, "is positive") elif x < 0: print(x, "is negative") else: print(x, "is unlike anything I've ever seen...") inspect(0) inspect(-15)

slide-49
SLIDE 49

Booleans and conditionals

  • Cautions about indentation

49

def f(x): if x > 0: print("Only printed when x is positive; x =", x) print("Also only printed when x is positive; x =", x) print("Always printed, regardless of x's value; x =", x) f(1) f(0)

slide-50
SLIDE 50

Booleans and conditionals

Data type conversion:

  • We've seen int(), which turns things into ints, and

float(), which turns things into floats, so you might not be surprised to hear that Python has a bool() function which turns things into bools.

50

print(bool(1)) # all numbers are treated as true, except 0 print(bool(0)) print(bool("asf")) # all strings are treated as true, except the empty string "" print(bool("")) # Generally empty sequences (strings, lists, and other types we've yet to see like lists and tuples) # are "falsey" and the rest are "truthy"

slide-51
SLIDE 51

Booleans and conditionals

51

if 0: print(0) elif "spam": print("spam")

slide-52
SLIDE 52

Booleans and conditionals

Conditional expressions

Setting a variable to either of two values depending on some condition is a pretty common pattern.

52

def quiz_message(grade): if grade < 50:

  • utcome = 'failed'

else:

  • utcome = 'passed'

print('You', outcome, 'the quiz with a grade of', grade) quiz_message(80) def quiz_message(grade):

  • utcome = 'failed' if grade < 50 else 'passed'

print('You', outcome, 'the quiz with a grade of', grade) quiz_message(45)

slide-53
SLIDE 53

Exercise

  • Try: CS330_ex3.py
slide-54
SLIDE 54

Questions?

  • Submit your in-class exercises