A variable is a name used to store data in a Python program. The value stored in a variable can be a number, text, decimal value, Boolean value, or other types of data.
A variable is a named location used to store a value in memory. For example:
name = "Rahul"
age = 20
Here, name and age are variables.
In Python, a variable is created when you assign a value to it using the assignment operator =.
x = 10
name = "Amit"
price = 99.50
The = operator is used to assign a value to a variable.
age = 25
This means that the value 25 is assigned to the variable age.
name = "Rahul"
city = "Patna"
marks = 85
The value of a variable can be changed during program execution.
age = 20
age = 25
print(age)
A Python variable can store different types of values.
name = "Amit"
age = 21
height = 5.8
is_student = True
Here:
A variable can store text using single or double quotation marks.
name = "Rahul"
print(name)
An integer variable stores a whole number without a decimal point.
age = 25
marks = 90
print(age)
print(marks)
A float variable stores a number containing a decimal point.
price = 99.50
height = 5.8
print(price)
print(height)
A Boolean variable can contain either True or False.
is_student = True
is_teacher = False
print(is_student)
print(is_teacher)
The type() function is used to find the data type of a variable.
age = 25
print(type(age))
Another example:
name = "Rahul"
print(type(name))
Python allows you to create multiple variables in a single program.
name = "Amit"
age = 22
city = "Patna"
print(name)
print(age)
print(city)
You can assign values to multiple variables in one statement.
x, y, z = 10, 20, 30
print(x)
print(y)
print(z)
The same value can be assigned to multiple variables.
x = y = z = 100
print(x)
print(y)
print(z)
Python has some rules for naming variables:
Valid examples:
name = "Rahul"
age1 = 20
student_name = "Amit"
_total = 500
The following variable names are invalid:
1name = "Rahul"
student-name = "Amit"
class = 10
These names are invalid because they either start with a number, contain an invalid character, or use a Python keyword.
Python variable names are case-sensitive. This means uppercase and lowercase letters are treated differently.
name = "Rahul"
Name = "Amit"
print(name)
print(Name)
Here, name and Name are two different variables.
Variables can be used in mathematical calculations.
a = 10
b = 20
sum = a + b
print(sum)
Variables make programs easier to understand and modify.
Variables can also be used with strings.
first_name = "Rahul"
last_name = "Kumar"
full_name = first_name + " " + last_name
print(full_name)
name = "Rahul"
age = 20
marks = 85.5
is_student = True
print("Name:", name)
print("Age:", age)
print("Marks:", marks)
print("Student:", is_student)
Question: Which symbol is used to assign a value to a variable in Python?