Variables and Assignments

Essential Knowledge:

  • A variable is an abstraction inside a program that can hold a value. Each variable has associated data storage that represents one value at a time, but that value can be a list or other collection that in turn contains multiple values.
  • Using meaningful variable names helps with readability of program code and understanding of what values are represented by the variables.
  • Some programming languages provide types to represent data, which are referenced using variables. These types include numbers, Booleans, lists, and strings.
  • Some values are better suited to representation using one type of datum rather than another.

What is a variable

  • An abstraction inside a program that can hold a value

An example naming variables

  • You want to store the highest score you scored in a game. So, you want to call this variable highScore
  • You want to store a name, so you can call the variable firstName
  • It is also possible to store true or false in a variable. For example, the variable could be called isSunny, where true and false are stored in the variable.
  • phoneNumber could be a variable that stores phone numbers.
  • These examples are short and convenient as opposed to a long description
  • However, they give insight to the basic goal of the variable.
  • Spaces also cause a problem because it is not allowed
  • Dashes and numbers are also less ideal.

Data Type examples

  • highScore –> an integer
    • probably doing addition or subtraction, save it as an integer or numbers.
  • firstName –> text(or string)
    • since a name is text, it should be saved as a string
  • isSunny –> boolean
    • only gives two options: true or false within variable
  • phoneNumber –> text(string)
    • no math involved just a string of numbers

Practice

Question: What would be the best variable name and data type to store a user’s age in a program?

  • Answer: name: age data type: integer Q: What would be the best variable name and data type to store the number of students in your class?
  • A: name: numStudents data type: integer to add and subtract Q: What would be the best variable name and data type to store the title of a movie?
  • A: name: movieTitle data type: text(or string) Q: What would be the best variable name and data type to store if someone’s pet is a dog. A: name: isDog data type: boolean

Possible Hacks

Go through the following examples and with your table discuss the best variable name and the data type for each situation and stored variable:

  • You want to store the best price for apples.
  • You are storing true or false in a variable that asks if the classroom is cold.
  • How do you store the ID numbers for the students in the classroom?