Python - Variables

In Python we need to create variables that will store data that we want to use in our programs.

To declare a variable we simply choose a sensible name and assign it a value.

Take a look at some of the examples below, do you notice anything different about the middle one:

pet = "dog"

age = 14

bestFriend = "Bart"

We must give variables sensible names so that we can use them within our code. There are some rules you must follow when choosing variable names.

  • variable names cannot start with a number e.g 1stCalculation

  • variable names cannot have spaces e.g my variable

  • variable names cannot be reserved words e.g print

When you want to use two words in your variable name we can use camel case (a capital letter for each word) to show the break between words. For example if you wanted to create a variable called total numbers, you could call your variable totalNumbers. Other examples may be myFirstNumber, totalNumberStudents

Variables can only hold one type of data. This means we have to carefully choose the most suitable data type for each piece of data we store.

The most common types of variable are:

In a Python window you could create the variables and assign each variable some sample data. e.g.

What is different about firstName, age and enjoySchool?

Watch the video below for an explanation of variables

pythonVariables.mp4

Constants

Python does not have a method of declaring constants, so be careful not to change the value of any variable you use to store a constant value.