Last time we covered writing variables in Python. This time we'll go further into the data types you'll use on Python variables.
Here we go...
What Is a Data Type?
A data type is an attribute given to a variable to mark which operations can be done to that variable.
A variable with one data type won't agree to sit next to a variable with another type. The simplest example is adding a number to text, say 1 + "satu". The code you write errors out right away.
>>> a = 1 + "satu"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
See that? The highlighted part shows the error unsuported operand. That happens because the addition operator (+) doesn't support an operation between a number and text.
The Kinds of Data Types in Python
Python knows several data types, among them:
- Numeric type:
int,float,complex - Text type:
str - Logic type:
bool - List type:
tuple,range,list,dict
For now it's enough to know the kinds of data types Python has. The details on each type we'll cover on another occasion.
How to Find a Variable's Data Type
To find the data type of a variable you made, you can use the type() command. It takes a variable or a value whose data type you want to know.
>>> nama = "Budi"
>>> bulat = 3
>>> pecahan = 0.9
>>> type(nama)
<class 'str'>
>>> type(bulat)
<class 'int'>
>>> type(pecahan)
<class 'float'>
The output of that function is the data type of the variable you passed in. You can see it above. The data type sits inside quotation marks, after the class keyword.
Wrapping Up
That's it for this one, hope it helps...
Next time we'll look further into numeric data in Python. See ya...