Variables and Values
In Python, we have variables and values. Think of a variable as a box, and a value as something that goes inside the box. Here is an example of a variable and its value:
animal = “cat”
In this case, animal
is the variable, and “cat”
is its value. In fact, it is a specific type of value--a string. A value that has letters or characters and no numbers is a string type value. We put strings inside quotation marks. When we write a variable, we are declaring the variable.
In this case, we can say that we are assigning the value of “cat”
to the variable animal. The =
is called the assignment operator. It’s not an “equals” sign in the sense that 2 = 2, but it does convey a relationship. We are basically saying that animal
represents “cat”
. That means that when we do something with animal
, we are doing something with “cat”
.
For example, look at this code:
print(animal)
The print
function tells the program to print, or display, something in the output area of our code editor. (A function is an action that we can do in Python.) Keeping in mind that animal
represents “cat”
, what do you think we’ll see if we print the value of animal?
Try it yourself: In the code editor on the right, declare a variable called animal
. Then assign it a value, like “cat”
(or another animal, if you’re not a cat person). Then tell the program to print the variable. Click the large gray triangle button at the top of the editor to run your program and see the results!
You can also have multiple words as part of a single value. For example:
favorite_song = “Somewhere Over the Rainbow”
Try typing the above code in the editor and then printing favorite_song
.
Note that variable names are lowercase. Use underscores when you need to include multiple words, as in favorite_song
, cat_name
, and so on.
Sometimes we might want to have more than one value assigned to a variable. We might want to have a list of values, for instance. In Python, we can make a list, also called an array. For example:
animal = [“cat”, “dog”, “bird”, “fish”]
“Cat”
, “dog”
, “bird”
, and “fish”
are all values in the array. In this example, they are all single-word strings. But you can have multiple-word strings as values in an array, as well:
favorite_songs = [“Somewhere Over the Rainbow”, “Happy Birthday”, “Imagine”]
What do you think would be the result if you typed the above line of code in your code editor and then printed favorite_songs
? Try it and see!