Chapter 2
Objects
- Variables are names for objects.
- Objects represent values
- All values (integers, strings, functions, lists, etc.)
- Think of an object as a chunk of memory (RAM) that represents something
- Variables are bound to objects.
- This binding can change.
- x = 2
- x = 4
- Objects are automatically garbage collected when no variable names them.
- Objects can have more than one name. (That will become relevant later.)
- All objects have
- Value (‘20’, ‘bob’, 3.14159, etc.)
- Type (integer, string, float)
- Identity
- You can use
type()to determine the type of the object referenced by a variable. - The identity is a unique identifier for each object. (This identifier is not a variable)
- use
id()to get the identity of an object.
- use
- Why do we need to keep track of the type of a variable?
- Tells computer how to interpret the bits.
- Also specifies what the legal operations are on those bits.
x/yis legal ifxandyare integers, but not if they are strings.
- How does Python know what type a variable is?
- It remembers it when the variable is assigned.
Expressions
/does floating point division, not integer division.- Even
15 / 5returns afloat. - This may be different from other languages you know.
- use
//to perform integer division.- Show
17 / 5vs17 // 5
- Show
- Even
**is an exponent (Not all languages provide this operator)- Remember your order of operations:
5 + 2 * 3 - Compound operators (
+=,*=, etc.) - Remember that mod
%gives a remainder.
Modules
- When writing larger programs, we usually put Python code in a file.
- It makes it easier to run and re-run.
- Larger programs often break code into multiple files.
- It makes the code easier to manage.
- You can also share parts of your code with others to reduce duplication.
- A file containing code to be used elsewhere is called a module
- To use code from a module in another file, use the import statement.
- For example, the file
math.pycontains many useful functions (sin,cos,sqrt, etc.)- Rather than having every programmer have to write these functions herself, you can say
import math. - Then you have access to the objects inside
math.pylike thismath.sqrt(49) https://docs.python.org/3/library/math.html
- Rather than having every programmer have to write these functions herself, you can say
- Python comes with a standard library of modules to import. These modules contain functions that are so commonly used that it makes sense to bundle them in the language. Available modules include
- math
- random
https://docs.python.org/3/library/
IC 2: Change for a dollar Euclidean distance