Like other programming languages, in python the variable declaration having certain rules and regulations.
The variables are very short name like x and y or descriptive names like student_age, car_price etc.
So, some common rules follow while declaring the variables in python.
A variable name must start with a letter( a-z, A-Z) or underscore character ( _ ).
A variable name can’t start with a number.
A variable name can only be a alpha numeric characters and underscores (A-z, 0-9, and _ ).
Generally variables are case-sensitive like age, Age and AGE these three variables are different.
Because each variables play different role in python syntax.
Examples Of Python Legal Variable Names:
myvar = "Rahul" my_var = "Rahul" _my_var = "Rahul" myVar = "Rahul" MYVAR = "Rahul" myvar2 = "Rahul" print(myvar) print(my_var) print(_my_var) print(myVar) print(MYVAR) print(myvar2)
The output will be,
Rahul Rahul Rahul Rahul Rahul Rahul
Some Illegal variable declaration are:
2myvar = "Rahul" my-var = "Rahul" my var = "Rahul"
This program produces an error in this code,
Traceback (most recent call last): File "/usr/lib/python3.7/py_compile.py", line 143, in compile _optimize=optimize) File "<frozen importlib._bootstrap_external>", line 791, in source_to_code File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "./prog.py", line 1 2myvar = "John" ^ SyntaxError: invalid syntax During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<string>", line 1, in <module> File "/usr/lib/python3.7/py_compile.py", line 147, in compile raise py_exc py_compile.PyCompileError: File "./prog.py", line 1 2myvar = "John" ^ SyntaxError: invalid syntax
In Python variable names are case-sensitive.
Python Multi Words Variable Names:
If variable name is small it easy to read but big it difficult to read.
There are several techniques to read the variable very easily. Like Camel case, Pascal Case, Snake Case.
Each word, except the first, starts with a capital letter:
myVariableName = "Rahul"
Each word starts with a capital letter:
MyVariableName = "Rahul"
Each word is separated by an underscore character:
my_variable_name = "John"