Variables and Data Types in Python
A variable in Python is a name that refers to a value stored in memory. Variables allow you to store, retrieve, and manipulate data in your programs. You assign a value to a variable using the equals sign ($=$).
A data type specifies the kind of value a variable holds. Python is a dynamically-typed language, so you do not need to declare the data type explicitly; Python infers it at runtime.
Common data types in Python include:
- int: Integer numbers (e.g., $5$, $-3$) - **float**: Floating-point (decimal) numbers (e.g., $3.14$, $-0.5$) - **str**: Strings, or sequences of characters (e.g., `"hello"`) - **bool**: Boolean values ($text{True}$ or $text{False}$)
- Multiply price by quantity:
- Substitute the values:
- Assign the result to a variable:
- Variables are names that store values; their data type depends on the value assigned.
- Python supports several basic data types, including int, float, str, and bool.
- You can perform operations with variables according to their data types.
Worked Example
Suppose you want to store and manipulate the price of an item:
``python`
price = 19.99 # float
quantity = 3 # int
item_name = "Book" # str
in_stock = True # bool
Let's calculate the total cost:
$$ \text{total_cost} = \text{price} \times \text{quantity} $$
$$ \text{total_cost} = 19.99 \times 3 = 59.97 $$
`python``
total_cost = price * quantity # 59.97