Probability
Intro to Python Programming
Shreya Jayaraman and Luxi Wang
Alex Tsun
Agenda
From Java to Python
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.
Casting
bool() returns False if passed:
Otherwise, returns True
Arithmetic Operators
Arithmetic Operators
Assignment Operators
Don’t:
Do:
Comparison Operators
Single-line comments in Python begin with #
Logical Operators
Strings
String concatenation
Strings
Solution 1: cast to string before printing!
Strings
Solution 2: format string syntax!
Literal text
Replacement fields in {}
(Escape by doubling {{ }})
Eliminates need to cast these values!
If/Else Statements
N.B. There are no {} in Python (used like they are in Java)! -> Indentation is necessary and must be consistent
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
Range
start (inclusive) - optional, default: 0
end (exclusive) - required
step - optional, default: 1
For Loops
Python
Java
Initialization
Condition & update
Similar to for-each loop in Java!
A Mundane While Loop Example...
5
4
3
2
1
Codealong: Python Syntax - Loops
Lists: ordered series of items
0-indexed
can negative index from end of list!
returns list length
Lists: Manipulation
Example calls:
Result:
Returns a new list (vs. append - adds to list ‘in-place’)
Lists: Slicing
list name
start index (inclusive)
end index (exclusive)
Lists: Slicing Examples
From beginning of list
To end of list
Step size
Generating a list of squares
Generating a list of squares
output expression
variable
input list
List Comprehension
Generating a list of squares
Either is ok to use!
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.]]
Codealong: Python Syntax -Lists
Strings: A Reprise
Tuples
Define tuple using ()
Index into tuple using []
Imports
Module Name
Alias for module
specific function to import
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!
Functions: Keyword Arguments
Example Calls:
Output:
Using keyword arguments allows you to specify which parameter an argument applies to - order doesn’t matter here!
Functions: Default Parameters
Default parameter name and value
All the default arguments must come at the end of the function!
Functions: Default Parameters
Example Calls:
Output:
Passing Functions
Example Call:
Output:
Helper Functions
Inner function available only in scope of outer function
Multiple Return Values
Returns multiple values as an implicit tuple (Slide Reference)
hello
hello
hello
hello
hello
Output:
Main in Python
the main method
calls main method
Codealong: Python Syntax - Functions
Sets: collections of unique elements
True if in set:
True if not in set:
Returns length of set:
Removes element from set:
Constructing Sets:
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
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
Classes
Example Calls:
Output:
No new keyword to instantiate class
Function calls: object.function(parameters)
The NumPy Library
k-Tensors
3-Tensor Example: 2D Color image
Image Width
Image Height
RGB
About NumPy
Using Numpy
Conventional numpy package alias
Usage: np.method_name()
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.
Matrices in NumPy: Ones
Matrices in NumPy:Ones
Compare to the Java code for this…
Matrices in NumPy: Array
Casts a list of lists to numpy array
Matrices in NumPy: Arange
(Equivalent to: )
start - optional, default: 0
end - required
step - optional, default: 1
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). |
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
Codealong: NumPy - Creating Arrays
Matrices in Numpy: Reshape
a = np.arange(1, 9)
b= a.reshape((2, 4))
c = b.reshape((4, 2))
d = c.reshape((8, 1))
Matrices in NumPy: vstack and hstack
Function | Example Call | Output |
vstack | | |
hstack | | |
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
Codealong: NumPy - Advanced
Indexing with Arrays
Example Call:
Indexing with Arrays
Example Call:
8
Output:
Indexing with Arrays
Example Call:
Indexing with Arrays
Example Call:
3 4
Output:
Indexing with Arrays
Example Call:
Indexing with Arrays
Example Call:
2 3
6 7
10 11
Output:
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)
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
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. |
The MatPlotLib Library
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.
An Example