2.5: Variables and Assignment in Python

Variable concepts (Section 2.5)

  • A variable is a name that represents a storage location in the computer's memory. Programs store data in memory and perform operations on that data.
    • Example scenario: Online shopping cart data is stored in memory as you add items; when you checkout, a program computes totals and stores results back in memory.
  • In Python specifically, a variable references a value in memory rather than holding the value directly. A variable holds the address of the memory location that stores the value.
  • Creating variables with assignment statements:
    • General format: variable=expression\text{variable} = \text{expression}
    • The assignment operator is "=".
    • After execution, the left-hand variable references the value on the right-hand side.
    • Example: age=25\text{age} = 25 creates a variable named age that references the value 25.
    • Note on the illustration language: the idea is the arrow from the variable to the value shows the reference.
  • How to experiment with variables (interactive mode concepts):
    • Create variables using simple assignments, then use print to display values.
    • Example (conceptual):
    • width=10\text{width} = 10
    • length=5\text{length} = 5
    • print(\text{width}, \text{length})
    • Important: when you pass a variable to print, do not enclose the variable name in quotes; quoting would print the literal text instead of the value.
  • Validating assignment targets:
    • The left side of the assignment must be a variable name.
    • Example of an error: 25=h25 = h is a syntax error: cannot assign to a literal.
  • Example programs (variable usage and output):
    • Program: room = 503; print("I am staying in Room Number", room)
    • Output: I am staying in Room Number 503
    • Program with two variables: top_speed = 160; distance = 300
    • Output examples: "The top speed is 160" and "The distance traveled is 300"
  • Printing multiple items:
    • You can pass multiple values to print: print("I am staying in room number", room)
    • When multiple arguments are passed, Python prints them separated by spaces automatically.
  • Variable reassignment and memory management:
    • Variables can reference different values over time.
    • Example: dollars = 2.75; later, dollars = 99.95
    • The old value (2.75) remains in memory only if something else references it; otherwise, it becomes garbage.
  • Data types and numeric literals:
    • Python categorizes numbers as int (whole numbers) or float (numbers with a fractional part).
    • Numeric literals determine type by their form:
    • Whole number literals (no decimal point) are \/int\/: 503503 → int
    • Literals with a decimal point are \/float\/: 2.752.75 → float
    • Examples:
    • room=503\text{room} = 503 (int)
    • dollars=2.75\text{dollars} = 2.75 (float)
  • Determining data types with type():
    • Use the built-in type function to inspect a value's type:
    • type(1)int\text{type}(1) \rightarrow \text{int}
    • type(1.0)float\text{type}(1.0) \rightarrow \text{float}
  • Currency literals caution:
    • Do not include symbols, spaces, or commas in numeric literals.
    • Example of incorrect: value=$4,567.99\text{value} = \$4,567.99
    • Correct form: value=4567.99\text{value} = 4567.99
  • Strings and STR type:
    • Strings are stored using the STR data type in memory.
    • Example:
    • \text{first_name} = "Catherine"
    • \text{last_name} = "Marino"
    • Displaying strings: print( firstname, lastname ) outputs: Catherine Marino
    • A value can be reassigned to a different type (dynamic typing): a variable can reference values of different types over time.
  • Variable naming rules (Python):
    • You cannot use Python keywords as variable names.
    • Variable names cannot contain spaces.
    • The first character must be a letter (a–z, A–Z) or an underscore _.
    • After the first character, you may use letters, digits, or underscores.
    • Variable names are case sensitive: items and Items are different variables.
    • Prefer descriptive names to indicate purpose (e.g., temperature, speed).
    • Readability conventions:
    • Underscores for multiword names (snakecase): e.g., grosspay, payradar, dogsold_today
    • CamelCase is another style (first word lowercase, subsequent words start with uppercase): e.g., grossPay, payRate, dogSoldToday
  • Sensible example names and constraints:
    • Legal: unitsperday, dayofweek
    • Illegal: threedgraph (likely due to incorrect spelling or formatting in the example); names cannot begin with a digit (e.g., 3d_graph is illegal)
    • Names may contain only letters, digits, or underscores
  • Using print with strings and variables together:
    • Example: print("I am staying in room number", room)
    • The two arguments print will display with a space between them automatically due to the print function behavior.
  • Variable reassignment illustrated:
    • Example: dollars = 2.75
    • Then dollars = 99.95
    • The previous value is not referenced by any variable, so it can be garbage collected.
  • Type flexibility of variables (dynamic typing):
    • A variable can be created with one type, then later assigned a value of a different type without error.
    • Example interactive sequence (conceptual):
    • x = 99; print(x) → 99
    • x = "take me to your leader"; print(x) → take me to your leader
  • Key caveat: case sensitivity and quotes with print
    • If you print the variable name with quotes, you print the literal text of the name, not the value: print("width") outputs width
    • If you pass the variable width without quotes, you print the value it references
  • Important: you must assign a value before using a variable
    • Accessing a variable that has not yet been assigned raises an error; e.g., attempting to print an uninitialized variable will fail
  • Interactive examples recap:
    • Multiple assignments: x,y,z=0,1,2x, y, z = 0, 1, 2 ensures x → 0, y → 1, z → 2
    • Another example: name,i=T¨rinidad,¨847name, i = \"Trinidad\", 847
  • Practical takeaway for exam prep:
    • Know the assignment format and the meaning of the assignment operator
    • Distinguish between int and float literals and how Python decides type
    • Remember the rules for valid variable names and case sensitivity
    • Be able to predict outputs of simple print statements with mixed strings and variables
    • Understand that Python uses dynamic typing and that variables can be reassigned to different types
    • Recognize common errors: assigning to literals, using uninitialized variables, and mismatched case in variable names

Self-check questions (concept checks)

  • 2.1 What is a variable?
    • Answer: A name that references a storage location in memory; in Python, the variable holds the address of the memory location that stores the value.
  • 2.11 Which of the following are illegal variable names in Python and why? X 99 bottles, Julie 02/2009, the sales figure for fiscal year and trade report
    • Answer (brief): All contain issues in Python: spaces are not allowed, and symbols like '/' are not allowed; also they cannot start with a digit. Thus, all shown names violate the rules (spaces or invalid characters).
  • 2.12 Is the variable name sales the same as Sales? Why or why not?
    • Answer: No. Variable names are case sensitive in Python, so sales and Sales refer to different variables.
  • 2.13 Is the following assignment statement valid or invalid? 72 = amount
    • Answer: Invalid. You cannot assign to a literal; the left-hand side must be a variable name.
  • 2.14 What will the following code display? Val = 99; print val
    • Answer: It will print 99 (assuming Python 2 syntax; in Python 3 you would need print(val)).
  • 2.15 Look at the following assignment statements: Valueone = 99. Valuetwo = 45.9. Valuethree = sevenpointzero. Valuefour = seven. Value_five = a b c. After these statements execute, what is the Python data type of the values referenced by each variable?
    • Answer: valueone → int, valuetwo → float, valuethree would be invalid due to non-numeric literal (unless defined elsewhere as a numeric value), valuefour → int, value_five is invalid as written (spaces without operators or valid identifiers).
  • 2.16 What will be displayed by the following program? Myvalue = 99. Myvalue = zero; print My_value
    • Answer: The final value assigned to Myvalue is 0, so the output is 0 (assuming the syntax matches the language used in the course; in Python 3 it would require proper syntax like Myvalue = 99; Myvalue = 0; print(Myvalue)).