Sub topic 1
Names, Objects, and Assignment
Prerequisites
Assume you can run Python code in a script or interactive interpreter, use print(), and recognize a program statement.
Names, Objects, and Assignment
Python assignment binds a name to an object. It does not copy a value into a permanent box. A name can later refer to a different object.
count = 3
other = count
count = 4
print(other) # 3
print(count) # 4Both names first refer to the integer object 3. Reassigning count does not change other.
Choosing Valid and Readable Names
A name may contain letters, digits, and underscores, but it cannot start with a digit. Python is case-sensitive, so total and Total differ.
Use lowercase snake_case for ordinary names. Choose names that explain the value:
student_name = "Ada"
items_in_cart = 3Avoid names that hide meaning, such as x, unless the scope is very small. Do not use Python keywords such as class, if, or return.
Dynamic Typing and Checking Types with `type()`
Python is dynamically typed. The object has a type, while a name has no fixed type. Rebinding a name to another kind of object is allowed.
value = 3
print(type(value))
value = "three"
print(type(value))The first call reports int; the second reports str. In larger programs, stable naming and clear interfaces are usually better than repeatedly changing a name's kind of value.
Identity, Equality, and Mutability
== tests whether two objects have equal contents. is tests whether they are the very same object. Use is mainly for singleton values such as None.
Some objects are mutable, meaning their contents can change. Lists are mutable. Integers and strings are immutable.
a = [1, 2]
b = a
b.append(3)
print(a) # [1, 2, 3]
print(a == b) # True
print(a is b) # TrueThe assignment b = a creates another name for the same list. It does not copy the list.
Integers and Floats
int represents whole numbers. float represents numbers with a fractional part. Arithmetic between them often produces a float.
whole = 7
fraction = 2.5
print(whole + fraction) # 9.5
print(type(whole)) # <class 'int'>
print(type(fraction)) # <class 'float'>Floats are approximations, so avoid assuming every decimal is exact.
Exercise
After x = 5, y = x, and y += 1, what are x and y?
Show answer
x is 5 and y is 6; augmented assignment rebinds y to a new integer object.