Python Programming - Variables
- Variables - General Questions
For example:
a, b, c = 1, 2, 3
This statement assigns the values 1, 2, and 3 to the variables a, b, and c, respectively.
You can also assign the same value to multiple variables in one line:
a = b = c = "Orange"
This statement assigns the value "Orange" to the variables a, b, and c.
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. For example:
fruits = ["apple", "banana", "cherry"]
a, b, c = fruits
This statement extracts the values "apple", "banana", and "cherry" from the list fruits and assigns them to the variables a, b, and c, respectively.
x = 10
y = 5
x, y = y, x
print(x, y)In this code, two variables x and y are assigned the values 10 and 5 respectively.
The third line swaps the values of the variables using the tuple packing and unpacking technique.
When the variables are printed to the console, the output is 5 10.
Global variables are defined outside of any function, and can be accessed and modified from anywhere in the code.
However, it's generally not recommended to use global variables extensively, as they can make the code harder to understand and debug.
my_dict = {'a': 1, 'b': 2, 'c': 3}
del my_dict['b']
print(my_dict)In this code, a dictionary my_dict is defined with three key-value pairs.
The second line uses the del statement to remove the key-value pair with the key 'b' from the dictionary.
When the dictionary is printed to the console, it shows the modified dictionary {'a': 1, 'c': 3}.