Python Variables
A variable is a named label that points to a value stored in your program's memory.
What is a variable?
In Python, a variable is created the moment you assign a value to it using the equals sign. There is no separate keyword to declare a variable and no need to state what kind of value it will hold. The name on the left of the equals sign becomes a reference to whatever value sits on the right, and you can read that value back simply by using the name later in your code.
Creating variables
age = 30
city = "Berlin"
price = 19.95
print(age)
print(city)
print(price)Because a variable is just a reference, you are free to reassign it at any time. The next assignment replaces the old reference, and Python does not complain even if the new value is a completely different type from the old one.
Reassigning and changing type
score = 100
print(score) # 100
score = "perfect"
print(score) # perfectText vs. numbers
Values wrapped in quotation marks are strings (text), while numbers are written without quotes. This distinction matters: the digits inside quotes are treated as characters rather than as a quantity you can do arithmetic with.
- Use single or double quotes for text values, for example name = "Ada".
- Write numbers without quotes so they behave as numeric values, for example count = 42.
- A variable holds only one value at a time; assigning again discards the previous value.
- You can display a variable's value with the built-in print() function.
Quotes decide the type
quantity = 5 # an integer
label = "5" # a string of one character
print(quantity + 1) # 6
print(label + "1") # 51Exercise: Python Variables
What must you do before assigning a value to a variable in Python?