Variables
A variable is a named container that holds a data value.
Creating Variables
You don't declare a variable in Python with any special command. It comes into being the first time you give it a value. You don't state a type for it either, and the same variable can later hold a value of a different type.
Example
Prompt
Create a variable x with value 5 and a variable y with value "John", then print both.
Output: complete Python program
main.py
x = 5
y = "John"
print(x)
print(y)
Change type
No type is declared here, and x switches from a number to a string:
Prompt
Create a variable x with value 4 (int), then change it to "Sally" (str), and print x.
Output: complete Python program
main.py
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Casting
Casting lets you choose a variable's data type yourself.
Example
Prompt
Create three variables using casting: x as str(3), y as int(3), z as float(3), then print all three.
Output: complete Python program
main.py
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
print(x)
print(y)
print(z)
Get the Type
The type() function tells you what data type a variable holds.
Example
Prompt
Create a variable x with value 5 and y with value "John", then print the type of each using the type() function.
Output: complete Python program
main.py
x = 5
y = "John"
print(type(x))
print(type(y))
Single or Double Quotes?
Both single and double quotes work for creating a string variable:
Example
Prompt
Show that string variables can be declared with either double or single quotes by assigning "John" both ways.
Output: complete Python program
main.py
x = "John"
# is the same as
x = 'John'
print(x)
Case-Sensitive
Case matters in variable names, so a and A are not the same.
Example
Here you get two separate variables:
Prompt
Demonstrate that variable names are case-sensitive by creating a = 4 and A = "Sally", then print both to show they are different variables.
Output: complete Python program
main.py
a = 4
A = "Sally"
#A will not overwrite a
print(a)
print(A)