Python Variables and Data Types
Variables
Variables are containers for storing values. In Python, you can easily declare variables by assigning a value to a name. Variables do not need to be declared with any keywords or specified data types, python will figure out those parts.
Here are some examples of variables. We encourage you to type out the code below for practice. Also, you can print out the variables to check what values were stored in them.
Data Types
Variables can store data of differnt types and the char below categorizes these data types into seven categories.
str - stands for string. Strings are any values wrapped in single or double quotes like 'Amy' or "park".
int - stands for integer. Examples of integers are 67, 0, -15.
float - stands for decimal. Examples of decimals are 0.16, 3.4, -0.99.
complex - represent a mix of real and imaginary numbers. Examples of compex numbers are 1j, 2 + 4j.
list - an ordered, changeable data abstraction used to store values. Surrounded by two square brackets. An example of a list is [1, -0.8, 'A', True].
tuple - an ordered and unchangeable data abstraction stored to store values. Surrounded by two parenthesis. An example of a tuple is (1,-0.8, 'A', True).
dict - an ordered, changeable data abstraction used to store key:value pairs. Surrounded by curly braces. An example of a dictionary is {name:'Sam', grade:10, city:'New Jersey'}
set - an unordered and unindexed data abstraction used to store values. An example of a set is {'apples','bananas','cherries'}
The other data types are quite uncommon, especially for students who are just starting out with computer science so we will not delve into them. You will learn about these data types in more detail in future lessons, right now we are just hitting the tip of the iceberg.
You can find the data type of the value assigned to a variable by using the type() function. Pass in the variable as a parameter and it will return the appropriate data type
Casting
Casting is the process of changing the data types of variables
str(x) will turn the data type of x to a string.
int(x) will turn the data type of x to an integer
float(x) will turn the data type of x to a float
Concatenation
Concatenation is the process of combining or adding two variables. The variables you add must be of the same data type or else the computer will throw an error.
So, do not add integers to strings. Use the str() keyword to convert the integers to strings before adding them together. Similiarly, don't add booleans to strings. You can add booleans to integers though its still good coding practice to convert them both to one data type.
If you don't like casting and find it to be unnecessarily tedious, you can use f-strings instead.