Unit 3, Section 1.1: Data Types and Variables
Essential Knowledge (College Board's Must Knows):
- A variable is an abstraction inside a program that holds a value, where each variable has associated data storage that represents a single value at a time (However, if the value is a collection type such as a list, then the value can contain multiple values).
- Variables typically have meaningful names that helps with the overall organization of the code and understanding of what is being represented by the variables
- Some programming languages provide a variety of methods to represent data, which are referenced using variables (Booleans, numbers, lists, and strings)
- One form of a value is better suited for representation than another.
What is a Variable?
A variable is an abstraction made inside a program that holds a value. These variables are used in code to refer to more complex values that the variable contains and makes the program code more organized and smoother to run.
Variables can be seen as "containers" and each container has a name that holds what it is supposed to hold. In the following code, we can see that a variable has the value of "Alex." How can we make the variable appear more organized in the code?
x = "Alex"
print(x + "likes pie.")
# Make it so that "x" is easier to identify to the user
Choosing Variables
When choosing variables, it is important to assign the variables name to something that correlates with what the function of the variable is supposed to do. For example, we do not want a variable that is supposed to hold a name be named "age" becaue it can be confusing and mistakes may be more prevalent.
age = "Timothy"
name = "39"
# Notice how age is going to be seen when printing the code. That can lead to confusion
print(name + " is " + age)
Data Types
Variables have different data types that store specific kinds of data depending on what is being represented. Some examples are shown below:
- integer (numbers)
- string (or text/letters)
- Boolean (True/False statements)
These types of data types can be useful when trying to represent a value. For example, you would not want a variable meant to represent someone's name with an integer.
Questions (College Board's Essential Knowledge):
- What exactly IS a variable?
- What is the best data type to represent someone's dog's name?
- Why is it important to give variables specific names before containing values?
- What is the best way to represent someone's phone number?
Bonus (Not required but important to know):
- How can we update a variable's value
- What function is used to recieve a user's input?
Hacks
As your code becomes increasingly more complex, variables and their names will make reading and fixing your code easier.
Create code that...
- Uses variables
- Show your understanding of different variable data types by using at least 2 different types in your code
- Uses meaningful names to prevent confusion