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

  1. Make a variable name that contains your name.

  2. 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?

  3. Set x to 3 and y to 4. What do you think x + y will be? Try it out!

  4. Set x to "3" and y to "4". What do you think x + y will be? Try it out!