Bài trước: Python căn bản (4): Variables (cont)
-----
[Từ điển]
5. Python Data Types
5.1 Built-in Data Types
In programming, data type is an important concept.
Variables can store data of different types, and different types
can do different things.
Python has the following data types built-in by default, in these
categories:
- Text Type: str
- Numeric Types: int, float, complex
- Sequence Types: list, tuple, range
- Mapping Type: dict
- Set Types: set, frozenset
- Boolean Type: bool
- Binary Types: bytes, bytearray, memoryview
- None Type: NoneType
5.2 Getting the Data Type
You can get the data type of any object by using the type()
function:
Example
Print the data type of the variable x:
x = 5
print(type(x))
5.3 Setting the Data Type
In Python, the data type is set when you assign a value to a
variable:
Example Data
Type
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana",
"cherry"}) frozenset
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType
5.4 Setting the Specific Data Type
If you want to specify the data type, you can use the following
constructor functions:
Example Data
Type
x = str("Hello World") str
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = list(("apple", "banana",
"cherry")) list
x = tuple(("apple", "banana",
"cherry")) tuple
x = range(6) range
x = dict(name="John", age=36) dict
x = set(("apple", "banana",
"cherry")) set
x = frozenset(("apple", "banana",
"cherry")) frozenset
x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
5.5 Exercise
1. If x = 5, what is the correct syntax for printing the data type
of the variable x?
A. print(dtype(x))
B. print(type(x))
C. print(x.dtype())
D. print(d.type())
2. The following code example would print the data type of x, what
data type would that be?
x = 5
print(type(x))
A. float
B. double
C. int
D. number
3. The following code example would print the data type of x, what
data type would that be?
x = "Hello World"
print(type(x))
A. Text
B. str
C. String
D. data
4. The following code example would print the data type of x, what
data type would that be?
x = 20.5
print(type(x))
A. number
B. int
C. float
D. str
5. The following code example would print the data type of x, what
data type would that be?
x = ["apple", "banana", "cherry"]
print(type(x))
A. tuple
B. list
C. arr
D. set
6. We have a list of names, including Teo, Ti, Suu, Dan, Meo.
Let’s create a variable to store that list. Print list out screen.
-----
Cập nhật: 3/9/2024
Bài sau: Python căn bản (6): Python Numbers
-----
[Nội dung tham khảo từ w3schools, pynative và Internet]
Bạn muốn học Python căn bản tại Đà Lạt, liên hệ