9. Biến (tiếp)
Ở bài học trước bạn đã biết được:
- Biến là một vùng nhớ được đặt tên
- Trong Python, chỉ việc đặt tên biến, gán giá trị là có thể sử dụng, không phải khai báo biến
- Đặt tên biến có ngữ nghĩa
Trong bài học này, chúng ta cùng tìm hiểu thêm một số chủ đề liên quan tới biến.
9.1 Gán nhiều giá trị
Gán nhiều giá trị cho nhiều biến
Với Python, bạn có thể gán nhiều giá trị cho nhiều biến trên một hàng.
Ví dụ:
x, y, z = "Orange", "Bannan", "Cherry"
print(x)
print(y)
print(z)
Lưu ý: số biến phải tương ứng với số giá trị, nếu không Python sẽ báo lỗi.
Gán 1 giá trị cho nhiều biến
Bạn có thể gán một giá trị cho nhiều biến trên một dòng lệnh.
Ví dụ:
x = y = z = "Orange"
print(x)
print(y)
print(z)
Phân rã một mảng (dãy)
Nếu bạn có một nhóm gồm nhiều giá trị trong một danh sách (list), một bộ (tuple). Bạn có thể phân rã các giá trị đó vào các biến rời nhau. Quá trình này gọi là quá trình phân rã.
Ví dụ:
Phân rã một danh sách:
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
9.2 Xuất giá trị của biến
Sử dụng hàm print() để xuất giá trị của các biến.
Ví dụ
x = "Python is awesome"
print(x)
Để xuất giá trị của nhiều biến, trong hàm print(), sử dụng dấu phẩy (,) để phân cách giữa các biến.
Ví dụ:
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
Bạn cũng có thể sử dụng toán tử cộng (+) để xuất nhiều biến cùng lúc.
Ví dụ:
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
Lưu ý: bạn nhớ thêm khoảng trắng sau chữ "Python " và "is ", nếu không có, kết quả xuất ra sẽ như thế này "Pythonisawesome".
Đối với kiểu dữ liệu số, dấu cộng (+) sẽ được Python hiểu là một toán tử số học, là phép tính cộng.
Ví dụ:
x = 5
y = 10
print(x + y)
Trong hàm print(), khi bạn dùng dấu cộng (+) để cộng một số và một chuỗi, Python sẽ thông báo lỗi. Vì không thể thực hiện phép cộng giữa một chuỗi và một số.
Ví dụ:
x = 5
y = "John"
print(x + y)
Cách tốt nhất để xuất nhiều loại giá trị trong hàm print() là sử dụng dấu phẩy (,) để ngăn cách giữa các biến.
Ví dụ:
x = 5
y = "John"
print(x, y)
9.3 Định danh của biến
Như ở bài học trước đã đề cập, biến là một thùng chứa, được gắn tên, dùng để chứa số, chứa thông tin.
Ví dụ, bạn lập trình, và chạy đoạn mã sau:
hoTen = "Nguyen Van Teo"
print(hoTen) // Nguyen Van Teo
Tuy nhiên, trong Python, biến không “chứa” số, “chứa” thông tin theo nghĩa đen. Nghĩa là, trong biến hoTen không chứa chuỗi "Nguyen Van Teo". Mà biến hoTen sẽ chứa định danh của chuỗi "Nguyen Van Teo".
Định danh là gì?
Bạn có thể hiểu, định danh (identity) là địa chỉ duy nhất của đối tượng (giá trị) mà biến đó đang tham chiếu (trỏ) tới trong bộ nhớ máy tính.
Vậy định danh của chuỗi "Nguyen Van Teo" là gì?
Sử dụng hàm id(ten_bien) để xuất ra định danh.
print(id(hoTen)
// 2553555729520
// (Kết quả xuất id() trên máy bạn có thể khác)
Định danh của biến hoTen là 2553555729520, đây là một vị trí duy nhất trên bộ nhớ máy tính (RAM)
Tóm lại, trong Python:
- Biến là một tên gọi, trỏ tới một đối tượng trong bộ nhớ của máy tính (gọi là RAM)
- Đối tượng là số, chuỗi, danh sách, hàm. Mỗi đối tượng được lưu trữ ở một vị trí cụ thể trên bộ nhớ RAM
- Vị trí duy nhất (địa chỉ) của một đối tượng được gọi là định danh của đối tượng
Bạn lập trình và chạy đoạn mã sau, để hiểu hơn về định danh trong Python:
a = 10 # a trỏ đến đối tượng số 10
b = a # b cũng trỏ đến cùng đối tượng số 10
print(id(a)) # 140721721419160
print(id(b)) # 140721721419160 (cùng địa chỉ)
a = 20 # a bây giờ trỏ đến đối tượng số 20 (đối tượng 10 vẫn còn)
print(id(a)) # 140721721419480 (địa chỉ khác)
print(id(b)) # 140721721419160 (b vẫn trỏ đến đối tượng số 10 ban đầu)
9.4 Bài tập
Bài tập 9a. Gán và in giá trị
Mục tiêu: củng cố cách gán nhiều giá trị cho nhiều biến và sử dụng hàm print() để xuất kết quả.
Yêu cầu:
- Viết một dòng lệnh duy nhất để gán ba giá trị: "Môn học", "Lớp", và "Trường" cho ba biến lần lượt là subject, grade, và school. Bạn thay thế Môn học, Lớp và Trường là thông tin của chính bạn.
- Sau đó, sử dụng một câu lệnh print() duy nhất với dấu phẩy (,) để xuất ra màn hình một câu có dạng: "Tôi học [Môn học] ở lớp [Lớp] tại trường [Trường]."
Gợi ý:
- Sử dụng cú pháp gán nhiều giá trị: biến1, biến2, biến3 = giá trị1, giá trị2, giá trị3.
- Sử dụng print() với dấu phẩy để nối chuỗi và biến.
Bài tập 9b: Phân rã mảng và tính toán
Mục tiêu: thực hành phân rã một danh sách và kết hợp với phép toán số học.
Yêu cầu:
1. Tạo một danh sách có tên scores chứa ba điểm số: 9, 8, 10
2. Phân rã danh sách scores này vào ba biến riêng biệt, lần lượt là score1, score2, và score3
3. Viết một dòng lệnh để tính tổng ba điểm số đó
4. Sử dụng hàm print() để xuất ra màn hình một câu có dạng: "Tổng điểm của bạn là [Tổng điểm]"
5. Cho biết id của các biến scores, score1, score2, score3
Gợi ý:
- Sử dụng cú pháp phân rã mảng: biến1, biến2, biến3 = tên_mảng
- Sử dụng toán tử + để cộng các biến số
- sử dụng hàm id() để biết được id của các biến
Bài tập 9c: Củng cố việc sử dụng dấu phẩy và dấu cộng trong hàm print()
Mục tiêu: Phân biệt rõ ràng cách sử dụng dấu phẩy (,) và dấu cộng (+) khi kết hợp chuỗi và số trong hàm print().
Yêu cầu:
1. Tạo một biến name có giá trị là tên của bạn (ví dụ: "An")
2. Tạo một biến age có giá trị là tuổi của bạn (ví dụ: 13)
3. Viết hai câu lệnh print() khác nhau để xuất ra cùng một kết quả trên màn hình:
- Sử dụng dấu phẩy (,)
- Sử dụng dấu cộng (+)
4. Giải thích tại sao cách dùng dấu phẩy (,) thường được khuyên dùng hơn khi kết hợp chuỗi và số.
Gợi ý:
- Với dấu cộng, bạn phải chuyển đổi kiểu dữ liệu của biến age sang chuỗi bằng hàm str(): str(age)
- Nhắc lại kiến thức trong bài học: dấu cộng là toán tử số học, không thể dùng để cộng trực tiếp một số và một chuỗi
Câu hỏi ôn tập
Câu hỏi 9.1 Dòng lệnh nào đúng cú pháp, để gán giá trị 'Hello World' cho 3 biến trong một câu lệnh?
A. x, y, z = 'Hello World'
B. x = y = z = 'Hello World'
C. x|y|z = 'Hello World'
D. 'x' = 'y' = 'z' = 'Hello World'
Câu hỏi 9.2 Dòng mã nào sau đây đúng cú pháp, để gán nhiều giá trị cho nhiều biến?
A. x, y, z = "Orange", "Banana", "Cherry"
B. x = y = z = "Orange", "Banana", "Cherry"
C. x|y|z = "Orange", "Banana", "Cherry"
D. 'x' = 'y' = 'z' = "Orange", "Banana", "Cherry"
Câu hỏi 9.3 Quan sát đoạn mã sau:
fruits = ['apple',
'banana', 'cherry']
a, b, c = fruits
print(a)
Kết quả khi xuất biến a là gì?
A. apple
B. banana
C. cherry
D. True
Câu hỏi 9.4 Quan sát đoạn mã sau:
print('Hello', 'World')
Kết quả xuất ra màn hình là gì?
A. Hello, World
B. Hello World
C. HelloWorld
D. 'Hello', 'World'
Câu hỏi 9.5 Quan sát đoạn mã sau:
a = 'Hello'
b = 'World'
print(a + b)
Kết quả xuất ra màn hình là gì?
A. a + b
B. Hello World
C. HelloWorld
D. 'Hello''World'
Câu hỏi 9.6 Quan sát đoạn mã sau:
a = 4
b = 5
print(a + b)
Kết quả xuất ra màn hình là gì?
A. 45
B. 9
C. 4 + 5
D. Error
Đây là bản dịch sang tiếng Anh (ngôn ngữ lập trình chuẩn) cho bài học về biến trong Python.
9. Variables (Cont)
In the previous lesson, you learned that:
- A variable is a named storage location
- In Python, you can use a variable simply by naming it and assigning a value, without needing to declare it first
- Variable names should be semantic (meaningful)
In this lesson, we will explore some more topics related to variables.
9.1 Assigning multiple values
Assigning multiple values to multiple variables
In Python, you can assign multiple values to multiple variables on a single line.
Example:
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
Note: The number of variables must correspond to the number of values; otherwise, Python will raise an error.
Assigning one value to multiple variables
You can assign a single value to multiple variables in one statement.
Example:
x = y = z = "Orange"
print(x)
print(y)
print(z)
Unpacking a collection (array/sequence)
If you have a collection of values in a list, a tuple, or another sequence, you can extract those values into separate variables. This process is called unpacking.
Example: Unpacking a list:
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits # Unpacks the list into the three variables
print(x)
print(y)
print(z)
9.2 Outputting variable values
Use the print() function to display the values of variables.
Example:
x = "Python is awesome"
print(x)
To output the values of multiple variables using the print() function, use a comma (,) to separate the variables.
Example:
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
You can also use the plus operator (+) to output multiple variables simultaneously.
Example:
x = "Python "
y = "is "
z = "awesome"
print(x + y + z) # String concatenation
Note: Remember to add a space after "Python " and "is ". If you don't, the resulting output will be "Pythonisawesome".
For numeric data types, the plus operator (+) is interpreted by Python as an arithmetic operator (addition).
Example:
x = 5
y = 10
print(x + y) # Output: 15
In the print() function, when you use the plus operator (+) to combine a number and a string, Python will raise an error. This is because addition cannot be performed between a string and a number (non-string types must be explicitly converted).
Example (Error):
x = 5
y = "John"
print(x + y) # This will cause a TypeError
The best way to output multiple types of values in the print() function is to use the comma (,) to separate the variables.
Example (Recommended):
x = 5
y = "John"
print(x, y) # Output: 5 John (The comma automatically inserts a space)
9.3 Variable identity
As mentioned in the previous lesson, a variable is a named container used to hold numbers or information.
For example, when you run this code:
name = "Nguyen Van Teo"
print(name) # Output: Nguyen Van Teo
However, in Python, a variable doesn't literally "contain" the value. The variable name does not hold the string "Nguyen Van Teo". Instead, the variable name holds the identity of the string object "Nguyen Van Teo".
What is Identity?
You can understand identity as the unique address of the object (value) that the variable is referencing (pointing to) in the computer's memory.
So, what is the identity of the string "Nguyen Van Teo"?
Use the built-in function id(variable_name) to output the identity.
print(id(name))
# Example Output: 2553555729520
# (The id() result on your machine may differ)
The identity of the variable name is 2553555729520; this is a unique location in the computer's memory (RAM).
In summary, in Python:
- A variable is a name that points to an object in the computer's memory (RAM)
- An object is the value (number, string, list, function, etc.). Each object is stored at a specific location in RAM
- The unique location (address) of an object is called its identity
Run the following code to better understand identity in Python:
a = 10 # 'a' points to the integer object 10
b = a # 'b' also points to the SAME integer object 10
print(id(a)) # Example: 140721721419160
print(id(b)) # Example: 140721721419160 (Same address)
a = 20 # 'a' now points to the new integer object 20 (The object 10 still exists)
print(id(a)) # Example: 140721721419480 (Different address)
print(id(b)) # Example: 140721721419160 ('b' still points to the original object 10)
9.4 Exercises
Exercise 9a. Assignment and printing values
Objective: Reinforce the practice of assigning multiple values to multiple variables and using the print() function for output.
Requirements:
- Write a single line of code to assign three values: "Subject name", "Grade level", and "School name" to the three variables subject, grade, and school, respectively. (Replace "Subject name," "Grade level," and "School name" with your actual information)
- Then, use a single print() statement with commas (,) to output a sentence in the format: "I study [Subject name] in grade [Grade level] at [School name]."
Hints:
- Use the multiple assignment syntax: var1, var2, var3 = val1, val2, val3
- Use print() with commas to combine strings and variables
Exercise 9b: Array unpacking and calculation
Objective: Practice unpacking a list and combining it with arithmetic operations.
Requirements:
- Create a list named scores containing three scores: 9, 8, and 10
- Unpack this scores list into three separate variables, named score1, score2, and score3, respectively
- Write a single line of code to calculate the sum of the three scores
- Use the print() function to output a sentence in the format: "Your total score is [Total Score]"
- Print the id of the variables: scores, score1, score2, and score3.
Hints:
- Use the array unpacking syntax: var1, var2, var3 = array_name
- Use the + operator to add the numeric variables
- Use the id() function to get the identity of the variables
Exercise 9c: Reinforcing the use of comma vs. plus in print()
Objective: Clearly distinguish between using the comma (,) and the plus operator (+) when combining strings and numbers in the print() function.
Requirements:
- Create a variable name with your name as the value (e.g., "An")
- Create a variable age with your age as the value (e.g., 13)
- Write two different print() statements to output the exact same result on the screen (e.g., "An 13"):
+ Using the comma (,)
+ Using the plus operator (+)
- Explain why using the comma (,) is generally recommended when combining strings and numbers
Hints:
- With the plus operator, you must convert the data type of the age variable to a string using the str() function: str(age)
- Recall from the lesson: the plus operator is an arithmetic operator and cannot directly add a number and a string (it requires both operands to be strings for concatenation)
Review Questions
Question 9.1 Which command line correctly assigns the value 'Hello World' to 3 variables in a single statement?
A. x, y, z = 'Hello World'
B. x = y = z = 'Hello World'
C. x|y|z = 'Hello World'
D. 'x' = 'y' = 'z' = 'Hello World'
Question 9.2 Which code line below correctly assigns multiple values to multiple variables?
A. x, y, z = "Orange", "Banana", "Cherry"
B. x = y = z = "Orange", "Banana", "Cherry"
C. x|y|z = "Orange", "Banana", "Cherry"
D. 'x' = 'y' = 'z' = "Orange", "Banana", "Cherry"
Question 9.3 Observe the following code snippet:
fruits = ['apple', 'banana', 'cherry']
a, b, c = fruits
print(a)
What is the result when variable a is outputted?
A. apple
B. banana
C. cherry
D. True
Question 9.4 Observe the following code snippet:
print('Hello', 'World')
What is the result outputted to the screen?
A. Hello, World
B. Hello World
C. HelloWorld
D. 'Hello', 'World'
Question 9.5 Observe the following code snippet:
a = 'Hello'
b = 'World'
print(a + b)
What is the result outputted to the screen?
A. a + b
B. Hello World
C. HelloWorld
D. 'Hello''World'
Question 9.6 Observe the following code snippet:
a = 4
b = 5
print(a + b)
What is the result outputted to the screen?
A. 45
B. 9
C. 4 + 5
D. Error