What is a variable?
A variable is a storage place that holds a value.
In other words, a variable lets you store a value, such as a number or string, in a place that you can refer back to using a name that you choose.
The value that is stored can vary -- hence the term variable.
For example, this line of code creates a variable named
price and stores the
39 in it:
price = 39
And this code creates a variable named
username and stores the string
"bob1964" in it:
username = "bob1964"
A variable is one of the basic concepts you'll need in nearly every program you write.
Try storing a number
This program defines and then prints a variable:
my_number = 123
Try changing the program to instead store the number
999 in the variable
before it is printed.
Create a variable from scratch
Write a line of code that stores the string
"apple" into a variable named
Here's the code again that defines the
price = 39
price is the name of the
39 is the value of the variable.
Storing a value into a variable is called a variable assignment.
More complex variable assignments
The right-hand side of a variable assignment can be a number, a string, or
another variable. It can even be an expression using
These are all valid variable assignments:
a = 100
b = a + a
c = b*3
x = "test"
y = x + x
Using multiple variables
Write a program consisting of four lines of code.
In the first line of code, store the number
20 in a variable named
In the second line of code, store the number
113 in a variable named
In the third line of code, calculate
price * amount and store it in a
In the fourth line of code, print the value in the
You can give a variable almost any name you want. For example, these lines are all valid Python code:
myVar = 123
x = 42
UPPERCASE = 1
empty_string = ""
However variable names cannot contain spaces.
Python programmers normally use all-lowercase names with underscores in place of spaces, such as in this example:
user_password = "secret"
Let's practice using the terminology for variables.
Write a program with four lines of code.
The first line of code should be a variable assignment. The variable should
have the name
word1 and the value
The second line of code should be a variable assignment with the name
and the value
The third line should use
+ to concatenate
word2 and store the
result into a variable named
The fourth line should print the value stored in the