In Python, a variable is a named reference to a value that can be stored in memory. Variables are created when a value is assigned to them using the equal sign (=) operator, and they can be used to store and manipulate data in a program. Python is dynamically typed. The type of variable is determined at runtime based on the value assigned to it.
Variable names in Python can contain letters, digits, and underscores but cannot begin with a digit. They are case-sensitive, so "my_variable" and "My_Variable" are considered two different variables. Python also has reserved keywords that cannot be used as variable names, such as "if," "while," and "for."
To assign a value to a variable, you can use the equal sign (=) operator. For example, to assign the value 5 to a variable named "x," you can write:
x = 5
After executing this statement, the variable "x" will contain the value 5.
You can also assign the result of an expression to a variable like this:
y = 2 * x + 1
In this case, the expression "2 * x + 1" is evaluated first, and the result is then assigned to the variable "y."
You can also update the value of a variable by assigning a new value to it:
x = 10
x = x + 1
In this example, the value of "x" is first set to 10 and then incremented by 1.
From arithmetic to logical — understand every operator that powers Python! Read more on our blog.
Python is dynamically typed, which means that the type of a variable is determined at runtime based on the value assigned to it. This means that you can change the variable type by assigning a different type of value to it. For example, you can assign an integer to a variable and then later assign a string to the same variable:
x = 5
x = "hello"
However, this can make your code harder to read and debug, so it is generally a good practice to use variables of consistent types throughout your program.
Code exercise with a solution
Exercise: Create two variables, "x" and "y", and assign them the values 5 and 3, respectively. Compute the sum, difference, product, and quotient of the two variables, and print the results.
Solution:
x = 5
y = 3
sum = x + y
diff = x - y
prod = x * y
quot = x / y
print("The sum of x and y is", sum)
print("The difference of x and y is", diff)
print("The product of x and y is", prod)
print("The quotient of x and y is", quot)
Output:
The sum of x and y is 8
The difference of x and y is 2
The product of x and y is 15
The quotient of x and y is 1.6666666666666667
In this solution, we create two variables, "x" and "y" and assign them the values 5 and 3, respectively. We then compute the sum, difference, product, and quotient of the two variables and store them in variables with corresponding names. Finally, we print out the results using the print() function.
Elevate your Python skills with our Python Training program at TrainingHub.io!
Suggested blogs
Recent blogs
31 January 2026
|