VARIABLES & ASSIGNMENTS

Variables are one of the most important concepts in programming, and you will certainly be using them in every useful program you write. Variables are like labels, or names, for the numbers, strings and other values in your programs. Variables are used for keeping track of all the facts and figures you use throughout your code.

Variables can be given any name you choose (although there are some rules to that!) Choosing good variable names makes it easier to write your code, to change your code later and to help others understand your code.

The definition of "variable" is something that can vary (change), and that's what program variables do throughout a program. To assign a variable a value, you use the equals sign in what is called an assignment statement, which looks like:



To change it to a different value, you also use another assignment statement:



A variable can be any type of value, including a number, a phrase, the results of a calculation, or a list.

Variables Can Be Numbers

As an example, we'll calculate the number of seconds in a day. To do do this, we'll start by creating a variable called “sec_in_minute” that will be the number of seconds in a minute (which is 60):



Note: When naming variables, you can use any combination of uppercase letters, lowercase letters, numbers and underscore characters (_). The only rule is that the variable name must start with a letter. It’s good practice to use variable names that make your code easier to understand and read.

Now, let’s create two more variables:



We can now compute (and print) the number of seconds in a day with:



The asterisk ('*') is a multiplication symbol - see the CALCULATIONS project for more information.

Here is what the output would look like if you ran that code:


86400

Variables Can Be Assigned the Value of Other Variables

Remember we said above that variables can be almost any type of data – that includes data from other variables. We can take our program one step further by creating a variable called sec_in_day and using it to be our calculation for the number of seconds in a day:



Now, if you want to output the number of seconds in a day, you can simply print the number being held by the sec_in_day variable:



This is what the output would look like:


86400

Variables Can Be Strings

Variables can also be strings. For example, we could have a variable that holds one of the output message we’re using above:



We could then print that message to the output, along with our calculation:



Here is what the code and output would look like using a variable for the text string:


Number of seconds in a day: 86400

Note that because message is now a variable, we don’t put quotation marks around it.

home