Teach Your Kids To Code: A Parent-friendly Guide to Python Programming

(vip2019) #1

32 Chapter 3


Variables: Where We Keep Our Stuff


In Chapters 1 and 2, we used a few variables (you might remem-
ber name from our first program in Chapter 1 or x and sides from
Chapter 2). Now let’s look at what variables really are and how
they work.
A variable is something you want the computer to remem-
ber while your program is running. When Python “remembers”
something, it’s storing that information in the computer’s memory.
Python can remember values of several types, including number
values (like 7 , 42 , or even 98.6) and strings (letters, symbols, words,
sentences, or anything you can type on the keyboard and then
some). In Python, as in most modern programming languages, we
assign a value to a variable with the equal sign (=). An assignment
like x = 7 tells the computer to remember the number 7 and give
it back to us anytime we call out x. We also use the equal sign to
assign a string of keyboard characters to a variable; we just have to
remember to put quotation marks (") around the string, like this:

my_name = "Bryson"

Here, we assign the value "Bryson" to the variable my_name.
The quotation marks around "Bryson" tell us that it is a string.
Whenever you assign a value to a variable, you write the
name of the variable first, to the left of the equal sign, and then
write the value to the right of the equal sign. We name variables
something simple that describes their contents (like my_name when
I’m storing my name) so we can easily
remember them and use them in our
programs. There are a few rules to
keep in mind as we make up names
for variables.
First, we always begin variable
names with a letter. Second, the rest
of the characters in the variable name
must be letters, numbers, or the under-
score symbol ( _ ); that means you can’t
have a space inside a variable name
(for example, my name will give you a
syntax error because Python thinks
Free download pdf