Storing data in variables

Table of Contents


1. Introduction

We use variables in programming as places to temporarily store data so that we can manipulate that data. We can have the user write to it via the keyboard, we can use files to write data to variables, we can do math operations or modify these variables, and we can print them back out to the screen or a text file.

Variables can store many different types of data, with the most basic types being integers (whole numbers) floats (numbers with decimal portions), strings ("text within double quotes"), characters (a single number, letter, or symbol, usually stored in 's'ingle 'q'uotes), and booleans (true/false).

2. Types of data

The term data type refers to the type of data that is stored within a variable. For some programming languages, the data type is figured out via context and we don't have to specify what the type is in our code (Python, Lua), but with statically typed languages, we must declare a variable and its type before using it.

Some of the most basic data types and example values are:

Data type Description C++ example Python example Lua example
integer whole numbers int age=100; age=100 age=100
float numbers w/ decimals float price=9.95; price=9.95 price=9.95
boolean true or false bool saved=true; saved=True saved=true
string text, numbers, symbols, within double quotes string name = "asdf"    

In C++, string values must be within double quotes and characters within single quotes:

string name="Pixel";
char currency='$';

And Python and Lua can work with characters but generally you work with everything as a string, so you can write your strings in double quotes or single quotes:


3. Creating variables

Assignment statements allow us to store data within a variable. It takes this form:


In Python and Lua you can create a variable by simply writing an assignment statement, creating a new variable name (or reusing an existing one), and setting it equal to some data…

print( "I need a variable to store how much money I have..." )
my_money = 123.45
print( "I have", my_money )

In C++, variables must be declared before or while being assigned, and their data type must be specified, and the statement will end with a semicolon ;

Declare without assignment
Declare with assignment
Assignment (after declaration)
cout << "I need a variable to store how much money I have..." << endl;
float my_money = 123.45;
cout << "I have " << my_money << endl;

4. Assigning values to variables

Once a variable has been declared (in C++) or assigned a value (Python/Lua), then it will continue existing in that context. You can keep using the variable, such as for usage in math operations, and you can overwrite the value being stored in that variable as well.

When assigning a value to a variable, the variable being assigned to always goes on the left-hand side ("LHS") of the equal sign. Here, the equal sign = is known as the assignment operator. On the right-hand side ("RHS") of the equal sign you can use a literal to assign a specific value, or include an expression, such as a math operation, whose result will then be stored in the variable.

Python/Lua assignment statement
C++ assignment statement

4.1. Assigning literal values to variables


A literal is an actual number or string that you're hard-coding into the program, such as below:

Description Python/Lua C++
Assigning a float literal to the price variable price = 9.76 price = 9.76;
Assigning a string literal to the state variable state = "Kansas" state = "Kansas";

4.2. Copying data between variables


If you have variables on both sides of the equal sign, then the value from the RHS gets copied to the variable on the LHS:

Description Python/Lua C++
Copy value from book_price to price variable price = book_price price = book_price;
Copy value from college_state to state variable state = college_state state = college_state;

4.3. Storing the result of a math operation in a variable


The RHS may have a mathematical expression. The program will compute the result of that operation and store the result in the variable on the LHS.

Description Python/Lua C++
Evaluate math expression and store result in price variable price = price1 + price2 price = price1 + price2;

You can even do math on a variable and assign the result back to the same variable…

Description Python/Lua C++
Add 1 to counter and store the result in the counter variable. counter = counter+1 counter = counter+1;


cat_count = 1
print( "I have", cat_count, "cat(s)" )
print( "..." )
print( "Oops, adopted another cat!" )
cat_count = cat_count + 1
print( "I have", cat_count, "cat(s)" )


int cat_count = 1
cout << "I have", cat_count, "cat(s)" << endl;
cout << "..." << endl;
cout << "Oops, adopted another cat!" << endl;
cat_count = cat_count + 1;
cout <<  "I have", cat_count, "cat(s)" << endl;

5. Named constants

A named constant looks similar to a variable in that it is a place to store data and it has a name, however the value of a named constant cannot (or should not) change after its initialization. With C++, this is enforced by using the const keyword, though with Lua and Python, the language itself does not enforce the const-ness.

Description Python/Lua C++
Create named constant VERSION_NUM VERSION_NUM = 1.23 const VERSION_NUM = 1.23;

Named constanst are useful because we may have some data we want to use in the program in various places, but if we hard-coded that value (like 1.23), we would then have to update every occurrence of that number if we were going to change it. Additionally, someone unfamiliar with that section of code might go, "1.23? What does that mean??". By using named constants, you can refer to it throughout the program by name - which is descriptive of what it is - and when you need to update it, you just update one location - the original declaration.

6. Naming conventions

You can name a variable anything you’d like - but it can only contain numbers, underscore _, and upper- and lower-case letters in the name. Variable names can begin with the underscore or a letter, but it cannot start with a number. And definitely NO spaces allowed in a variable name!

Additionally, a variable name cannot be a keyword - a name reserved for something else in the language, such as if, int, etc.

Most programming languages, including C++, Python, and Lua, are case sensitive as well, which means if you name a variable username, it will be a different variable from one named userName (or if you type userName when the variable is called username, the compiler/interpreter will complain at you because it doesn’t know what you mean).

There is no "official" style, and you may encounter lower_case_with_underscores style or camelCaseWords style. The main thing is to be consistent.
There doesn't seem to be a specific naming convention, but as with above, just be consistent.

7. Working with variables

As you build a program you will be utilizing variables in different ways…

7.1. Display variable values

We can use our language's display functionality to display the value of a variable. When we do this, it is good to include a label before the variable's value so the user knows what is being communicated.

Description Python/Lua C++
Display value of variable price print( price ) cout << price;
Display label and value of price print( "Price:", price ) cout << "Price: " << price << endl;

7.2. Storing user input in a variable

We may also ask the user to enter some data, which we will then store within a variable. For types like integers and floats, this can be pretty simple. With Python, we have the input function, which allows us to display a question or prompt before the user enters their selection. For Lua and C++, we will need to use a display command (print/cout) to display the question or prompt first, and then get the user's input second.

Getting input in Python:

name = input( "What is the name of the product? " )
quantity = int( input( "How many products do we have? " ) )
price = float( input( "What is the price of the product? " ) )

With Python, input gives us a string by default. To make sure we're getting an integer, we need to wrap the input( ) function with the int( ) function. Similarly, for floats, we need to surround input( ) with the float( ) function.

Getting input in Lua:

print( "What is the name of the product?" )
name = "*l" )
print( "How many products do we have?" )
quantity = "*n" )
print( "What is the price of the product?" )
price = "*n" )

With Lua, we use the function. Within the double quotes, we specify what type of information we are reading. *l means "line", and will allow us to read in text with spaces. *n means "number", and will allow us to read integers and floats.

Getting input in C++:

string name;
cout << "What is the name of the product? ";
getline( cin, name );

int quantity;
cout << "How many products do we have? ";
cin >> quantity;

float price;
cout << "What is the price of the product? ";
cin >> price;

With C++, we use cin to get input from the console. For lines of strings, we need to use the special getline( ) function, with cin as the first item and our variable name as the second. With integers and floats, we can use cin >> to read values into those variables.

We will cover more with getting input from the keyboard in a later lesson.

7.3. Performing math operations

We can perform math computations with our variables and with numeric literals. The most common operations are:

Operation Symbol Example
Addition + z = x+y
Subtraction - z = x-y
Multiplication * z = x*y
Division / z = x/y

Make sure to put the result somewhere! When you do a math operation and you want to use the result elseware in the program, make sure you’re storing the result in a variable via an assignment statement! If you just do this, nothing will happen:

total_cats + 1;

You can use an assignment statement to store the result in a new variable…

new_total = total_cats + 1;

Or overwrite the variable you’re working with…

total_cats = total_cats + 1;

7.3.1. Compound operations

Compound operations: There are also shortcut operations you can use to quickly do some math and overwrite the original variable. This works with each of the arithmetic operations:

In C++:

total_cats = total_cats + 1;
total_cats += 1;

Each of these add 1 to the total_cats variable. With the top two lines, we could change 1 to be any other number to add multiple to the variable.

In Python:

total_cats = total_cats + 1
total_cats += 1

Python doesn't support the ++ operation to add 1 to a variable, and Lua doesn't support that nor the += command.

In addition to += to add onto a variable, we can also use -= to subtract a value, *= to multiply a value, and /= to divide a value.

7.4. Working with text strings

If we have two variables storing string values and we use the + operator on them, we will concatenate them - or combine them - together, in C++ and Python:

flavor = "chocolate";
dessert = "ice cream";
food = flavor + " " + dessert;

With the above, we will get the result "chocolate ice cream" stored in the food variable. This works the same with Python, except you don't need the semicolons ; at the end of the statements.

For Lua, the .. operator is used to concatenate:

flavor = "chocolate"
dessert = "cake"
food = flavor .. " " .. dessert

Author: Rachel Wil Sha Singh

Created: 2023-10-20 Fri 21:24