Bài trước: Python thực hành (8) - Làm việc với biến
-----
4. Python Variables
(cont)
4.1 Assign Multiple Values
Many Values to Multiple Variables
Python allows you to assign values to multiple variables in one line:
Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
Note: Make sure the number of variables matches the number of values, or else you will get an error.
One Value to Multiple Variables
And you can assign the same value to multiple variables in one line:
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)
Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to extract the values into variables. This is called unpacking.
Example
Unpack a list:
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
4.2 Output Variables
The Python print() function is often used to output variables.
Example
x = "Python is awesome"
print(x)
In the print() function, you output multiple variables, separated by a comma:
Example
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
You can also use the + operator to output multiple variables:
Example
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
Notice the space character after "Python " and "is ", without them the result would be "Pythonisawesome".
For numbers, the + character works as a mathematical operator:
Example
x = 5
y = 10
print(x + y)
In the print() function, when you try to combine a string and a number with the + operator, Python will give you an error:
Example
x = 5
y = "John"
print(x + y)
The best way to output multiple variables in the print() function is to separate them with commas, which even support different data types:
Example
x = 5
y = "John"
print(x, y)
4.3 Exercise
1. What is the correct syntax to add the value 'Hello World' to 3 variables in one 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'
2. What is the correct syntax to assign values to multiple variables in one line?
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"
3. Consider the following code:
fruits = ['apple', 'banana', 'cherry']
a, b, c = fruits
print(a)
What will be the result of a?
A. apple
B. banana
C. cherry
D. True
4. Consider the following code:
print('Hello', 'World')
What will be the printed result?
A. Hello, World
B. Hello World
C. HelloWorld
D. 'Hello', 'World'
5. Consider the following code:
a = 'Hello'
b = 'World'
print(a + b)
What will be the printed result?
A. a + b
B. Hello World
C. HelloWorld
D. 'Hello''World'
6. Consider the following code:
a = 4
b = 5
print(a + b)
What will be the printed result?
A. 45
B. 9
C. 4 + 5
D. Error
-----
Bài sau: