Member-only story
A variable in Python
A variable in Python is a symbolic name that is a reference or pointer to an object. Once an object is assigned to a variable, you can refer to the object by that name. Variables in Python are created by assigning a value to a name; they don’t need to be declared explicitly. The variable is created the moment you first assign a value to it.
Example 1: Basic Variable Assignment
Let’s demonstrate a basic example of variable assignment and usage in Python:
# Assigning values to variables
my_number = 42
my_string = "Hello, world!"
# Using the variables
print(my_number) # Output: 42
print(my_string) # Output: Hello, world!
# Variables can be re-assigned to different values and types
my_number = "forty-two"
print(my_number) # Output: forty-two
In this example, my_number
is initially an integer with a value of 42. Later, my_number
is reassigned a string value "forty-two". This demonstrates Python's dynamic typing, where you don't need to explicitly declare a variable's type.
Example 2: Variables as Pointers
Variables in Python act as pointers to objects rather than holding data themselves. This can be illustrated when working with mutable objects like lists:
original_list = [1, 2, 3]
new_list = original_list
#…