Applied Programming/Variables

What are variables?Edit

A variable is a named piece of computer memory, containing some information inside. Think of a variable as a box with a name, where we can "store" something. We create, edit, and delete variables, as much as we need in our tasks.[1]

In the following example, we create a variable with the identifier "my_variable" and store the number 13 within it. We then print out "my_variable" and receive the number 13 in return.

my_variable = 13
print(my_variable)
''>13''

How are they used?Edit

Variables are useful when you need to store, modify, or call information during the execution of programs. In essence, variables are the lifeblood of computer programming because they can store inputs and computational results. They allow for more flexibility in design and operation.

Types of variablesEdit

Local - A variable whose value is defined inside of a single function, and therefore is not accessible by other functions in the program.

Global - A variable whose value is defined outside of the functions, and therefore is accessible by all functions in the program.

Dynamic - A variable whose memory location is determined when the program runs.

Static - A variable whose memory is reserved for it during compilation.

Constant - A variable? While there are similarities between the two, a constant is markedly different in that its value never changes.

Data typesEdit

String - multiple characters that can include letters, numbers or special characters.

Integer - a whole number (no decimal or fraction)

Float - a number with or without a decimal; 32 bit precision (or accurate to approximately 8 decimal places)

Double - a number with or without a decimal; 64 bit precision (or accurate to approximately 16 decimal places)

Boolean - data type who’s value can only be true or false

Character - data type consisting of a single Unicode character

Mixed - any combination of the above data types

Declaring and initializing variablesEdit

The standard format for declaring and initializing a variable has the name identifier on the left and the value on the right. When you initialize the variable, you normally use the = symbol. It goes in between the name identifier and the value. Single whitespaces are used to separate the elements within the variable's declaration/initialization. This is done to increase code readability and understandability.[2] Here are some examples:

C++, C#, and Java

int veggies = 23;

Python

veggies = int(23)

PHP

$veggies = 23;

It is not always a requirement to initialize or give a value to a variable during the declaration. There may be circumstances when it is preferable to declare a variable without initializing it; perhaps the variable will hold a lot of data and it is wiser to conserve memory resources until necessary. An example in C++:

int veggies;

Different programming languages have their own naming conventions, some of these overlap. Here are some universal tips to keep in mind when creating variables:[3]

  • It is important to use descriptive names for variables.
  • Variable names must begin with a letter, underscore, or non-number character.
  • Do not use a comma for decimal numbers, only the period or point.
  • Every language has reserved words that cannot be used in variable names, for example, Date.

FunctionsEdit

Functions are structuring elements that simultaneously group and isolate portions of code. Within functions, variables are used for inputting and outputting data. If a function does not specify it, any calculations stored within variables will be lost if the function does not return the value upon conclusion. This is called the return statement. To do this in Python, the last line of the function definition simply states:

return something

Subsequent functions can use these return values if stated so within their definition by using a set of parenthesis, known as parameters. The variable holding the return values gets stated within the parameters. Like so:

def subsequent_function(something):

The return values or arguments stored within the variable 'something' can now be used by 'subsequent_function'. Functions are not required to have return values.

The timing or location of a variable's declaration/initialization within a program affect its operation. This applies to the concept of functional scope. For instance, a variable that is declared/initialized outside of the program's function sets becomes a global variable. All of the functions within a program will have access to use the global variables. Here's some food for thought:

sofritas = 1
guacamole = 1
 
 
def make_burrito():
    tortilla = 1
    veggies = 1
    rice = 2
    beans = 2
    burrito = guacamole + veggies + sofritas + rice + beans + tortilla
    return burrito
 
 
def make_taco():
    shell = 1
    lettuce = 1
    tomatoes = 1
    taco = guacamole + tomatoes + lettuce + sofritas + shell
    return taco
 
 
def make_dinner():
    burrito = make_burrito()
    taco = make_taco()
 
 
make_dinner()

In this Python example, the chef does not have access to lettuce and tomatoes when making the burrito. Likewise, the chef can't use veggies, rice, and beans for making the taco. These are examples of variables with local scope. The sofritas and guacamole represent global variables; the chef has access to both when making the burrito and the taco.

ActivitiesEdit

1. Create a variable named carname and assign the value Volvo to it.

2. Create a variable named x and assign the value 50 to it.

3. Display the sum of 5 + 10, using two variables: x and y.

4. Create a variable called z, assign x + y to it, and display the result.

5. Remove the illegal characters in the variable name:

    2my-first_name = "John"

6. Insert the correct syntax in the boxes to assign the same value to all three variables in one code line.

    x  y  z  "Orange"

7. Insert the correct keyword in the box to make the variable x belong to the global scope.

    def myfunc():
     x
    x = "fantastic"

[4]

Key TermsEdit

Arguments - The actual input expression passed/supplied to a function, procedure, or routine in the invocation/call statement.[5]

Array - A list or group of similar types of data values that are grouped.[6]

Assignment - Sets the value saved in the storage location denoted by a given variable name.[7]

Boolean - A data type having two values, typically denoted true and false.[8]

Constant - A value that cannot be altered by the program during normal execution.[9]

Data type - A classification of data which tells the compiler or interpreter how the programmer intends to use the data.[10]

Declaration - A language construct that specifies the properties of a given identifier.[11]

Double - A computer number format, usually occupying 64 bits in computer memory; it represents a wide dynamic range of numeric values by using a floating radix point.[12]

Dynamic variable - A variable whose address is determined when the program is run. [13]

Expression - A combination of one or more explicit values, constants, variables, operators, and functions that a programming language interprets and computes to produce another value.[14]

Floating point - The formulaic representation that approximates a real number to a fixed amount of significant digits.[15]

Function / Subroutine - A sequence of program instructions that performs a specific task, packaged as a unit.[16]

Global variable - A variable with global scope, meaning that it is visible (hence accessible) throughout the program, unless shadowed.[17]

Identifier - Tokens (also called symbols) which name the language entities (variables, types, labels, subroutines, and packages).[18]

Initialize - The assignment of an initial value for a data object or variable.[19]

Integer - A number that can be written without a fractional component.[20]

Local variable - A variable that is given local scope.[21]

Modulus - The remainder after division of one number by another.[22]

Naming conventions - A set of rules for choosing the character sequence to be used for identifiers which denote variables, types, functions, and other entities in source code and documentation.[23]

Objects - A combination of related variables, constants and other data structures which can be selected and manipulated together.[24]

Operator - A programming language construct that performs a calculation from zero or more input values to an output value.[25]

Order of operations - A collection of rules that reflect conventions about which procedures to perform first in order to evaluate a given mathematical expression.[26]

Parameters - A special kind of variable used in a subroutine to refer to one of the pieces of data (values) provided as input to the subroutine.[27]

Pointer - A variable that contains the address of a location in the memory. The location is the commencing point of an object, such as an element of the array or an integer.[28]

Program - As an organized collection of instructions, which when executed perform a specific task or function. It is processed by the central processing unit (CPU) of the computer before it is executed.[29]

Real number - A value that represents a quantity along a line, including integers, fractions, and irrational numbers.[30]

Reserved word - A word that cannot be used as an identifier, such as the name of a variable, function, or label – it is "reserved from use".[31]

Return statement - Code that causes execution to leave the current subroutine and resume at the point in the code immediately after the instruction which called the subroutine.[32]

Scope - The part of a program where the name binding is valid, that is where the name can be used to refer to the entity.[33]

Statement - The smallest standalone element of an imperative programming language that expresses some action to be carried out.[34]

Static variable - A variable that has been allocated "statically", meaning that its lifetime (or "extent") is the entire run of the program.[35]

String - A sequence of characters, either as a literal constant or as some kind of variable.[36]

Subroutine - A sequence of program instructions that performs a specific task, packaged as a unit.[16]

Variable - A storage location paired with an associated symbolic name (an identifier), which contains some known or unknown quantity of information referred to as a value.[37]

Whitespace character - A character that does not correspond to a visible mark, but typically does occupy an area on a page.[38]

ReferencesEdit

  1. https://en.wikiversity.org/wiki/Types_and_variables
  2. https://launchschool.com/books/ruby/read/variables
  3. https://www.kidscodecs.com/variables/
  4. https://www.w3schools.com/python/python_variables.asp
  5. Wikipedia: Parameter_(computer_programming)
  6. "Top Programming Terms and Definitions for Beginners [Updated"] (in en). https://hackr.io/blog/programming-terms-definitions-for-beginners. 
  7. Wikipedia: Type safety
  8. Wikipedia: Boolean data type
  9. Wikipedia: Constant (computer programming)
  10. Wikipedia: Data type
  11. Wikipedia: Declaration (computer programming)
  12. Wikipedia: Double-precision_floating-point_format
  13. "Dynamic Variable" (in en). https://www.webopedia.com/definitions/dynamic-variable/. 
  14. Wikipedia: Expression (computer science)
  15. Wikipedia: Floating point
  16. a b Wikipedia: Subroutine
  17. Wikipedia: Global_variable
  18. Wikipedia: Identifier_(computer_languages)
  19. Wikipedia: Initialization_(programming)
  20. Wikipedia: Integer
  21. Wikipedia: Local_variable
  22. Wikipedia: Modulo operation
  23. Wikipedia: Naming_convention_(programming)
  24. "Top Programming Terms and Definitions for Beginners [Updated"] (in en). https://hackr.io/blog/programming-terms-definitions-for-beginners. 
  25. Wikipedia: Operation (mathematics)
  26. Wikipedia: Order of operations
  27. Wikipedia: Parameter_(computer_programming)
  28. "Top Programming Terms and Definitions for Beginners [Updated"] (in en). https://hackr.io/blog/programming-terms-definitions-for-beginners. 
  29. "Top Programming Terms and Definitions for Beginners [Updated"] (in en). https://hackr.io/blog/programming-terms-definitions-for-beginners. 
  30. Wikipedia: Real number
  31. Wikipedia: Reserved_word
  32. Wikipedia: Return_statement
  33. Wikipedia: Scope_(computer_science)
  34. Wikipedia: Statement (computer science)
  35. Wikipedia: Static_variable
  36. Wikipedia: String (computer science)
  37. Wikipedia: Variable (computer science)
  38. Wikipedia: Whitespace_character