6. Kiểu dữ liệu số nguyên
Bạn chắc chắn đã sử dụng máy tính cầm tay (calculator) khi thực hiện các phép tính trong môn toán, như: cộng, trừ, nhân, chia. Máy tính (computer) là một thiết bị thông minh hơn, nên nó cũng sẽ thực hiện được các tính toán như vậy.
Chúng ta cùng sử dụng ngôn ngữ Python để ra lệnh cho máy tính làm một số phép toán số học.
6.1 Phép toán số học
Để đơn giản, chúng ta sẽ sử dụng chế độ ra lệnh trực tiếp cho Python.
Trong cửa sổ dòng lệnh (CMD), gõ lệnh py (hoặc python) để vào chế độ nhập lệnh. Hoặc bạn cũng có thể nhập lệnh vào cửa sổ IDLE Shell.
Nhập cách lệnh sau, quan sát kết quả, bạn có thể tính lại bằng tay, để kiểm tra xem máy tính có làm đúng không?
Phép cộng
3 + 5
Ví dụ:
Microsoft Windows [Version 10.0.19045.5608]
(c) Microsoft Corporation. All rights reserved.
C:\Users\Teo>py
Python 3.13.2 (tags/v3.13.2:4f8bb39, Feb 4 2025, 15:23:48) [MSC v.1942 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 3 + 5
8
Phép trừ
10 - 4
# kết quả: 6
Phép nhân
3 * 5
# kết quả: 15
Phép chia
18 / 3
# kết quả: 6.0
Vậy là bạn đã biết cách dùng ngôn ngữ Python để ra lệnh cho máy tính thực hiện các phép tính: cộng, trừ, nhân chia. Thật đơn giản phải không.
Nếu tinh ý, bạn sẽ thấy kết quả trong phép tính chia là 6.0, đây là “có vẻ” là một số thập phân; trong khi kết quả của các phép cộng, trừ, nhân là các số nguyên.
Lý do có hiện tượng trên là do trong Python có 2 loại số, là số nguyên (integer) và số thực (decimal, float, double).
6.2 Số nguyên
Số nguyên (integer) là một tập hợp các số không có phần thập phân hoặc phần lẻ, bao gồm:
- Số dương (positive integers): ví dụ 1, 2, 3,
- Số âm (negative integers): ví dụ -1, -2, -3,
- Số 0 (zero): 0.
Trong toán học, số nguyên được ký hiệu là ℤ (từ "Zahl" trong tiếng Đức, nghĩa là "số"). Đây là một tập con của số thực (real numbers), nhưng khác với số thực ở chỗ số nguyên không bao gồm số thập phân (như 2.5) hay số vô tỉ (như √2).
Đặc điểm của số nguyên:
- Không có phần thập phân hoặc phân số.
- Có thể là số âm, số dương, hoặc bằng 0.
- Được dùng để đếm các vật thể rời rạc (discrete) hoặc biểu thị sự thay đổi (tăng/giảm).
Số nguyên xuất hiện trong cuộc sống hàng ngày:
- Đếm số lượng: “Tôi có 5 quả táo" (5 là số nguyên dương).
- Nhiệt độ: "Nhiệt độ là -3°C" (-3 là số nguyên âm).
- Vị trí: "Tôi đang đứng ở Km số 0 của đường quốc lộ 1" (0 là số nguyên).
Kiểu dữ liệu số nguyên trong Python là gì?
Trong Python, số nguyên (integer) là một kiểu dữ liệu cơ bản dùng để biểu diễn các số không có phần thập phân, bao gồm:
- Số nguyên dương (positive integers): 1, 2, 3,
- Số nguyên âm (negative integers): -1, -2, -3,
- Số 0: 0.
Kiểu dữ liệu số nguyên trong Python được ký hiệu là int. Nó thuộc nhóm kiểu dữ liệu số (numeric types), cùng với float (số thực) và complex (số phức).
Đặc điểm nổi bật của kiểu int trong Python
[1] Không giới hạn kích thước
- Khác với nhiều ngôn ngữ lập trình khác (như C, Java) giới hạn kích thước số nguyên (32-bit, 64-bit), trong Python, kiểu int có thể biểu diễn số nguyên với kích thước bất kỳ, miễn là máy tính có đủ bộ nhớ.
- Điều này nhờ vào cách Python quản lý bộ nhớ động (dynamic memory allocation).
[2] Không phân biệt các kiểu: int, long hay short
- Python không phân biệt int, long, hay short như C/C++. Tất cả số nguyên đều là int, và Python tự động điều chỉnh kích thước theo giá trị.
[3] Hỗ trợ các phép toán cơ bản
- Cộng (+), trừ (-), nhân (*), chia lấy nguyên (//), chia lấy dư (%), lũy thừa (**)
Khai báo
- Bạn chỉ cần nhập một số, không có phần thập phân; hoặc gán một giá trị số, không có phần thập phân cho biến, Python sẽ tự nhận diện nó là int
- Không cần khai báo kiểu dữ liệu
Sử dụng
Ở phần đầu bài học, bạn đã sử dụng các phép toán: cộng, trừ, nhân và chia trên các số nguyên.
Phần này, chúng ta cùng tìm hiểu thêm một số phép tính khác.
- Chia lấy phần nguyên (floor division): là phép chia chỉ lấy phần nguyên của kết quả, mà không lấy phần thập phân. Ví dụ: 5 : 3 = 1.666, chúng ta chỉ lấy phần nguyên là 1; không lấy phần thập phân là .666
5 // 3
# kết quả: 1
- Chia lấy phần dư (modulus): là một phép toán số học để tìm ra số dư sau khi chia một số cho một số khác. Kết quả của phép chia lấy phần dư là số còn lại sau khi thực hiện phép chia nguyên. Ví dụ: 5 : 3 = 1 (dư 2)
5 % 3
# kết quả: 2
- Lũy thừa (exponentiation) là một cách viết gọn khi bạn muốn nhân một số với chính nó nhiều lần. Nó cho biết một số được nhân bao nhiêu lần với chính nó. Ví dụ: 2 ** 3, đọc là 2 lũy thừa 3, là lấy số 2 nhân 3 lần với chính nó. Trong đó 2 gọi là cơ số (số được nhân), 3 gọi là số mũ (số lần nhân). Kết quả: 2 ** 3 = 8.
2 ** 3
# kết quả: 8
6.3 Bài tập
Bài tập 6a. Anh Tèo được công ty Green thuê để trồng cây thông. Khu đất trồng thông có hình vuông. Anh Tèo đo một cạnh của khu đất có chiều dài 35 m. Giả sử tiền công trả cho việc trồng thông trên mỗi mét vuông đất là 50000VND. Vậy, anh Tèo được công ty Green trả bao nhiêu tiền. Lập trình bằng Python để giải bài tập.
Yêu cầu xuất ra màn hình kết quả (với x, y là các số):
Dien tich của khu dat la: xxx
So tien anh Teo duoc nhan la: yyy
Bài tập 6b. Một vệ tinh quay quanh Trái Đất và gửi dữ liệu về Trái Đất 3 lần mỗi giờ. Nếu mỗi lần gửi dữ liệu, tín hiệu phải đi qua khoảng cách 12000 km, hãy tính tổng khoảng cách tín hiệu đi được trong 2 giờ. Lập trình bằng Python để giải bài tập.
Yêu cầu xuất ra màn hình kết quả (với x, y là các số):
So lan ve tinh gui tin hieu trong 2 gio la: xxx
Tong khoang cach tin hieu di duoc la: yyy
Câu hỏi 6.1 Đâu là kí hiệu của phép toán lũy thừa trong Python?
A. ^
B. **
C. *
D. //
Câu hỏi 6.2 Đâu là kí của phép chia lấy dư trong Python?
A. %
B. **
C. //
D. /
Câu hỏi 6.3 Đâu là kí của phép chia lấy phần nguyên trong Python?
A. ^
B. %
C. //
D. /
Câu hỏi 6.4 Số nguyên trong Python gồm các số sau. Phát biểu nào không đúng?
A. Số thập phân (decimal): ví dụ 2.7
B. Số dương (positive integers): ví dụ 1, 2, 3,
C. Số âm (negative integers): ví dụ -1, -2, -3,
D. Số 0 (zero): 0
6. Integer Data Type
You have certainly used a handheld calculator to perform mathematical operations, such as addition, subtraction, multiplication, and division. A computer is a smarter device, so it can also perform such calculations.
Let’s use the Python language to instruct the computer to perform some arithmetic operations.
6.1 Arithmetic Operations
For simplicity, we will use Python’s interactive mode (direct command mode).
In the command prompt (CMD) window, type the command py (or python) to enter the command input mode. Alternatively, you can enter commands directly into the IDLE Shell window.
Enter the following commands and observe the results. You can recalculate them manually to check if the computer is correct.
Addition
3 + 5
Example:
Microsoft Windows [Version 10.0.19045.5608]
(c) Microsoft Corporation. All rights reserved.
C:\Users\Teo>py
Python 3.13.2 (tags/v3.13.2:4f8bb39, Feb 4 2025, 15:23:48) [MSC v.1942 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 3 + 5
8
Subtraction
10 - 4
# result: 6
Multiplication
3 * 5
# result: 15
Division
18 / 3
# result: 6.0
Now you know how to use the Python language to instruct a computer to perform basic operations: addition, subtraction, multiplication, and division. It's quite simple, isn't it?
If you observe closely, you will see that the result of the division operation is 6.0, which "appears" to be a decimal number, while the results of addition, subtraction, and multiplication are integers.
The reason for this phenomenon is that Python has two main types of numbers: integers (int) and floating-point numbers (often called float or real numbers in mathematics).
6.2 Integers
Mathematically, an integer is the set of numbers that have no fractional or decimal part. This set includes:
- Positive integers: e.g., 1, 2, 3, …
- Negative integers: e.g., -1, -2, -3, …
- Zero: 0
In mathematics, the set of integers is denoted by Z (from the German word "Zahl," meaning "number"). This set is a subset of the real numbers, but unlike real numbers, integers do not include decimal numbers (like 2.5) or irrational numbers (like sqrt(2)).
Characteristics of Integers:
- No fractional or decimal part
- Can be negative, positive, or zero
- Used to count discrete objects or represent changes (increase/decrease)
Integers in everyday life:
- Counting quantity: "I have 5 apples" (5 is a positive integer)
- Temperature: "The temperature is -3°C" (-3 is a negative integer)
- Position: "I am standing at Kilometer mark 0 of National Highway 1" (0 is zero/integer)
What is the Integer Data Type in Python?
In Python, the integer is a fundamental data type used to represent whole numbers (numbers without a fractional part). This includes:
- Positive integers: 1, 2, 3, …
- Negative integers: -1, -2, -3, …
- Zero: 0
The integer data type in Python is denoted as int. It belongs to the group of numeric data types, along with float (floating-point numbers) and complex (complex numbers).
Key Features of the int Type in Python
[1] Arbitrary-Precision (Unlimited Size)
- Unlike many other programming languages (like C or Java) which limit integer size (32-bit, 64-bit), the Python int type can represent integers of virtually any size, limited only by the computer's available memory
- This is achieved through Python's dynamic memory allocation
[2] No Distinction between int, long, or short
- Python does not distinguish between int, long, or short as C/C++ does. All integers are simply int, and Python automatically adjusts the size according to the value.
[3] Supports Basic Arithmetic Operations
- Addition (+), subtraction (-), multiplication (*), floor division (//), modulus (%), and exponentiation (**)
Declaration
- You simply need to enter a number without a decimal part, or assign a whole number value to a variable, and Python will automatically recognize it as int
- Explicit data type declaration is not required
Usage
In the first part of the lesson, you used addition, subtraction, multiplication, and division on integers.
In this section, let's explore a few more operations.
Floor Division: This is a division operation that only returns the integer part of the result, discarding the fractional part. Example: 5 : 3 = 1.666, we only take the integer part, which is 1; we discard the decimal part, .666.
5 // 3
# result: 1
Modulus (Remainder): This is an arithmetic operation used to find the remainder after dividing one number by another. The result of the modulus operation is the leftover amount after performing the integer division. Example: 5 : 3 = 1 (remainder 2).
5 % 3
# result: 2
Exponentiation: This is a concise way to write when you want to multiply a number by itself multiple times. It indicates how many times a number is multiplied by itself. Example: 2 ** 3 is read as 2 to the power of 3, meaning the number 2 is multiplied by itself 3 times. Here, 2 is called the base (the number being multiplied), and 3 is called the exponent (the number of times it is multiplied). Result: 2^3 = 8.
2 ** 3
# result: 8
6.3 Exercises
Exercise 6a. Mr. Teo is hired by Green company to plant pine trees. The plot of land for planting is square-shaped. Mr. Teo measures one side of the plot to be 35 meters long. Assume the labor cost for planting pine trees is 50,000 VND per square meter of land. How much money will Mr. Teo be paid by the Green company? Program the solution using Python.
Requirement is to output the result to the screen (where x and y are numbers):
Dien tich cua khu dat la: xxx
So tien anh Teo duoc nhan la: yyy
Exercise 6b. A satellite orbits the Earth and sends data back to Earth 3 times every hour. If the signal has to travel a distance of 12,000 km each time data is sent, calculate the total distance the signal travels in 2 hours. Program the solution using Python.
Requirement is to output the result to the screen (where x and y are numbers):
So lan ve tinh gui tin hieu trong 2 gio la: xxx
Tong khoang cach tin hieu di duoc la: yyy
Question 6.1 Which symbol represents the exponentiation operator in Python?
A. ^
B. **
C. *
D. //
Question 6.2 Which symbol represents the modulus (remainder) operator in Python?
A. %
B. **
C. //
D. /
Question 6.3 Which symbol represents the floor division operator in Python?
A. ^
B. %
C. //
D. /
Question 6.4 The integer type in Python includes the following numbers. Which statement is incorrect?
A. Decimal numbers: e.g., 2.7
B. Positive integers: e.g., 1, 2, 3, ...
C. Negative integers: e.g., -1, -2, -3, ...
D. Zero: 0