Mastering Python: Day 3
Efficient Variable Assignments and Unpacking Techniques
Assigning Multiple Values to Multiple Variables
Python allows you to assign values to multiple variables in one line:
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
Assigning One Value to Multiple Variables
You can also assign the same value to multiple variables in one line:
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)
Unpacking 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)
Python - Output Variables
In Python, you can output variables using the print()
function. Here's an example:
VerifyOpen In EditorEditCopy code1x = 5
2y = "Hello, World!"
3
4print(x) # Output: 5
5print(y) # Output: Hello, World!
In this example, we assign the value 5
to the variable x
and the string "Hello, World!"
to the variable y
. Then, we use the print()
function to output the values of these variables.
If you want to output multiple variables at once, you can separate them with commas:
VerifyOpen In EditorEditCopy code1x = 5
2y = "Hello, World!"
3
4print(x, y) # Output: 5 Hello, World!
Alternatively, you can use string formatting to output variables in a more readable format. For example:
VerifyOpen In EditorEditCopy code1x = 5
2y = "Hello, World!"
3
4print("The value of x is {} and the value of y is {}".format(x, y))
5# Output: The value of x is 5 and the value of y is Hello, World!
Or, in Python 3.6 and later, you can use f-strings:
VerifyOpen In EditorEditCopy code1x = 5
2y = "Hello, World!"
3
4print(f"The value of x is {x} and the value of y is {y}")
5# Output: The value of x is 5 and the value of y is Hello, World!