Variables
Who has done Algebra before? Algebra involves variables. Programming also involves variables, though instead of "solving for x" we're usually assigning a variable to a value.
Just like any other programming language, Python also has variables.
>>> x = 4
>>> x * 3
12
Variables can contain any of the types we've covered so far: strings, floats, integers…just about anything can be shoved in a variable. When we assign a value to a variable we can do other things with that variable without having to explicitly state their values.
So, variables can be used just like any other value:
>>> socks = 2
>>> shirts = 1
>>> shorts = 1
>>> clothing = socks + shirts + shorts
>>> clothing
4
Variable Exercises
Make a variable
name
that contains your name.Make a variable called
x
and assign it to a number. Now assign it to a string instead. Did that work? Did its value change?Set
x
to3
andy
to4
. What do you thinkx + y
will be? Try it out!Set
x
to"3"
andy
to"4"
. What do you thinkx + y
will be? Try it out!