Python Variables

picture of python with python logo in corner

Python variables are loosely-typed. Variables store your data in memory while your program is running and make it easier to read and write Python code.

Variables are what make a computer more useful than a calculator!

Let’s say that you have 4 apples, 4 oranges, and 4 bananas. You could add up all your fruit on a calculator (or in the python IDLE) like this:

code snippet for Python program without variables

But what if you got more apples? Which number in that equation should change? What if you also wanted a total of red items in your kitchen? Variables help keep track of which number belongs to what kind of thing you are working with.

Let’s try this again using variables:

code sample demonstrating python variables from jupyter notebook

Behind the scenes Python is creating a storage space in memory for the number that goes into each of these variables and it keeps track of which name belongs to which spot in memory. It’s like putting labels on your boxes when you move. When you get to your new home, it’s a lot easier to unpack.

Rules for Python variables:

  • variable names are case-sensitive: apples is not the same as APPLES, or Apples
  • your programs will be easier to understand if you use descriptive variable names (apples instead of a)
  • if you need to use more than one word python programmers prefer to use “snake_case” to name their variables, as in: red_apples, green_apples, yellow_apples.
  • you may encounter variations of camel case variables if you read programs written in other languages or by programmers who know other languages
    • lowerCamelCase: redApples, greenApples, yellowApples
    • UpperCamelCase: RedApples, GreenApples, YellowApples (also sometimes called PascalCase after a programming language that no one uses anymore)
  • variables can store more than just numbers, for example:
    • name = ‘Curious George’
    • is_animal = True