Variables are one of the most fundamental concepts in Python programming. A variable is used to store data or information that can be used and modified later in a program. It acts like a container that holds values such as numbers, text, or other data types.
Understanding how to create variables and follow proper naming rules is essential for writing clean and error free code.
WHAT IS A VARIABLE
A variable is created when you assign a value to a name using the equals sign.
Example:
x = 10
name = “Ali”
price = 99.99
In the examples above, x, name, and price are variables that store different types of data.
Python automatically detects the data type of the variable based on the assigned value, so you do not need to declare the type separately.
RULES FOR NAMING VARIABLES
When creating variables in Python, you must follow specific naming rules.
A variable name must start with a letter or an underscore.
A variable name cannot start with a number.
A variable name can contain letters, numbers, and underscores.
A variable name cannot contain spaces.
A variable name cannot use special symbols such as @, #, or %.
Python keywords such as if, for, while, and class cannot be used as variable names.
Correct examples:
age = 25
user_name = “Hira”
totalMarks = 450
Incorrect examples:
1name = “Ali”
user-name = “Sara”
for = 10
CASE SENSITIVITY IN VARIABLES
Python is case sensitive. This means that uppercase and lowercase letters are treated differently.
Example:
Name = “Ali”
name = “Sara”
These are two different variables.
BEST PRACTICES FOR VARIABLE NAMES
Use meaningful names that describe the purpose of the variable.
Use lowercase letters with underscores for better readability.
Avoid very short names unless used in simple loops.
Keep names simple and clear.
Example:
student_name = “Ahmed”
total_marks = 500
Using proper variable names makes your code easier to read, understand, and maintain.
WHY VARIABLES ARE IMPORTANT
Variables allow you to store and manage data dynamically in your programs. They help in performing calculations, processing user input, and building real world applications.
Mastering variables and naming rules is an important step toward becoming a confident Python programmer.