All programming languages have a way of storing certain types of information in variables. Certain data types or needed for one situation and different data types for another. It is important to know the differences in the data types otherwise serious problems could arise when developing an application. In this post, we will look at some of the more commonly used data types in Python.
variable name = data inside the variable
You simply type a name, use the equal sign, and then include the data to be saved in the variable. Below is an example where I save the number 3 inside a variable called “example”
example=3 print(example) 3
The “print” function was used to display the contents of the “example” variable.
There are two commonly used numeric data types in Python and they are integers and floating point values.
Integers are simply whole positive or negative numbers. To specifically save a number as an integer you place the number inside the “int” before saving as a variable as in the example below.
example=int(3) print(example) 3
You can check the data type by using the “type” function on your variable. This is shown below.
type(example) Out: int
The results are “int” which stands for integer.
Floating-point numbers are numbers with decimals. If your number includes a decimal it will automatically be stored as a floating type. If your number is a whole number and you want to save it as a floating type you need to use the “float” function when storing the data. Below are examples of both
#This is an example of a float number example=3.23 print(example) 3.23 #This is an example of converting a whole number to a floating point example=float(3) print(example) 3.0
Floating points can store exponent numbers using scientific notation. Floating point numbers are used because decimals are part of the real world. The downside is they use a lot of memory compared to integers.
We will look at two additional data types and they are boolean and string.
A boolean variable only has two possible values which are True or False. This seems useless but it is powerful when it is time to have your application do things based on conditions. You are not really limited to True or False you can also type in mathematical expressions that Python evaluates. Below are some examples.
#Variable set to True example=True print(example) True #Variable set to True after evaluting an expression example=1<2 print(example) True
A string is a variable that contains text. The text is always enclosed in quotations and can be numbers, text, or a combination of both.
example="ERT is an awesome blog" print(example) ERT is an awesome blog
Programming is essentially about rearranging data for various purposes. Therefore, it only makes sense that there would be different ways to store data. This post provides some common forms in which data can manifest itself while using Python.