Syntax and Values
Understand expressions, names, core value types, identity, equality, and mutability.
Python programs combine values with operations. A value has a type, such as int, str, or
bool. An expression produces a value; a statement performs an action such as assigning
a name.
Expressions, statements, and names
2 + 3 # expression: produces 5
subtotal = 2 + 3 # assignment statement
tax_rate = 0.2
total = subtotal * (1 + tax_rate)
print(total) # 6.0= binds a name to a value; it does not mean mathematical equality. Names are case-sensitive,
must not begin with a digit, and conventionally use snake_case.
user_count = 12
user_count = user_count + 1
print(user_count) # 13The right side is evaluated first, then the resulting value is rebound to user_count.
Core scalar types
items = 4 # int: whole number
price = 2.75 # float: floating-point number
label = "notebook" # str: Unicode text
available = True # bool: True or False
missing = None # NoneType: intentional absenceInspect values while learning:
print(type(price)) # <class 'float'>
print(isinstance(items, int)) # TruePrefer isinstance(value, expected_type) when checking types because it handles subclasses.
Usually, however, code should use a value's supported behavior instead of checking its exact
type.
Literals and conversion
A literal writes a value directly:
decimal = 1_000_000
binary = 0b1010
scientific = 1.5e3
empty_text = ""Constructors can convert compatible values:
quantity = int("12")
unit_price = float("3.50")
message = str(404)
enabled = bool(1)
print(quantity * unit_price) # 42.0Conversion can fail:
# int("twelve") # ValueError: invalid literal for int()Validate uncertain input or handle the error rather than assuming conversion will succeed.
Comments, indentation, and line structure
Comments begin with #. Indentation is syntax, not decoration:
temperature = 24
if temperature > 20:
status = "warm"
print(status)Use four spaces per indentation level. Parentheses allow readable multi-line expressions:
total = (
10
+ 20
+ 30
)Avoid backslashes for continuation when parentheses, brackets, or braces work.
Equality, identity, and None
== compares values. is asks whether two references point to the same object.
first = [1, 2]
second = [1, 2]
print(first == second) # True: equal contents
print(first is second) # False: distinct objectsUse identity for None:
result = None
if result is None:
print("No result yet")Do not use is to compare numbers or strings. Implementation-level object reuse can make such
comparisons appear to work unpredictably.
Mutable and immutable values
Immutable objects cannot be changed in place. Integers, floats, booleans, strings, and tuples are immutable. Lists, dictionaries, and sets are mutable.
score = 10
alias = score
score += 1
print(alias, score) # 10 11Rebinding score does not alter the integer referred to by alias.
tasks = ["read"]
same_tasks = tasks
tasks.append("practice")
print(same_tasks) # ['read', 'practice']Both names refer to one mutable list, so mutation is visible through either name. Make a shallow copy when independent top-level collections are required:
independent_tasks = tasks.copy()Multiple assignment
Python evaluates the complete right side before assigning names:
left = 3
right = 8
left, right = right, left
print(left, right) # 8 3This is unpacking, covered in depth later.
Common mistakes
- Using an undefined name produces
NameError. - Writing
true,false, ornoneinstead ofTrue,False, orNone. - Mixing tabs and spaces or forgetting indentation after a line ending in
:. - Expecting
input()to return a number; it always returns a string. - Using
iswhen value equality with==is intended. - Assuming assignment copies a mutable object.
Decision guidance
- Use
intfor exact whole-number counts. - Use
floatfor approximate real-number calculations, but not exact currency accounting. - Use
strfor text, even when the characters happen to be digits. - Use
boolfor genuine two-state facts andNonefor “not present yet.” - Copy mutable containers only when shared mutation is not intended.
Practice
- Store a Celsius temperature and compute Fahrenheit with
c * 9 / 5 + 32. - Convert
"125"to an integer, add25, and print the value and its type. - Create two names for one list, mutate it, and explain the result.
- Correct this condition:
if response is "yes":.
LEARNING RECORD
Finish this lesson
Mark it complete when you can explain the main decision without looking.
KNOWLEDGE CHECK