In Python, a variable is a named storage location that holds a value. A variable is created when a value is assigned to it using the assignment operator “=”.
Python variables are dynamically typed, which means that the data type of a variable is inferred at runtime based on the value that is assigned to it. This means that a variable can be assigned a value of any data type, such as integer, float, string, boolean, etc.
Here’s an example of creating a variable in Python:
age = 25
In this example, the variable “age” is assigned the value of 25. This means that the value of the variable can be accessed and manipulated later in the program.
Python also allows multiple assignments in a single line, as shown in the example below:
x, y, z = 1, 2.5, "Hello"
In this example, three variables are assigned values in a single line. The first variable “x” is assigned the value of 1, the second variable “y” is assigned the value of 2.5 (a float), and the third variable “z” is assigned the string “Hello”.
# Assigning values to variables
name = "Alice"
age = 25
height = 1.65
# Printing the values of variables
print("Name:", name)
print("Age:", age)
print("Height:", height)
# Updating the value of a variable
age = 26
# Printing the updated value of the variable
print("Updated age:", age)
In this example, we create three variables “name”, “age”, and “height” and assign them values. We then print the values of the variables using the print() function.
Next, we update the value of the “age” variable by assigning it a new value of 26. Finally, we print the updated value of the “age” variable.