1 of 74

Probability

Intro to Python Programming

Shreya Jayaraman and Luxi Wang

Alex Tsun

2 of 74

Agenda

  • From Java to Python
  • The Numpy Library: Tensors, Generating Random Numbers
  • The Matplotlib Library

3 of 74

From Java to Python

4 of 74

The Anatomy of Python Variables!

Variable names:

lowercase with underscores between words.

Types:

There are no explicit types in Python! The format var_name:var_type can be used for optional typing for readability.

No semicolons

Strings declared with “” or ‘’

Booleans capitalized

null type

Aside: Optional type annotations are NOT enforced, nor standard practice! However, we may use them at the beginning of this course for extra readability and understanding.

5 of 74

Casting

bool() returns False if passed:

  • False
  • None
  • Empty object
  • Object has value 0

Otherwise, returns True

6 of 74

Arithmetic Operators

  • Just like Java…
    • Addition

    • Subtraction

    • Multiplication

    • Modulus

7 of 74

Arithmetic Operators

  • A bit different
    • Integer division

    • Float division

    • Exponentiation

8 of 74

Assignment Operators

Don’t:

Do:

9 of 74

Comparison Operators

Single-line comments in Python begin with #

10 of 74

Logical Operators

11 of 74

Strings

String concatenation

12 of 74

Strings

Solution 1: cast to string before printing!

13 of 74

Strings

Solution 2: format string syntax!

Literal text

Replacement fields in {}

(Escape by doubling {{ }})

Eliminates need to cast these values!

14 of 74

If/Else Statements

N.B. There are no {} in Python (used like they are in Java)! -> Indentation is necessary and must be consistent

15 of 74

Codealong: Python Syntax - Variables, If/Else statements

The slides of the lesson are here - we’ll let you know which slide to access!

Here, you’ll find instructions and hints for the challenge

This is your code editor!

And finally, your terminal

Access: Go to the CSE 312 EdStem and click (Lessons) on the upper-right

16 of 74

Range

start (inclusive) - optional, default: 0

end (exclusive) - required

step - optional, default: 1

17 of 74

For Loops

Python

Java

Initialization

Condition & update

Similar to for-each loop in Java!

18 of 74

A Mundane While Loop Example...

5

4

3

2

1

19 of 74

Codealong: Python Syntax - Loops

20 of 74

Lists: ordered series of items

0-indexed

can negative index from end of list!

returns list length

21 of 74

Lists: Manipulation

Example calls:

Result:

Returns a new list (vs. append - adds to list ‘in-place’)

22 of 74

Lists: Slicing

list name

start index (inclusive)

end index (exclusive)

23 of 74

Lists: Slicing Examples

From beginning of list

To end of list

Step size

24 of 74

Generating a list of squares

25 of 74

Generating a list of squares

output expression

variable

input list

List Comprehension

26 of 74

Generating a list of squares

Either is ok to use!

27 of 74

Generating from Text Files

np.genfromtxt(filename)

Returns data from text file as n-d array

Data file

[[ 0. 3. 2.]

[ 1. 4. 1.]

[ 2. 8. 2.]

[ 3. 3. 1.]

[ 4. 9. 2.]

[ 5. 4. 1.]

[ 6. 6. 2.]

[ 7. 7. 1.]

[ 8. 1. 2.]

[ 9. 7. 1.]

[10. 0. 2.]]

28 of 74

Codealong: Python Syntax -Lists

29 of 74

Strings: A Reprise

  • Use similar notation to lists since Python treats as ‘list of chars’ - but immutable!

30 of 74

Tuples

  • Immutable ordered list of values

Define tuple using ()

Index into tuple using []

31 of 74

Imports

Module Name

Alias for module

specific function to import

32 of 74

A Basic Function (positional arguments, like java!)

function name

parameter name

parameter type

return type

Example Call: multiplier(4, 5)

Output: 20

Example Call: multiplier(3, “hi”)

Output: ‘hihihi’

Caution: typing for readability, not enforced; this call will not cause an error!

33 of 74

Functions: Keyword Arguments

Example Calls:

Output:

Using keyword arguments allows you to specify which parameter an argument applies to - order doesn’t matter here!

34 of 74

Functions: Default Parameters

Default parameter name and value

  • Default parameter value is used if user doesn’t supply one

All the default arguments must come at the end of the function!

35 of 74

Functions: Default Parameters

Example Calls:

Output:

36 of 74

Passing Functions

Example Call:

Output:

37 of 74

Helper Functions

Inner function available only in scope of outer function

38 of 74

Multiple Return Values

Returns multiple values as an implicit tuple (Slide Reference)

hello

hello

hello

hello

hello

Output:

39 of 74

Main in Python

the main method

calls main method

40 of 74

Codealong: Python Syntax - Functions

41 of 74

Sets: collections of unique elements

True if in set:

True if not in set:

Returns length of set:

Removes element from set:

Constructing Sets:

42 of 74

Dictionaries (like MAPs in JAVA!)

Unordered collection of key/value mappings

Returns value associated with key, i.e. ‘H’

Reassigns value associated with key

Returns true if in keyset

Iterate through every key first_n in dictionary x

Output:

Grace Hopper

Margaret Hamilton

Both iterate through the keyset

43 of 74

Classes

Constructor: defined with special __init__() function

Fields are defined within the constructor.

self is like this in Java, but must be explicitly passed as the first parameter to every function

‘‘‘ ’’’ or “““ ””” used for multi-line comments

44 of 74

Classes

Example Calls:

Output:

No new keyword to instantiate class

Function calls: object.function(parameters)

45 of 74

The NumPy Library

46 of 74

k-Tensors

  • Generalization of scalars, vectors, matrices to k dimensions
  • Can be thought of as a k-dimensional array
  • Think of scalars as 0-D tensors, vectors as 1-D tensors, matrices as 2-D tensors...

47 of 74

3-Tensor Example: 2D Color image

Image Width

Image Height

RGB

48 of 74

About NumPy

  • Package for ‘scientific computing’ - i.e. a lot of the mathematical tools we’ll be needing in this course

  • Why NumPy?
    • Arithmetic functions
    • Multi-dimensional tensors
    • Faster computations than base Python

49 of 74

Using Numpy

Conventional numpy package alias

Usage: np.method_name()

50 of 74

Matrices in NumPy: Zeros

Produces a 3x4 matrix

Parameter: takes the shape of the array - a tuple or int (int x -> (x, )) representing the dimensions of the array.

Notice only 1 parameter - so nested parentheses.

51 of 74

Matrices in NumPy: Ones

52 of 74

Matrices in NumPy:Ones

Compare to the Java code for this…

53 of 74

Matrices in NumPy: Array

  • np.array() will return an n-d array that satisfies the parameters

Casts a list of lists to numpy array

54 of 74

Matrices in NumPy: Arange

  • np.arange() will return an array with evenly spaced values

(Equivalent to: )

start - optional, default: 0

end - required

step - optional, default: 1

55 of 74

Matrices in Numpy: Quick Summary

Method

Description

np.zeros(shape)

Return a new array of given shape, filled with zeros.

np.ones(shape)

Return a new array of given shape, filled with ones.

np.array(object)

Creates an array object satisfying the specified requirements.

np.arange([start, ]stop, [step, ])

Return evenly spaced values within a given interval, from start (inclusive) to stop (exclusive).

56 of 74

Codealongs

The slides of the lesson are here - we’ll let you know which slide to access!

Here, you’ll find instructions and hints for the challenge

This is your code editor!

And finally, your terminal

Access: Go to the CSE 312 EdStem and click (Lessons) on the upper-right

57 of 74

Codealong: NumPy - Creating Arrays

58 of 74

Matrices in Numpy: Reshape

a = np.arange(1, 9)

b= a.reshape((2, 4))

c = b.reshape((4, 2))

d = c.reshape((8, 1))

  • Restructures the shape of an existing array to the given shape
  • Usage: array.reshape(shape)

59 of 74

Matrices in NumPy: vstack and hstack

Function

Example Call

Output

vstack

hstack

60 of 74

Arithmetic with NumPy Arrays vs. Lists

Operation

Result of operation on array

Operation

Result of operation on list

ar + 5

[6, 7, 8, 9]

li + 5

TypeError

ar + ar

[2, 4, 6, 8]

li + li

[1, 2, 3, 4, 1, 2, 3, 4]

ar ** 3

[1, 8, 27, 64]

li ** 3

TypeError

ar * 3

[3, 6, 9, 12]

li * 3

[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]

ar * ar

[1, 4, 9, 16]

li * li

TypeError

* NumPy arrays allow pointwise (elementwise) operations

61 of 74

Codealong: NumPy - Advanced

62 of 74

Indexing with Arrays

Example Call:

63 of 74

Indexing with Arrays

Example Call:

8

Output:

64 of 74

Indexing with Arrays

Example Call:

65 of 74

Indexing with Arrays

Example Call:

3 4

Output:

66 of 74

Indexing with Arrays

Example Call:

67 of 74

Indexing with Arrays

Example Call:

2 3

6 7

10 11

Output:

68 of 74

Aggregators

np.sum

np.sum

78 (returns sum of all entries of matrix)

, axis = 0

[15 18 21 24] (returns sum of each col)

np.sum

, axis = 1

[10 26 42] (returns sum of each row, as a row vector)

69 of 74

More Aggregators

, axis = 1

, axis = 1

, axis = 0

np.mean

np.min

4.25

np.max

[7 6 8]

np.argmax

[3 2 0]

[1 3 5 0]

Returns the indices of the maximum values along an axis

70 of 74

Generating Random Numbers

NumPy Function

Description

np.random.uniform(low=0.0, high=1.0, size=None)

Return a matrix of shape “size” with floating point random numbers in the interval [low, high)

np.random.randint(low, high=1.0, size=None)

Return a matrix of shape “size” with random integers from low (inclusive) to high (exclusive). If only pass in one parameter (low), generates a random integer in [0, low).

np.random.binomial(n, p, size=None)

Return a matrix of shape “size” with each entry being a random sample of the number of heads in n independent coin flips where P(head)=p.

71 of 74

The MatPlotLib Library

72 of 74

Plotting A Graph using matplotlib.pyplot

The x and y coordinates of the data

Line color. Some abbreviations available, such as r - red, g - green, b - blue, etc.

Label for line in the legend

Line style. ‘-’ gives a solid line, ‘--’ gives a dashed one, ‘-.’ gives a dash-dot one, etc.

73 of 74

An Example

74 of 74