Introduction
In this lesson, you will move from simply running Python code to actually managing data with variables. You will learn how to declare and use variables, what kinds of data they can store, how reassignment changes values during execution, and how to convert between data types safely and intentionally.
By the end, you should feel confident creating variables for numbers, text, and boolean values, understanding how they behave in memory, and using type conversion functions to keep your programs predictable and error‑free.
1. What Is a Variable in Python?
A variable is a name that refers to a value stored in memory. Think of it as a labeled box: the box name is the variable, and the content is the value.
Python uses the assignment operator = to bind a name to a value:
age = 25
name = "Alice"
is_member = True
Here, age, name, and is_member are variables. They are created the moment you assign them a value.
2. Declaring Variables Correctly
2.1 Variable Names and the Assignment Operator
A variable declaration in Python is just an assignment statement:
score = 10 # integer
player_name = "Sam" # string
is_active = False # boolean
Key points:
- The name goes on the left of
=. - The value (expression) goes on the right of
=. - The expression is evaluated first, then the result is bound to the name.
You can also assign the result of an expression:
width = 5
height = 3
area = width * height
Now area stores the result of width * height at that moment in time.
Example: Basic Variable Creation and Use
# Example: Declaring and using variables
item_price = 19.99
quantity = 3
subtotal = item_price * quantity
print("Item price:", item_price)
print("Quantity:", quantity)
print("Subtotal:", subtotal)
# Output:
Item price: 19.99
Quantity: 3
Subtotal: 59.97
Explanation:
item_price,quantity, andsubtotalare variables.subtotalis calculated once when the assignment runs.- The
printcalls read the current values stored in those variables.
3. Mutable vs Immutable Variable Types
Python variables don’t contain values; they refer to objects in memory. Different object types behave differently.
- Immutable types: cannot be changed after creation.
- Common immutable types:
int,float,bool,str,tuple.
- Common immutable types:
- Mutable types: can be changed in place.
- Common mutable types:
list,dict,set.
- Common mutable types:
3.1 Immutable Example
# Example: Immutable variables (int and str)
count = 5
count = count + 1 # creates a new int object and rebinds 'count'
message = "Hello"
message = message + "!" # creates a new string object
print(count)
print(message)
# Output:
6
Hello!
Explanation:
count = count + 1does not modify the original5; it creates a new integer6and makescountrefer to that.- Same with strings: concatenation creates new string objects.
3.2 Mutable Example
# Example: Mutable variable (list)
numbers = [1, 2, 3]
numbers.append(4) # modifies the list in place
numbers[0] = 10 # changes the first element
print(numbers)
# Output:
[10, 2, 3, 4]
Explanation:
numberskeeps referring to the same list object, but that list’s contents change.- Understanding this matters when multiple variables refer to the same mutable object.
4. Storing and Updating Different Value Types
4.1 Numeric Variables
You can store integers and floating‑point numbers and update them using expressions:
# Example: Working with numeric variables
balance = 100.0
deposit = 25.5
balance = balance + deposit
withdrawal = 40
balance = balance - withdrawal
print("Final balance:", balance)
# Output:
Final balance: 85.5
Explanation:
- Each assignment updates
balancebased on its previous value. - You are always creating a new float and rebinding
balance(floats are immutable).
4.2 String Variables
# Example: Updating string variables
first_name = "Jordan"
last_name = "Lee"
full_name = first_name + " " + last_name
print("Full name:", full_name)
# Output:
Full name: Jordan Lee
Explanation:
- The
+operator concatenates strings and produces a new string. full_namestores the result;first_nameandlast_namestay unchanged.
4.3 Boolean Variables
Booleans represent truth values and are often used to track state:
# Example: Boolean variables
is_logged_in = False
# User logs in successfully
is_logged_in = True
print("Logged in:", is_logged_in)
# Output:
Logged in: True
Explanation:
is_logged_inis reassigned fromFalsetoTrueas the program state changes.
5. Variable Reassignment and Execution Flow
Reassignment means changing which object a variable refers to as the program runs.
# Example: Tracing variable reassignment
status = "pending"
print("Initial status:", status)
status = "processing" # reassign
print("During process:", status)
status = "completed" # reassign again
print("Final status:", status)
# Output:
Initial status: pending
During process: processing
Final status: completed
How to predict behavior:
- Read the code in execution order (top to bottom).
- At each
=, update your mental model of what value the variable now holds. - Later expressions always use the latest value.
A common mistake is assuming a later change will retroactively update earlier calculations—it does not. Once a calculation is done and stored, changing the input variables does not change that stored result unless you explicitly recompute it.
6. Type Conversion When Assigning and Manipulating Variables
When data comes from input() or external sources, it’s often a string. To use it as a number or boolean, you must convert its type.
Common conversion functions:
int(x)– convert to integerfloat(x)– convert to floating‑pointstr(x)– convert to stringbool(x)– convert to boolean (non‑empty / non‑zero isTrue)
6.1 Converting on Assignment
# Example: Converting types on assignment
raw_age = "30" # imagine this came from input()
age = int(raw_age) # convert string to int
raw_price = "19.95"
price = float(raw_price) # convert string to float
print(type(age), age)
print(type(price), price)
# Output:
<class 'int'> 30
<class 'float'> 19.95
Explanation:
raw_ageandraw_priceare strings.int()andfloat()create new numeric objects; the variablesageandpricenow refer to those.
6.2 Using Type Conversion in Expressions
# Example: Combining input-like strings with numeric operations
quantity_text = "4"
unit_price_text = "5.50"
quantity = int(quantity_text)
unit_price = float(unit_price_text)
total_cost = quantity * unit_price
message = "Total cost: " + str(total_cost)
print(message)
# Output:
Total cost: 22.0
Explanation:
- We convert string representations of numbers into
intandfloatbefore doing arithmetic. - To concatenate with another string, we convert
total_costback to a string usingstr().
6.3 Booleans from Other Types
# Example: Boolean conversion
items_in_cart = 0
has_items = bool(items_in_cart)
print("Items in cart:", items_in_cart)
print("Has items:", has_items)
# Output:
Items in cart: 0
Has items: False
Explanation:
bool(0)isFalse, whileboolof any non‑zero number isTrue.- This pattern is useful when tracking empty vs non‑empty states.
Summary / Key Takeaways
In this lesson on Declaring and Using Variables, you have learned:
- Variables are names bound to objects created via assignment using the
=operator, with the expression evaluated on the right side. - Immutable types (e.g., int, float, str, bool) never change in place; reassignment makes the variable refer to a new object instead.
- Mutable types (e.g., list, dict) can be modified without changing the variable’s binding, which affects all references to the same object.
- Variables can store and update numeric, string, and boolean values, and their contents can evolve as the program executes.
- Reassignment overwrites the previous binding, so later expressions always use the most recent value of a variable.
- Stored results do not auto‑update when source variables change; you must explicitly recompute if you need updated calculations.
- Type conversion functions like
int(),float(),str(), andbool()are essential for safely transforming data between types when assigning and manipulating variables. - Planning variable types and conversions ahead of time helps avoid runtime errors and makes program behavior easier to predict and reason about.
