Variables
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.
Examples
For example, this line of code creates a variable named price
and stores the
number 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
print(my_number)
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
fruit
.
Terminology
Here's the code again that defines the price
variable:
price = 39
Here, price
is the name of the
variable, and 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 +
or *
.
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 price
.
In the second line of code, store the number 113
in a variable named
amount
.
In the third line of code, calculate price * amount
and store it in a
variable named total
.
In the fourth line of code, print the value in the total
variable.
Variable names
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"
Terminology practice
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 "moon"
.
The second line of code should be a variable assignment with the name word2
and the value "light"
.
The third line should use +
to concatenate word1
and word2
and store the
result into a variable named combination
.
The fourth line should print the value stored in the combination
variable.