In Python (programming language), a variable is used to store data or values that can be used later in a program. Variables act as containers that hold information such as numbers, text, or lists.
Python makes working with variables easy because you do not need to declare the data type explicitly.
π Creating Variables
In Python, a variable is created when you assign a value to it using the assignment operator (=).
Example:
name = "John"
age = 25
price = 19.99
Here:
namestores a stringagestores an integerpricestores a floating-point number
π¨ Example Program Using Variables
name = "Alice"
age = 22
print(name)
print(age)
Output:
Alice
22
π Changing Variable Values
The value of a variable can be changed during program execution.
Example:
x = 10
x = 20
print(x)
Output:
20
π¦ Multiple Variables
You can assign values to multiple variables in one line.
x, y, z = 5, 10, 15
print(x, y, z)
π Assigning One Value to Multiple Variables
x = y = z = 100
print(x, y, z)
π Rules for Naming Variables
When creating variables in Python, follow these rules:
β Variable names:
- Must start with a letter or underscore
- Can contain letters, numbers, and underscores
- Are case-sensitive
Examples:
name
age
_total
student_marks
β Invalid variable names:
2name
my-name
class
β Good Naming Practices
Use meaningful variable names to make code easier to understand.
Example:
student_name = "Rahul"
total_marks = 85
Instead of:
a = "Rahul"
b = 85
π Key Points
- Variables store data in a program.
- Python automatically determines the data type.
- Variables are created when a value is assigned.
- Variable names should be meaningful and follow naming rules.