Table of Contents
ToggleVariables are containers for storing data values. In Python, you don’t need to declare a variable explicitly.
A variable is created as soon as you assign a value to it.
Python does not require a special command to declare a variable. The variable is created at the moment a value is assigned.
x = 5
y = "John"
print(x)
print(y)
Output:
5
John
In Python, variables are not bound to a specific type. They can change their type dynamically during runtime.
x = 4 # x is an integer
x = "Sally" # x is now a string
print(x)
Output:
Sally
You can specify the type of a variable using casting, which explicitly defines its data type.
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Output:
x = '3'
y = 3
z = 3.0
Use the type() function to find the data type of a variable.
x = 5
y = "John"
print(type(x))
print(type(y))
Output:
<class 'int'>
<class 'str'>
String variables can be declared using either single quotes or double quotes. Both methods are valid and interchangeable.
x = "John"
y = 'John'
print(x)
print(y)
Output:
John
John
Python variable names are case-sensitive. Variables with the same name but different capitalization are treated as separate variables.
a = 4
A = "Sally"
print(a)
print(A)
Output:
4
Sally
