Class 2: Python Primitives
Jump to navigation
Jump to search
BIOF 309 Curriculum - back to main page
Contents
Python Primitives (screencast 1)
Overview
- Exceptions
- Named Values(Variables)
- Core Python types
- Conversion between types
- Math expressions
- Matrix operations using NumPy
- Strings, with escape characters
Input and variables
- Comments denoted by hash character as first non-whitespace character on the line
- one statement per line, continuation with \, concatenation with ;
- assignment operator - names a value
- Assigning a name to a value never changes the value, or any of the other names
- "bind the name a to the value b"
- letters, underscores and digits, except can't have the first character be a digit
- No funny characters like hyphen
- name refers to something, a primitive value, a function, others
- Can bind multiple names to the same value
- same name can mean different things in different contexts, technical term is namespace
- global namespace
- every type has a namespace associated with it, enables each type to have its own versions of common methods
- no value = None
- retnum = input( "<prompt string>" )
- retstr = raw_input( "<prompt string>" )
import
help('modules')
- selective import
- import all functions into global namespace
- giving something a different name
- anything in if __name__ == '__main__': block doesn't run on import
- Modules and Packages - Required reading. Modules are just one file, packages are multiple files with an __init__py
object = identity, type and value
- Every object has an identity, a type and a value. An object’s identity never changes once it has been created; you may think of it as the object’s address in memory. The ‘is‘ operator compares the identity of two objects; the id() function returns an integer representing its identity (currently implemented as its address). (from http://docs.python.org/2/reference/datamodel.html)
Using print
- reserved word or keyword
- Use quotes for strings
- Use a comma to concatenate strings and non strings
- Use + to concatenate strings only
Floating Point numbers
Math Expressions
- exponent **
- mult *
- division /
- remainder "modulo" %
- floor division //
- addition +
- subtraction -
- integer vs float
- division
- exact vs inexact representation
- range of representations
- how they're kept track of in memory
- scientific notation
- order of operations - PEMDAS
- use parentheses to clarify
- += is shorthand for - augmented assignment stmt
import math
- import is another keyword
- sqrt() a function included in math
- tuple times 5 = unexpected results= repetition
matrix operations using numpy
- import numpy as np
- different ways to construct an array
- np.array
- np.empty
- np.zeros
- np.ones
- resize()
- stdev()
- numpy.ndarray data type
- some code to help debugging:
import numpy; numpy.set_printoptions(threshold=numpy.nan, linewidth=200, formatter={'all':lambda x: '{:0.2f}'.format(x)})